diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/src/main/java/jannovar/Jannovar.java b/src/main/java/jannovar/Jannovar.java index 6afede3d..9c6cb4ed 100644 --- a/src/main/java/jannovar/Jannovar.java +++ b/src/main/java/jannovar/Jannovar.java @@ -1,761 +1,762 @@ package jannovar; /** Command line functions from apache */ import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.Parser; import java.io.IOException; import java.io.File; import java.io.FileWriter; import java.io.BufferedWriter; import java.io.Writer; import java.util.ArrayList; import java.util.HashMap; import jannovar.annotation.Annotation; import jannovar.annotation.AnnotationList; import jannovar.common.Constants; import jannovar.common.Constants.Release; import jannovar.exception.AnnotationException; import jannovar.exception.FileDownloadException; import jannovar.exception.InvalidAttributException; import jannovar.exception.JannovarException; import jannovar.exception.VCFParseException; import jannovar.exome.Variant; import jannovar.io.EnsemblFastaParser; import jannovar.io.FastaParser; import jannovar.io.GFFparser; import jannovar.io.RefSeqFastaParser; import jannovar.io.SerializationManager; import jannovar.io.TranscriptDataDownloader; import jannovar.io.UCSCKGParser; import jannovar.io.VCFLine; import jannovar.io.VCFReader; import jannovar.reference.Chromosome; import jannovar.reference.TranscriptModel; /** * This is the driver class for a program called Jannovar. It has two purposes * <OL> * <LI>Take the UCSC files knownGene.txt, kgXref.txt, knownGeneMrna.txt, and knownToLocusLink.txt, * and to create corresponding {@link jannovar.reference.TranscriptModel TranscriptModel} objects and to * serialize them. The resulting serialized file can be used both by this program itself (see next item) * or by the main Exomizer program to annotated VCF file. * <LI>Using the serialized file of {@link jannovar.reference.TranscriptModel TranscriptModel} objects (see above item) * annotate a VCF file using annovar-type program logic. Note that this functionality is also * used by the main Exomizer program and thus this program can be used as a stand-alone annotator ("Jannovar") * or as a way of testing the code for the Exomizer. * </OL> * <P> * To run the "Jannotator" exectuable: * <P> * {@code java -Xms1G -Xmx1G -jar Jannotator.jar -V xyz.vcf -D $SERIAL} * <P> * This will annotate a VCF file. The results of jannovar annotation are shown in the form * <PRE> * Annotation {original VCF line} * </PRE> * <P> * Just a reminder, to set up annovar to do this, use the following commands. * <PRE> * perl annotate_variation.pl --downdb knownGene --buildver hg19 humandb/ * </PRE> * then, to annotate a VCF file called BLA.vcf, we first need to convert it to Annovar input * format and run the main annovar program as follows. * <PRE> * $ perl convert2annovar.pl BLA.vcf -format vcf4 > BLA.av * $ perl annotate_variation.pl -buildver hg19 --geneanno BLA.av --dbtype knowngene humandb/ * </PRE> * This will create two files with all variants and a special file with exonic variants. * <p> * There are three ways of using this program. * <ol> * <li>To create a serialized version of the UCSC gene definition data. In this case, the command-line * flag <b>- S</b> is provide as is the path to the four UCSC files. Then, {@code anno.serialize()} is true * and a file <b>ucsc.ser</b> is created. * <li>To deserialize the serialized data (<b>ucsc.ser</b>). In this case, the flag <b>- D</b> must be used. * <li>To simply read in the UCSC data without creating a serialized file. * </ol> * Whichever of the three versions is chosen, the user may additionally pass the path to a VCF file using the <b>-v</b> flag. * If so, then this file will be annotated using the UCSC data, and a new version of the file will be written to a file called * test.vcf.jannovar (assuming the original file was named test.vcf). * The * @author Peter N Robinson * @version 0.26 (14 July, 2013) */ public class Jannovar { /** Location of a directory that must contain the files * knownGene.txt, kgXref.txt, knownGeneMrnafile knownGene.txt * (the files may or may not be compressed with gzip. The same variable is * also used to indicate the location of the download directory. The default value * is "ucsc".*/ private String dirPath=null; /** * Flag to indicate that Jannovar should download known gene definitions files from the * UCSC server. */ private boolean createUCSC; /** Flag to indicate Jannovar should download transcript definition files for RefSeq.*/ private boolean createRefseq; /** Flag to indicate Jannovar should download transcript definition files for Ensembl.*/ private boolean createEnsembl; /** List of all lines from knownGene.txt file from UCSC */ private ArrayList<TranscriptModel> transcriptModelList=null; /** Map of Chromosomes */ private HashMap<Byte,Chromosome> chromosomeMap=null; /** List of variants from input file to be analysed. */ private ArrayList<Variant> variantList=null; /** Name of the UCSC serialized data file that will be created by Jannovar. */ private static final String UCSCserializationFileName="ucsc_%s.ser"; /** Name of the Ensembl serialized data file that will be created by Jannovar. */ private static final String EnsemblSerializationFileName="ensembl_%s.ser"; /** Name of the refSeq serialized data file that will be created by Jannovar. */ private static final String RefseqSerializationFileName="refseq_%s.ser"; /** Flag to indicate that Jannovar should serialize the UCSC data. This flag is set to * true automatically if the user enters --create-ucsc (then, the four files are downloaded * and subsequently serialized). If the user enters the flag {@code -U path}, then Jannovar * interprets path as the location of a directory that already contains the UCSC files (either * compressed or uncompressed), and sets this flag to true to perform serialization and then * to exit. The name of the serialized file that gets created is "ucsc.ser" (this cannot * be changed from the command line, see {@link #UCSCserializationFileName}). */ private boolean performSerialization=false; /** Name of file with serialized UCSC data. This should be the complete path to the file, * and will be used for annotating VCF files.*/ private String serializedFile=null; /** Path to a VCF file waiting to be annotated. */ private String VCFfilePath=null; /** An FTP proxy for downloading the UCSC files from behind a firewall. */ private String proxy=null; /** An FTP proxy port for downloading the UCSC files from behind a firewall. */ private String proxyPort=null; /** * Flag indicating whether to output annotations in Jannovar format (default: false). */ private boolean jannovarFormat; /** genome release for the download and the creation of the serialized transcript model file */ private Release genomeRelease = Release.HG19; public static void main(String argv[]) { Jannovar anno = new Jannovar(argv); /* Option 1. Download the UCSC files from the server, create the ucsc.ser file, and return. */ if (anno.createUCSC()) { try{ anno.downloadTranscriptFiles(jannovar.common.Constants.UCSC,anno.genomeRelease); anno.inputTranscriptModelDataFromUCSCFiles(); anno.serializeUCSCdata(); } catch (JannovarException e) { System.err.println("[Jannovar]: " + e.toString()); System.exit(1); } return; } if (anno.createEnsembl()) { try{ anno.downloadTranscriptFiles(jannovar.common.Constants.ENSEMBL,anno.genomeRelease); anno.inputTranscriptModelDataFromEnsembl(); anno.serializeEnsemblData(); } catch (JannovarException e) { System.err.println("[Jannovar]: " + e.toString()); System.exit(1); } return; } if (anno.createRefseq()) { try{ anno.downloadTranscriptFiles(jannovar.common.Constants.REFSEQ,anno.genomeRelease); anno.inputTranscriptModelDataFromRefseq(); anno.serializeRefseqData(); } catch (JannovarException e) { System.err.println("[Jannovar]: " + e.toString()); System.exit(1); } return; } /* Option 2. The user must provide the ucsc.ser file to do analysis. (or the ensembl.ser or refseq.ser files). We can either annotate a VCF file (3a) or create a separate annotation file (3b). */ if (anno.deserialize()) { try { anno.deserializeTranscriptDefinitionFile(); } catch (JannovarException je) { System.out.println("[Jannovar] Could not deserialize UCSC data: " + je.toString()); System.exit(1); } } else { System.err.println("[Jannovar] Error: You need to pass ucscs.ser file to perform analysis."); usage(); System.exit(1); } /* When we get here, the program has deserialized data and put it into the Chromosome objects. We can now start to annotate variants. */ if (anno.hasVCFfile()) { anno.annotateVCF(); /* 3a or 3b */ } else { System.out.println("[Jannovar] No VCF file found"); } } /** The constructor parses the command-line arguments. */ public Jannovar(String argv[]){ this.dirPath="data/"; /* default */ parseCommandLineArguments(argv); if(!this.dirPath.endsWith("/")) this.dirPath += "/"; } /** * @return true if user wants to download UCSC files */ public boolean createUCSC() { return this.createUCSC; } /** * @return true if user wants to download refseq files */ public boolean createRefseq() { return this.createRefseq; } /** * @return true if user wants to download ENSEMBL files */ public boolean createEnsembl() { return this.createEnsembl; } /** * This function creates a * {@link TranscriptDataDownloader} object in order to * download the required transcript data files. If the user has set the proxy and * proxy port via the command line, we use these to download the files. */ public void downloadTranscriptFiles(int source, Release rel) { TranscriptDataDownloader downloader = null; try { if (this.proxy != null && this.proxyPort != null) { downloader = new TranscriptDataDownloader(this.dirPath,this.proxy,this.proxyPort); } else { downloader = new TranscriptDataDownloader(this.dirPath); } downloader.downloadTranscriptFiles(source, rel); } catch (FileDownloadException e) { System.err.println(e); System.exit(1); } } /** * @return true if we should serialize the UCSC data. */ public boolean serialize() { return this.performSerialization; } /** * @return true if we should deserialize a file with UCSC data to perform analysis */ public boolean deserialize() { return this.serializedFile != null; } /** * @return true if we should annotate a VCF file */ public boolean hasVCFfile() { return this.VCFfilePath != null; } /** * Annotate a single line of a VCF file, and output the line together with the new * INFO fields representing the annotations. * @param line an object representing the original VCF line * @param v the Variant object that was parsed from the line * @param out A file handle to write to. */ private void annotateVCFLine(VCFLine line, Variant v, Writer out) throws IOException,AnnotationException { byte chr = v.getChromosomeAsByte(); int pos = v.get_position(); String ref = v.get_ref(); String alt = v.get_alt(); Chromosome c = chromosomeMap.get(chr); if (c==null) { String e = String.format("[Jannovar] Could not identify chromosome \"%d\"", chr ); throw new AnnotationException(e); } AnnotationList anno = c.getAnnotationList(pos,ref,alt); if (anno==null) { String e = String.format("[Jannovar] No annotations found for variant %s", v.toString()); throw new AnnotationException(e); } String annotation = anno.getSingleTranscriptAnnotation(); String effect = anno.getVariantType().toString(); String A[] = line.getOriginalVCFLine().split("\t"); for (int i=0;i<7;++i) out.write(A[i] + "\t"); /* Now add the stuff to the INFO line */ String INFO = String.format("EFFECT=%s;HGVS=%s;%s",effect,annotation,A[7]); out.write(INFO + "\t"); for (int i=8;i<A.length;++i) out.write(A[i] + "\t"); out.write("\n"); } /** * This function outputs a single line in Jannovar format. * @param n The current number (one for each variant in the VCF file) * @param v The current variant with one or more annotations * @param out File handle to write Jannovar file. */ private void outputJannovarLine(int n,Variant v, Writer out) throws IOException,AnnotationException { byte chr = v.getChromosomeAsByte(); String chrStr = v.get_chromosome_as_string(); int pos = v.get_position(); String ref = v.get_ref(); String alt = v.get_alt(); String gtype = v.getGenotypeAsString(); float qual = v.get_variant_quality(); Chromosome c = chromosomeMap.get(chr); if (c==null) { String e = String.format("[Jannovar] Could not identify chromosome \"%d\"", chr ); throw new AnnotationException(e); } AnnotationList anno = c.getAnnotationList(pos,ref,alt); if (anno==null) { String e = String.format("[Jannovar] No annotations found for variant %s", v.toString()); throw new AnnotationException(e); } ArrayList<Annotation> lst = anno.getAnnotationList(); for (Annotation a : lst) { String effect = a.getVariantTypeAsString(); String annt = a.getVariantAnnotation(); String sym = a.getGeneSymbol(); String s = String.format("%d\t%s\t%s\t%s\t%s\t%d\t%s\t%s\t%s\t%.1f", n,effect,sym,annt,chrStr,pos,ref,alt,gtype,qual); out.write(s + "\n"); } } /** * This function outputs a VCF file that corresponds to the original * VCF file but additionally has annotations for each variant. A new file * is created with the suffix "jv.vcf"; */ private void outputAnnotatedVCF(VCFReader parser) { this.variantList = parser.getVariantList(); ArrayList<VCFLine> lineList = parser.getVCFLineList(); File f = new File(this.VCFfilePath); String outname = f.getName(); int i = outname.lastIndexOf("vcf"); if (i<0) { i = outname.lastIndexOf("VCF"); } if (i<0) { outname = outname + ".jv.vcf"; } else { outname = outname.substring(0,i) + "jv.vcf"; } try { FileWriter fstream = new FileWriter(outname); BufferedWriter out = new BufferedWriter(fstream); /** Write the header of the new VCF file */ ArrayList<String> lst = parser.getAnnotatedVCFHeader(); for (String s: lst) { out.write(s + "\n"); } /** Now write each of the variants. */ for (VCFLine line : lineList) { Variant v = parser.VCFline2Variant(line); try{ annotateVCFLine(line,v,out); } catch (AnnotationException e) { System.out.println("[Jannovar] Warning: Annotation error: " + e.toString()); } } out.close(); }catch (IOException e){ System.out.println("[Jannovar] Error writing annotated VCF file"); System.out.println("[Jannovar] " + e.toString()); System.exit(1); } System.out.println("[Jannovar] Wrote annotated VCF file to \"" + outname + "\""); } /** * This function writes detailed annotations to file. One annotation * is written for each of the transcripts affected by a variant, and the * file is a tab-separated file in "Jannovar" format. * @param parser The VCFParser that has extracted a list of variants from the VCF file. */ private void outputJannovarFormatFile(VCFReader parser) { this.variantList = parser.getVariantList(); File f = new File(this.VCFfilePath); String outname = f.getName() + ".jannovar"; try { FileWriter fstream = new FileWriter(outname); BufferedWriter out = new BufferedWriter(fstream); /** Output each of the variants. */ int n=0; for (Variant v : variantList) { n++; try{ outputJannovarLine(n,v,out); } catch (AnnotationException e) { System.out.println("[Jannovar] Warning: Annotation error: " + e.toString()); } } out.close(); }catch (IOException e){ System.out.println("[Jannovar] Error writing annotated VCF file"); System.out.println("[Jannovar] " + e.toString()); System.exit(1); } System.out.println("[Jannovar] Wrote annotations to \"" + outname + "\""); } /** * This function inputs a VCF file, and prints the annotated version thereof * to a file (name of the original file with the suffix .jannovar). */ public void annotateVCF() { VCFReader parser = new VCFReader(); VCFLine.setStoreVCFLines(); try{ parser.parseFile(this.VCFfilePath); } catch (VCFParseException e) { System.err.println("[Jannovar] Unable to parse VCF file"); System.err.println(e.toString()); System.exit(1); } if (this.jannovarFormat) { outputJannovarFormatFile(parser); } else { outputAnnotatedVCF(parser); } } /** * Inputs the GFF data from RefSeq files, convert the * resulting {@link jannovar.reference.TranscriptModel TranscriptModel} * objects to {@link jannovar.interval.Interval Interval} objects, and * store these in a serialized file. */ public void serializeRefseqData() throws JannovarException { SerializationManager manager = new SerializationManager(); System.out.println("[Jannovar] Serializing RefSeq data as " + String.format(Jannovar.RefseqSerializationFileName,genomeRelease.getUCSCString(genomeRelease))); manager.serializeKnownGeneList(String.format(Jannovar.RefseqSerializationFileName,genomeRelease.getUCSCString(genomeRelease)), this.transcriptModelList); } /** * Inputs the GFF data from Ensembl files, convert the * resulting {@link jannovar.reference.TranscriptModel TranscriptModel} * objects to {@link jannovar.interval.Interval Interval} objects, and * store these in a serialized file. */ public void serializeEnsemblData() throws JannovarException { SerializationManager manager = new SerializationManager(); System.out.println("[Jannovar] Serializing Ensembl data as " + String.format(Jannovar.EnsemblSerializationFileName,genomeRelease.getUCSCString(genomeRelease))); manager.serializeKnownGeneList(String.format(Jannovar.EnsemblSerializationFileName,genomeRelease.getUCSCString(genomeRelease)), this.transcriptModelList); } /** * Inputs the KnownGenes data from UCSC files, convert the * resulting {@link jannovar.reference.TranscriptModel TranscriptModel} * objects to {@link jannovar.interval.Interval Interval} objects, and * store these in a serialized file. */ public void serializeUCSCdata() throws JannovarException { SerializationManager manager = new SerializationManager(); System.out.println("[Jannovar] Serializing known gene data as " + String.format(Jannovar.UCSCserializationFileName,genomeRelease.getUCSCString(genomeRelease))); manager.serializeKnownGeneList(String.format(Jannovar.UCSCserializationFileName,genomeRelease.getUCSCString(genomeRelease)), this.transcriptModelList); } /** * To run Jannovar, the user must pass a transcript definition file with the * -D flag. This can be one of the files ucsc.ser, ensembl.ser, or * refseq.ser (or a comparable file) containing a serialized version of the * TranscriptModel objects created to contain info about the * transcript definitions (exon positions etc.) extracted from * UCSC, Ensembl, or Refseq and necessary for annotation. */ public void deserializeTranscriptDefinitionFile() throws JannovarException { ArrayList<TranscriptModel> kgList=null; SerializationManager manager = new SerializationManager(); kgList = manager.deserializeKnownGeneList(this.serializedFile); this.chromosomeMap = Chromosome.constructChromosomeMapWithIntervalTree(kgList); } /** * Input the RefSeq data. */ private void inputTranscriptModelDataFromRefseq() { // parse GFF/GTF GFFparser gff = new GFFparser(); switch (this.genomeRelease) { case MM9: gff.parse(this.dirPath + Constants.refseq_gff_mm9); break; case MM10: gff.parse(this.dirPath + Constants.refseq_gff_mm10); break; case HG18: gff.parse(this.dirPath + Constants.refseq_gff_hg18); break; case HG19: gff.parse(this.dirPath + Constants.refseq_gff_hg19); break; default: System.err.println("Unknown release: "+genomeRelease); System.exit(20); break; } try { this.transcriptModelList = gff.getTranscriptModelBuilder().buildTranscriptModels(); } catch (InvalidAttributException e) { System.out.println("[Jannovar] Unable to input data from the Refseq files"); e.printStackTrace(); System.exit(1); } // add sequences FastaParser efp = new RefSeqFastaParser(this.dirPath+Constants.refseq_rna, transcriptModelList); int before = transcriptModelList.size(); transcriptModelList = efp.parse(); int after = transcriptModelList.size(); System.out.println(String.format("[Jannovar] removed %d (%d --> %d) transcript models w/o rna sequence", before-after,before, after)); } /** * Input the Ensembl data. */ private void inputTranscriptModelDataFromEnsembl() { // parse GFF/GTF GFFparser gff = new GFFparser(); String prefix = null; switch (this.genomeRelease) { case MM9: prefix = this.dirPath + Constants.ensembl_mm9; break; case MM10: prefix = this.dirPath + Constants.ensembl_mm10; break; case HG18: prefix = this.dirPath + Constants.ensembl_hg18; break; case HG19: prefix = this.dirPath + Constants.ensembl_hg19; break; default: System.err.println("Unknown release: "+genomeRelease); System.exit(20); break; } gff.parse(prefix + Constants.ensembl_gtf); try { this.transcriptModelList = gff.getTranscriptModelBuilder().buildTranscriptModels(); System.out.println("TranscriptmodelList size: "+this.transcriptModelList.size()); } catch (InvalidAttributException e) { System.out.println("[Jannovar] Unable to input data from the Ensembl files"); e.printStackTrace(); System.exit(1); } // add sequences EnsemblFastaParser efp = new EnsemblFastaParser(prefix+Constants.ensembl_cdna, transcriptModelList); int before = transcriptModelList.size(); transcriptModelList = efp.parse(); int after = transcriptModelList.size(); System.out.println(String.format("[Jannovar] removed %d (%d --> %d) transcript models w/o rna sequence", before-after,before, after)); } /** * Input the four UCSC files for the KnownGene data. */ private void inputTranscriptModelDataFromUCSCFiles() { UCSCKGParser parser = new UCSCKGParser(this.dirPath); try{ parser.parseUCSCFiles(); } catch (Exception e) { System.out.println("[Jannovar] Unable to input data from the UCSC files"); e.printStackTrace(); System.exit(1); } this.transcriptModelList = parser.getKnownGeneList(); } /** * A simple printout of the chromosome map for debugging purposes. */ public void debugShowChromosomeMap() { for (Byte c: chromosomeMap.keySet()) { Chromosome chromo = chromosomeMap.get(c); System.out.println("Chrom. " + c + ": " + chromo.getNumberOfGenes() + " genes"); } } /** * Parse the command line. The important options are -n: path to the directory with the NSFP files, * and -C a flag indicating that we want the program to delete the current table in the postgres * database and to create an empty table (using JDBC connection). * @param args Copy of the command line arguments. */ private void parseCommandLineArguments(String[] args) { try { Options options = new Options(); options.addOption(new Option("h","help",false,"Shows this help")); options.addOption(new Option("U","nfsp",true,"Path to directory with UCSC files.")); options.addOption(new Option("S","serialize",false,"Serialize")); options.addOption(new Option("D","deserialize",true,"Path to serialized file with UCSC data")); options.addOption(new Option("V","vcf",true,"Path to VCF file")); options.addOption(new Option("J","janno",false,"Output Jannovar format")); options.addOption(new Option("g","genome",true,"genome build (mm9, mm10, hg18, hg19), default hg19")); options.addOption(new Option(null,"create-ucsc",false,"Create UCSC definition file")); options.addOption(new Option(null,"create-refseq",false,"Create RefSeq definition file")); options.addOption(new Option(null,"create-ensembl",false,"Create Ensembl definition file")); options.addOption(new Option(null,"proxy",true,"FTP Proxy")); options.addOption(new Option(null,"proxy-port",true,"FTP Proxy Port")); Parser parser = new GnuParser(); CommandLine cmd = parser.parse(options,args); if (cmd.hasOption("h") || cmd.hasOption("H") || args.length==0) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar Jannovar.jar [-options]", options); usage(); System.exit(0); } if (cmd.hasOption("J")) { this.jannovarFormat = true; } else { this.jannovarFormat = false; } if (cmd.hasOption("create-ucsc")) { this.createUCSC = true; this.performSerialization = true; } else { this.createUCSC = false; } if (cmd.hasOption("create-refseq")) { this.createRefseq = true; this.performSerialization = true; } else { this.createRefseq = false; } if (cmd.hasOption("create-ensembl")) { this.createEnsembl = true; this.performSerialization = true; } else { this.createEnsembl = false; } if(cmd.hasOption("genome")){ String g = cmd.getOptionValue("genome"); if(g.equals("mm9")){this.genomeRelease = Release.MM9;} if(g.equals("mm10")){this.genomeRelease = Release.MM10;} if(g.equals("hg18")){this.genomeRelease = Release.HG18;} if(g.equals("hg19")){this.genomeRelease = Release.HG19;} - this.dirPath += genomeRelease.getUCSCString(genomeRelease); }else{ + System.out.println("[Jannovar] genome release set to default: hg19"); this.genomeRelease = Release.HG19; } + this.dirPath += genomeRelease.getUCSCString(genomeRelease); if (cmd.hasOption('S')) { this.performSerialization = true; } if (cmd.hasOption("proxy")) { this.proxy = cmd.getOptionValue("proxy"); } if (cmd.hasOption("proxy-port")) { this.proxyPort = cmd.getOptionValue("proxy-port"); } if (cmd.hasOption("U")) { this.dirPath = getRequiredOptionValue(cmd,'U'); } if (cmd.hasOption('D')) { this.serializedFile = cmd.getOptionValue('D'); } if (cmd.hasOption("V")) this.VCFfilePath = cmd.getOptionValue("V"); } catch (ParseException pe) { System.err.println("Error parsing command line options"); System.err.println(pe.getMessage()); System.exit(1); } } /** * This function is used to ensure that certain options are passed to the * program before we start execution. * * @param cmd An apache CommandLine object that stores the command line arguments * @param name Name of the argument that must be present * @return Value of the required option as a String. */ private static String getRequiredOptionValue(CommandLine cmd, char name) { String val = cmd.getOptionValue(name); if (val == null) { System.err.println("Aborting because the required argument \"-" + name + "\" wasn't specified! Use the -h for more help."); System.exit(-1); } return val; } private static void usage() { System.out.println("*** Jannovar: Usage ****"); System.out.println("Use case 1: Download UCSC data and create transcript data file (ucsc.ser)"); System.out.println("$ java -jar Jannovar.jar --create-ucsc"); System.out.println("Use case 2: Add annotations to a VCF file"); System.out.println("$ java -jar Jannovar.jar -D ucsc.ser -V example.vcf"); System.out.println("Use case 3: Write new file with Jannovar-format annotations of a VCF file"); System.out.println("$ java -jar Jannovar -D ucsc.ser -V vcfPath -J"); System.out.println("*** See the tutorial for details ***"); } }
false
true
private void parseCommandLineArguments(String[] args) { try { Options options = new Options(); options.addOption(new Option("h","help",false,"Shows this help")); options.addOption(new Option("U","nfsp",true,"Path to directory with UCSC files.")); options.addOption(new Option("S","serialize",false,"Serialize")); options.addOption(new Option("D","deserialize",true,"Path to serialized file with UCSC data")); options.addOption(new Option("V","vcf",true,"Path to VCF file")); options.addOption(new Option("J","janno",false,"Output Jannovar format")); options.addOption(new Option("g","genome",true,"genome build (mm9, mm10, hg18, hg19), default hg19")); options.addOption(new Option(null,"create-ucsc",false,"Create UCSC definition file")); options.addOption(new Option(null,"create-refseq",false,"Create RefSeq definition file")); options.addOption(new Option(null,"create-ensembl",false,"Create Ensembl definition file")); options.addOption(new Option(null,"proxy",true,"FTP Proxy")); options.addOption(new Option(null,"proxy-port",true,"FTP Proxy Port")); Parser parser = new GnuParser(); CommandLine cmd = parser.parse(options,args); if (cmd.hasOption("h") || cmd.hasOption("H") || args.length==0) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar Jannovar.jar [-options]", options); usage(); System.exit(0); } if (cmd.hasOption("J")) { this.jannovarFormat = true; } else { this.jannovarFormat = false; } if (cmd.hasOption("create-ucsc")) { this.createUCSC = true; this.performSerialization = true; } else { this.createUCSC = false; } if (cmd.hasOption("create-refseq")) { this.createRefseq = true; this.performSerialization = true; } else { this.createRefseq = false; } if (cmd.hasOption("create-ensembl")) { this.createEnsembl = true; this.performSerialization = true; } else { this.createEnsembl = false; } if(cmd.hasOption("genome")){ String g = cmd.getOptionValue("genome"); if(g.equals("mm9")){this.genomeRelease = Release.MM9;} if(g.equals("mm10")){this.genomeRelease = Release.MM10;} if(g.equals("hg18")){this.genomeRelease = Release.HG18;} if(g.equals("hg19")){this.genomeRelease = Release.HG19;} this.dirPath += genomeRelease.getUCSCString(genomeRelease); }else{ this.genomeRelease = Release.HG19; } if (cmd.hasOption('S')) { this.performSerialization = true; } if (cmd.hasOption("proxy")) { this.proxy = cmd.getOptionValue("proxy"); } if (cmd.hasOption("proxy-port")) { this.proxyPort = cmd.getOptionValue("proxy-port"); } if (cmd.hasOption("U")) { this.dirPath = getRequiredOptionValue(cmd,'U'); } if (cmd.hasOption('D')) { this.serializedFile = cmd.getOptionValue('D'); } if (cmd.hasOption("V")) this.VCFfilePath = cmd.getOptionValue("V"); } catch (ParseException pe) { System.err.println("Error parsing command line options"); System.err.println(pe.getMessage()); System.exit(1); } }
private void parseCommandLineArguments(String[] args) { try { Options options = new Options(); options.addOption(new Option("h","help",false,"Shows this help")); options.addOption(new Option("U","nfsp",true,"Path to directory with UCSC files.")); options.addOption(new Option("S","serialize",false,"Serialize")); options.addOption(new Option("D","deserialize",true,"Path to serialized file with UCSC data")); options.addOption(new Option("V","vcf",true,"Path to VCF file")); options.addOption(new Option("J","janno",false,"Output Jannovar format")); options.addOption(new Option("g","genome",true,"genome build (mm9, mm10, hg18, hg19), default hg19")); options.addOption(new Option(null,"create-ucsc",false,"Create UCSC definition file")); options.addOption(new Option(null,"create-refseq",false,"Create RefSeq definition file")); options.addOption(new Option(null,"create-ensembl",false,"Create Ensembl definition file")); options.addOption(new Option(null,"proxy",true,"FTP Proxy")); options.addOption(new Option(null,"proxy-port",true,"FTP Proxy Port")); Parser parser = new GnuParser(); CommandLine cmd = parser.parse(options,args); if (cmd.hasOption("h") || cmd.hasOption("H") || args.length==0) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar Jannovar.jar [-options]", options); usage(); System.exit(0); } if (cmd.hasOption("J")) { this.jannovarFormat = true; } else { this.jannovarFormat = false; } if (cmd.hasOption("create-ucsc")) { this.createUCSC = true; this.performSerialization = true; } else { this.createUCSC = false; } if (cmd.hasOption("create-refseq")) { this.createRefseq = true; this.performSerialization = true; } else { this.createRefseq = false; } if (cmd.hasOption("create-ensembl")) { this.createEnsembl = true; this.performSerialization = true; } else { this.createEnsembl = false; } if(cmd.hasOption("genome")){ String g = cmd.getOptionValue("genome"); if(g.equals("mm9")){this.genomeRelease = Release.MM9;} if(g.equals("mm10")){this.genomeRelease = Release.MM10;} if(g.equals("hg18")){this.genomeRelease = Release.HG18;} if(g.equals("hg19")){this.genomeRelease = Release.HG19;} }else{ System.out.println("[Jannovar] genome release set to default: hg19"); this.genomeRelease = Release.HG19; } this.dirPath += genomeRelease.getUCSCString(genomeRelease); if (cmd.hasOption('S')) { this.performSerialization = true; } if (cmd.hasOption("proxy")) { this.proxy = cmd.getOptionValue("proxy"); } if (cmd.hasOption("proxy-port")) { this.proxyPort = cmd.getOptionValue("proxy-port"); } if (cmd.hasOption("U")) { this.dirPath = getRequiredOptionValue(cmd,'U'); } if (cmd.hasOption('D')) { this.serializedFile = cmd.getOptionValue('D'); } if (cmd.hasOption("V")) this.VCFfilePath = cmd.getOptionValue("V"); } catch (ParseException pe) { System.err.println("Error parsing command line options"); System.err.println(pe.getMessage()); System.exit(1); } }
diff --git a/src/net/alexjf/tmm/adapters/TabAdapter.java b/src/net/alexjf/tmm/adapters/TabAdapter.java index 0aee24b..8eef91e 100644 --- a/src/net/alexjf/tmm/adapters/TabAdapter.java +++ b/src/net/alexjf/tmm/adapters/TabAdapter.java @@ -1,187 +1,189 @@ /******************************************************************************* * Copyright (c) 2013 - Alexandre Jorge Fonseca (alexjf.net) * License: GPL v3 (http://www.gnu.org/licenses/gpl-3.0.txt) ******************************************************************************/ package net.alexjf.tmm.adapters; import java.util.ArrayList; import java.util.Arrays; import net.alexjf.tmm.R; import net.alexjf.tmm.utils.PreferenceManager; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.ViewPager; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.view.ViewGroup; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.ActionBar.Tab; import com.actionbarsherlock.app.SherlockFragmentActivity; /** * Based on http://stackoverflow.com/a/10082836/441265 */ public class TabAdapter extends FragmentPagerAdapter implements ActionBar.TabListener, ViewPager.OnPageChangeListener { private final static String KEY_TABNAV = "pref_key_tab_navigation"; private final Activity activity; private final ActionBar actionBar; private final ViewPager viewPager; private final ArrayList<TabInfo> tabs = new ArrayList<TabInfo>(); private boolean tabsShown = true; private boolean swipeEnabled = true; private OnTabChangeListener onTabChangeListener; private OnTabFragmentCreateListener onTabFragmentCreateListener; public interface OnTabChangeListener { public void onTabChanged(int position); } public interface OnTabFragmentCreateListener { public void onTabFragmentCreated(Fragment fragment, int position); } static final class TabInfo { private final Class<?> clss; private final Bundle args; private Fragment fragment; TabInfo(Class<?> clss, Bundle args) { this.clss = clss; this.args = args; this.fragment = null; } } public TabAdapter(SherlockFragmentActivity activity, ViewPager pager) { super(activity.getSupportFragmentManager()); this.activity = activity; actionBar = activity.getSupportActionBar(); viewPager = pager; viewPager.setOnPageChangeListener(this); viewPager.setAdapter(this); refreshPreferences(); } public void refreshPreferences() { PreferenceManager prefManager = PreferenceManager.getInstance(); String[] tabNavigationTypes = activity.getResources().getStringArray(R.array.pref_tab_navigation_values); String tabNavigation = prefManager.readUserStringPreference(KEY_TABNAV, ""); - int navIndex = Arrays.asList(tabNavigationTypes).indexOf(tabNavigation); + // Don't consider -1 as valid value, minimum 0 + int navIndex = Math.max(0, + Arrays.asList(tabNavigationTypes).indexOf(tabNavigation)); tabsShown = navIndex % 2 == 0; swipeEnabled = navIndex > 0; if (tabsShown) { actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); } else { actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); } if (!swipeEnabled) { viewPager.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { return true; } }); } else { viewPager.setOnTouchListener(null); } } @Override public Object instantiateItem(ViewGroup container, int position) { Fragment fragment = (Fragment) super.instantiateItem(container, position); tabs.get(position).fragment = fragment; onTabFragmentCreateListener.onTabFragmentCreated(fragment, position); return fragment; } public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) { TabInfo info = new TabInfo(clss, args); tab.setTag(info); tab.setTabListener(this); tabs.add(info); actionBar.addTab(tab); notifyDataSetChanged(); } @Override public int getCount() { return tabs.size(); } @Override public Fragment getItem(int position) { TabInfo info = tabs.get(position); Fragment fragment = Fragment.instantiate(activity, info.clss.getName(), info.args); return fragment; } @Override public void destroyItem(ViewGroup container, int position, Object object) { super.destroyItem(container, position, object); tabs.get(position).fragment = null; } public Fragment getFragment(int position) { return tabs.get(position).fragment; } public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } public void onPageSelected(int position) { if (tabsShown) { actionBar.setSelectedNavigationItem(position); } notifyTabChanged(position); } public void onPageScrollStateChanged(int state) { } public void onTabSelected(Tab tab, FragmentTransaction ft) { int position = tab.getPosition(); viewPager.setCurrentItem(position); notifyTabChanged(position); } public void onTabUnselected(Tab tab, FragmentTransaction ft) { } public void onTabReselected(Tab tab, FragmentTransaction ft) { } public void setOnTabFragmentCreateListener(OnTabFragmentCreateListener listener) { this.onTabFragmentCreateListener = listener; } public void setOnTabChangeListener(OnTabChangeListener listener) { this.onTabChangeListener = listener; } private void notifyTabChanged(int position) { if (onTabChangeListener != null) { onTabChangeListener.onTabChanged(position); } } }
true
true
public void refreshPreferences() { PreferenceManager prefManager = PreferenceManager.getInstance(); String[] tabNavigationTypes = activity.getResources().getStringArray(R.array.pref_tab_navigation_values); String tabNavigation = prefManager.readUserStringPreference(KEY_TABNAV, ""); int navIndex = Arrays.asList(tabNavigationTypes).indexOf(tabNavigation); tabsShown = navIndex % 2 == 0; swipeEnabled = navIndex > 0; if (tabsShown) { actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); } else { actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); } if (!swipeEnabled) { viewPager.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { return true; } }); } else { viewPager.setOnTouchListener(null); } }
public void refreshPreferences() { PreferenceManager prefManager = PreferenceManager.getInstance(); String[] tabNavigationTypes = activity.getResources().getStringArray(R.array.pref_tab_navigation_values); String tabNavigation = prefManager.readUserStringPreference(KEY_TABNAV, ""); // Don't consider -1 as valid value, minimum 0 int navIndex = Math.max(0, Arrays.asList(tabNavigationTypes).indexOf(tabNavigation)); tabsShown = navIndex % 2 == 0; swipeEnabled = navIndex > 0; if (tabsShown) { actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); } else { actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); } if (!swipeEnabled) { viewPager.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { return true; } }); } else { viewPager.setOnTouchListener(null); } }
diff --git a/org.eclipse.riena.tests/src/org/eclipse/riena/ui/swt/utils/MouseWheelAdapterTest.java b/org.eclipse.riena.tests/src/org/eclipse/riena/ui/swt/utils/MouseWheelAdapterTest.java index a22e61e46..75c785b8a 100644 --- a/org.eclipse.riena.tests/src/org/eclipse/riena/ui/swt/utils/MouseWheelAdapterTest.java +++ b/org.eclipse.riena.tests/src/org/eclipse/riena/ui/swt/utils/MouseWheelAdapterTest.java @@ -1,80 +1,80 @@ /******************************************************************************* * Copyright (c) 2007, 2014 compeople AG and others. * 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 * * Contributors: * compeople AG - initial API and implementation *******************************************************************************/ package org.eclipse.riena.ui.swt.utils; import junit.framework.TestCase; import org.easymock.EasyMock; import org.junit.Test; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Shell; import org.eclipse.riena.core.test.collect.UITestCase; import org.eclipse.riena.ui.swt.utils.MouseWheelAdapter.Scroller; /** * Tests for the class {@link MouseWheelAdapter} */ @UITestCase public class MouseWheelAdapterTest extends TestCase { private static final int OS_SETTING_MOUSE_WHEEL = 3; private Display display; private Shell shell; private Scroller scroller; private MouseWheelAdapter mouseWheelAdapter; @Override protected void setUp() throws Exception { super.setUp(); display = Display.getDefault(); shell = new Shell(display); shell.open(); scroller = EasyMock.createMock(Scroller.class); mouseWheelAdapter = new MouseWheelAdapter(shell, scroller); } @Override protected void tearDown() { SwtUtilities.dispose(shell); } public void testSetNegativeScrollingSpeed() throws Exception { try { mouseWheelAdapter.setScrollingSpeed(-1); fail("Exception expected - setting a negative scrolling speed is not allowed!"); //$NON-NLS-1$ } catch (final IllegalArgumentException e) { // everything is ok } } @Test public void testSetScrollingSpeed() throws Exception { EasyMock.expect(scroller.mayScroll()).andReturn(true); final int speed = 15; mouseWheelAdapter.setScrollingSpeed(speed); scroller.scrollUp(OS_SETTING_MOUSE_WHEEL * speed); EasyMock.replay(scroller); final Event event = new Event(); event.time = 1; event.widget = shell; event.count = OS_SETTING_MOUSE_WHEEL; - event.x = shell.getLocation().x + 1; - event.y = shell.getLocation().y + 1; + event.x = shell.toDisplay(0, 0).x + 1; + event.y = shell.toDisplay(0, 0).y + 1; mouseWheelAdapter.handleEvent(event); EasyMock.verify(scroller); } }
true
true
public void testSetScrollingSpeed() throws Exception { EasyMock.expect(scroller.mayScroll()).andReturn(true); final int speed = 15; mouseWheelAdapter.setScrollingSpeed(speed); scroller.scrollUp(OS_SETTING_MOUSE_WHEEL * speed); EasyMock.replay(scroller); final Event event = new Event(); event.time = 1; event.widget = shell; event.count = OS_SETTING_MOUSE_WHEEL; event.x = shell.getLocation().x + 1; event.y = shell.getLocation().y + 1; mouseWheelAdapter.handleEvent(event); EasyMock.verify(scroller); }
public void testSetScrollingSpeed() throws Exception { EasyMock.expect(scroller.mayScroll()).andReturn(true); final int speed = 15; mouseWheelAdapter.setScrollingSpeed(speed); scroller.scrollUp(OS_SETTING_MOUSE_WHEEL * speed); EasyMock.replay(scroller); final Event event = new Event(); event.time = 1; event.widget = shell; event.count = OS_SETTING_MOUSE_WHEEL; event.x = shell.toDisplay(0, 0).x + 1; event.y = shell.toDisplay(0, 0).y + 1; mouseWheelAdapter.handleEvent(event); EasyMock.verify(scroller); }
diff --git a/openejb/container/openejb-core/src/main/java/org/apache/openejb/core/ivm/EjbObjectProxyHandler.java b/openejb/container/openejb-core/src/main/java/org/apache/openejb/core/ivm/EjbObjectProxyHandler.java index ac6fce77d..e583aaeea 100644 --- a/openejb/container/openejb-core/src/main/java/org/apache/openejb/core/ivm/EjbObjectProxyHandler.java +++ b/openejb/container/openejb-core/src/main/java/org/apache/openejb/core/ivm/EjbObjectProxyHandler.java @@ -1,435 +1,441 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.openejb.core.ivm; import java.io.ObjectStreamException; import java.lang.reflect.Method; import java.rmi.AccessException; import java.rmi.NoSuchObjectException; import java.rmi.RemoteException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import javax.ejb.AccessLocalException; import javax.ejb.ConcurrentAccessTimeoutException; import javax.ejb.EJBAccessException; import javax.ejb.EJBException; import javax.ejb.EJBLocalObject; import javax.ejb.EJBObject; import javax.ejb.NoSuchEJBException; import org.apache.openejb.AppContext; import org.apache.openejb.BeanContext; import org.apache.openejb.InterfaceType; import org.apache.openejb.core.ServerFederation; import org.apache.openejb.core.ThreadContext; import org.apache.openejb.spi.ApplicationServer; import org.apache.openejb.util.LogCategory; import org.apache.openejb.util.Logger; public abstract class EjbObjectProxyHandler extends BaseEjbProxyHandler { private static final Logger logger = Logger.getInstance(LogCategory.OPENEJB, "org.apache.openejb.util.resources"); static final Map<String, Integer> dispatchTable; static { dispatchTable = new HashMap<String, Integer>(); dispatchTable.put("getHandle", Integer.valueOf(1)); dispatchTable.put("getPrimaryKey", Integer.valueOf(2)); dispatchTable.put("isIdentical", Integer.valueOf(3)); dispatchTable.put("remove", Integer.valueOf(4)); dispatchTable.put("getEJBHome", Integer.valueOf(5)); dispatchTable.put("getEJBLocalHome", Integer.valueOf(6)); } public EjbObjectProxyHandler(BeanContext beanContext, Object pk, InterfaceType interfaceType, List<Class> interfaces, Class mainInterface) { super(beanContext, pk, interfaceType, interfaces, mainInterface); } public abstract Object getRegistryId(); public Object _invoke(Object p, Class interfce, Method m, Object[] a) throws Throwable { java.lang.Object retValue = null; java.lang.Throwable exc = null; try { if (logger.isDebugEnabled()) { logger.debug("invoking method " + m.getName() + " on " + deploymentID + " with identity " + primaryKey); } Integer operation = dispatchTable.get(m.getName()); if(operation != null){ if(operation.intValue() == 3){ if(m.getParameterTypes()[0] != EJBObject.class && m.getParameterTypes()[0] != EJBLocalObject.class ){ operation = null; } } else { operation = (m.getParameterTypes().length == 0)?operation:null; } } if (operation == null || !interfaceType.isComponent() ) { retValue = businessMethod(interfce, m, a, p); } else { switch (operation.intValue()) { case 1: retValue = getHandle(m, a, p); break; case 2: retValue = getPrimaryKey(m, a, p); break; case 3: retValue = isIdentical(m, a, p); break; case 4: retValue = remove(interfce, m, a, p); break; case 5: retValue = getEJBHome(m, a, p); break; case 6: retValue = getEJBLocalHome(m, a, p); break; default: throw new RuntimeException("Inconsistent internal state"); } } return retValue; /* * The ire is thrown by the container system and propagated by * the server to the stub. */ } catch (org.apache.openejb.InvalidateReferenceException ire) { invalidateAllHandlers(getRegistryId()); exc = (ire.getRootCause() != null) ? ire.getRootCause() : ire; throw exc; /* * Application exceptions must be reported dirctly to the client. They * do not impact the viability of the proxy. */ } catch (org.apache.openejb.ApplicationException ae) { exc = (ae.getRootCause() != null) ? ae.getRootCause() : ae; if (exc instanceof EJBAccessException) { if (interfaceType.isBusiness()) { throw exc; } else { if (interfaceType.isLocal()) { throw new AccessLocalException(exc.getMessage()).initCause(exc.getCause()); } else { throw new AccessException(exc.getMessage()); } } } throw exc; /* * A system exception would be highly unusual and would indicate a sever * problem with the container system. */ } catch (org.apache.openejb.SystemException se) { invalidateReference(); exc = (se.getRootCause() != null) ? se.getRootCause() : se; logger.debug("The container received an unexpected exception: ", exc); throw new RemoteException("Container has suffered a SystemException", exc); } catch (org.apache.openejb.OpenEJBException oe) { exc = (oe.getRootCause() != null) ? oe.getRootCause() : oe; logger.debug("The container received an unexpected exception: ", exc); throw new RemoteException("Unknown Container Exception", oe.getRootCause()); } finally { if (logger.isDebugEnabled()) { if (exc == null) { - logger.debug("finished invoking method " + m.getName() + ". Return value:" + retValue); + String ret; + try { // if it is a CDI (javassit proxy) it doesn't always work.... + ret = retValue.toString(); + } catch (Exception e) { + ret = "can't get toString() value (" + e.getMessage() + ")"; + } + logger.debug("finished invoking method " + m.getName() + ". Return value:" + ret); } else { logger.debug("finished invoking method " + m.getName() + " with exception " + exc); } } } } protected Object getEJBHome(Method method, Object[] args, Object proxy) throws Throwable { checkAuthorization(method); return getBeanContext().getEJBHome(); } protected Object getEJBLocalHome(Method method, Object[] args, Object proxy) throws Throwable { checkAuthorization(method); return getBeanContext().getEJBLocalHome(); } protected Object getHandle(Method method, Object[] args, Object proxy) throws Throwable { checkAuthorization(method); return new IntraVmHandle(proxy); } public org.apache.openejb.ProxyInfo getProxyInfo() { return new org.apache.openejb.ProxyInfo(getBeanContext(), primaryKey, getInterfaces(), interfaceType, getMainInterface()); } protected Object _writeReplace(Object proxy) throws ObjectStreamException { /* * If the proxy is being copied between bean instances in a RPC * call we use the IntraVmArtifact */ if (IntraVmCopyMonitor.isIntraVmCopyOperation()) { return new IntraVmArtifact(proxy); /* * If the proxy is referenced by a stateful bean that is being * passivated by the container we allow this object to be serialized. */ } else if (IntraVmCopyMonitor.isStatefulPassivationOperation()) { return proxy; /* * If the proxy is being copied between class loaders * we allow this object to be serialized. */ } else if (IntraVmCopyMonitor.isCrossClassLoaderOperation()) { return proxy; /* * If the proxy is serialized outside the core container system, * we allow the application server to handle it. */ } else { ApplicationServer applicationServer = ServerFederation.getApplicationServer(); if (interfaceType.isBusiness()){ return applicationServer.getBusinessObject(this.getProxyInfo()); } else { return applicationServer.getEJBObject(this.getProxyInfo()); } } } protected abstract Object getPrimaryKey(Method method, Object[] args, Object proxy) throws Throwable; protected abstract Object isIdentical(Method method, Object[] args, Object proxy) throws Throwable; protected abstract Object remove(Class interfce, Method method, Object[] args, Object proxy) throws Throwable; protected Object businessMethod(Class<?> interfce, Method method, Object[] args, Object proxy) throws Throwable { BeanContext beanContext = getBeanContext(); if (beanContext.isAsynchronous(method)) { return asynchronizedBusinessMethod(interfce, method, args, proxy); } else { return synchronizedBusinessMethod(interfce, method, args, proxy); } } protected Object asynchronizedBusinessMethod(Class<?> interfce, Method method, Object[] args, Object proxy) throws Throwable { BeanContext beanContext = getBeanContext(); AtomicBoolean asynchronousCancelled = new AtomicBoolean(false); AsynchronousCall asynchronousCall = new AsynchronousCall(interfce, method, args, asynchronousCancelled); try { Future<Object> retValue = beanContext.getModuleContext().getAppContext().submitTask(asynchronousCall); if (method.getReturnType() == Void.TYPE) { return null; } return new FutureAdapter<Object>(retValue, asynchronousCancelled, beanContext.getModuleContext().getAppContext()); } catch (RejectedExecutionException e) { throw new EJBException("fail to allocate internal resource to execute the target task", e); } } protected Object synchronizedBusinessMethod(Class<?> interfce, Method method, Object[] args, Object proxy) throws Throwable { return container.invoke(deploymentID, interfaceType, interfce, method, args, primaryKey); } public static Object createProxy(BeanContext beanContext, Object primaryKey, InterfaceType interfaceType, Class mainInterface) { return createProxy(beanContext, primaryKey, interfaceType, null, mainInterface); } public static Object createProxy(BeanContext beanContext, Object primaryKey, InterfaceType interfaceType, List<Class> interfaces, Class mainInterface) { if (!interfaceType.isHome()){ interfaceType = interfaceType.getCounterpart(); } EjbHomeProxyHandler homeHandler = EjbHomeProxyHandler.createHomeHandler(beanContext, interfaceType, interfaces, mainInterface); return homeHandler.createProxy(primaryKey, mainInterface); } private class AsynchronousCall implements Callable<Object> { private Class<?> interfce; private Method method; private Object[] args; private AtomicBoolean asynchronousCancelled; public AsynchronousCall(Class<?> interfce, Method method, Object[] args, AtomicBoolean asynchronousCancelled) { this.interfce = interfce; this.method = method; this.args = args; this.asynchronousCancelled = asynchronousCancelled; } @Override public Object call() throws Exception { try { ThreadContext.initAsynchronousCancelled(asynchronousCancelled); Object retValue = container.invoke(deploymentID, interfaceType, interfce, method, args, primaryKey); if (retValue == null) { return null; } else if (retValue instanceof Future<?>) { //TODO do we need to strictly check AsyncResult or just Future ? Future<?> asyncResult = (Future<?>) retValue; return asyncResult.get(); } else { // The bean isn't returning the right result! // We should never arrive here ! return null; } } finally { ThreadContext.removeAsynchronousCancelled(); } } } private class FutureAdapter<T> implements Future<T> { private Future<T> target; private AtomicBoolean asynchronousCancelled; private AppContext appContext; private volatile boolean canceled; public FutureAdapter(Future<T> target, AtomicBoolean asynchronousCancelled, AppContext appContext) { this.target = target; this.asynchronousCancelled = asynchronousCancelled; this.appContext = appContext; } @Override public boolean cancel(boolean mayInterruptIfRunning) { /*In EJB 3.1 spec 3.4.8.1.1 *a. If a client calls cancel on its Future object, the container will attempt to cancel the associated asynchronous invocation only if that invocation has not already been dispatched. * There is no guarantee that an asynchronous invocation can be cancelled, regardless of how quickly cancel is called after the client receives its Future object. * If the asynchronous invocation can not be cancelled, the method must return false. * If the asynchronous invocation is successfully cancelled, the method must return true. *b. the meaning of parameter mayInterruptIfRunning is changed. * So, we should never call cancel(true), or the underlying Future object will try to interrupt the target thread. */ /** * We use our own flag canceled to identify whether the task is canceled successfully. */ if(canceled) { return true; } if (appContext.removeTask((Runnable) target)) { //We successfully remove the task from the queue canceled = true; return true; } else { //Not find the task in the queue, the status might be ran/canceled or running //Future.isDone() will return true when the task has been ran or canceled, //since we never call the Future.cancel method, the isDone method will only return true when the task has ran if (!target.isDone()) { //The task is in the running state asynchronousCancelled.set(mayInterruptIfRunning); } return false; } } @Override public T get() throws InterruptedException, ExecutionException { if(canceled) { throw new CancellationException(); } T object = null; try { object = target.get(); } catch (Throwable e) { handleException(e); } return object; } @Override public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { if (canceled) { throw new CancellationException(); } T object = null; try { object = target.get(timeout, unit); } catch (Throwable e) { handleException(e); } return object; } private void handleException(Throwable e) throws ExecutionException { //unwarp the exception to find the root cause while (e.getCause() != null) { e = (Throwable) e.getCause(); } /* * StatefulContainer.obtainInstance(Object, ThreadContext, Method) * will return NoSuchObjectException instead of NoSuchEJBException * * when it can't obtain an instance. Actually, the async client * is expecting a NoSuchEJBException. Wrap it here as a workaround. */ if (e instanceof NoSuchObjectException) { e = new NoSuchEJBException(e.getMessage(), (Exception) e); } boolean isExceptionUnchecked = (e instanceof Error) || (e instanceof RuntimeException); // throw checked excpetion and EJBException directly. if (!isExceptionUnchecked || e instanceof EJBException) { throw new ExecutionException(e); } // wrap unchecked exception with EJBException before throwing. throw (e instanceof Exception) ? new ExecutionException(new EJBException((Exception) e)) : new ExecutionException(new EJBException(new Exception(e))); } @Override public boolean isCancelled() { return canceled; } @Override public boolean isDone() { if(canceled) { return false; } return target.isDone(); } } }
true
true
public Object _invoke(Object p, Class interfce, Method m, Object[] a) throws Throwable { java.lang.Object retValue = null; java.lang.Throwable exc = null; try { if (logger.isDebugEnabled()) { logger.debug("invoking method " + m.getName() + " on " + deploymentID + " with identity " + primaryKey); } Integer operation = dispatchTable.get(m.getName()); if(operation != null){ if(operation.intValue() == 3){ if(m.getParameterTypes()[0] != EJBObject.class && m.getParameterTypes()[0] != EJBLocalObject.class ){ operation = null; } } else { operation = (m.getParameterTypes().length == 0)?operation:null; } } if (operation == null || !interfaceType.isComponent() ) { retValue = businessMethod(interfce, m, a, p); } else { switch (operation.intValue()) { case 1: retValue = getHandle(m, a, p); break; case 2: retValue = getPrimaryKey(m, a, p); break; case 3: retValue = isIdentical(m, a, p); break; case 4: retValue = remove(interfce, m, a, p); break; case 5: retValue = getEJBHome(m, a, p); break; case 6: retValue = getEJBLocalHome(m, a, p); break; default: throw new RuntimeException("Inconsistent internal state"); } } return retValue; /* * The ire is thrown by the container system and propagated by * the server to the stub. */ } catch (org.apache.openejb.InvalidateReferenceException ire) { invalidateAllHandlers(getRegistryId()); exc = (ire.getRootCause() != null) ? ire.getRootCause() : ire; throw exc; /* * Application exceptions must be reported dirctly to the client. They * do not impact the viability of the proxy. */ } catch (org.apache.openejb.ApplicationException ae) { exc = (ae.getRootCause() != null) ? ae.getRootCause() : ae; if (exc instanceof EJBAccessException) { if (interfaceType.isBusiness()) { throw exc; } else { if (interfaceType.isLocal()) { throw new AccessLocalException(exc.getMessage()).initCause(exc.getCause()); } else { throw new AccessException(exc.getMessage()); } } } throw exc; /* * A system exception would be highly unusual and would indicate a sever * problem with the container system. */ } catch (org.apache.openejb.SystemException se) { invalidateReference(); exc = (se.getRootCause() != null) ? se.getRootCause() : se; logger.debug("The container received an unexpected exception: ", exc); throw new RemoteException("Container has suffered a SystemException", exc); } catch (org.apache.openejb.OpenEJBException oe) { exc = (oe.getRootCause() != null) ? oe.getRootCause() : oe; logger.debug("The container received an unexpected exception: ", exc); throw new RemoteException("Unknown Container Exception", oe.getRootCause()); } finally { if (logger.isDebugEnabled()) { if (exc == null) { logger.debug("finished invoking method " + m.getName() + ". Return value:" + retValue); } else { logger.debug("finished invoking method " + m.getName() + " with exception " + exc); } } } }
public Object _invoke(Object p, Class interfce, Method m, Object[] a) throws Throwable { java.lang.Object retValue = null; java.lang.Throwable exc = null; try { if (logger.isDebugEnabled()) { logger.debug("invoking method " + m.getName() + " on " + deploymentID + " with identity " + primaryKey); } Integer operation = dispatchTable.get(m.getName()); if(operation != null){ if(operation.intValue() == 3){ if(m.getParameterTypes()[0] != EJBObject.class && m.getParameterTypes()[0] != EJBLocalObject.class ){ operation = null; } } else { operation = (m.getParameterTypes().length == 0)?operation:null; } } if (operation == null || !interfaceType.isComponent() ) { retValue = businessMethod(interfce, m, a, p); } else { switch (operation.intValue()) { case 1: retValue = getHandle(m, a, p); break; case 2: retValue = getPrimaryKey(m, a, p); break; case 3: retValue = isIdentical(m, a, p); break; case 4: retValue = remove(interfce, m, a, p); break; case 5: retValue = getEJBHome(m, a, p); break; case 6: retValue = getEJBLocalHome(m, a, p); break; default: throw new RuntimeException("Inconsistent internal state"); } } return retValue; /* * The ire is thrown by the container system and propagated by * the server to the stub. */ } catch (org.apache.openejb.InvalidateReferenceException ire) { invalidateAllHandlers(getRegistryId()); exc = (ire.getRootCause() != null) ? ire.getRootCause() : ire; throw exc; /* * Application exceptions must be reported dirctly to the client. They * do not impact the viability of the proxy. */ } catch (org.apache.openejb.ApplicationException ae) { exc = (ae.getRootCause() != null) ? ae.getRootCause() : ae; if (exc instanceof EJBAccessException) { if (interfaceType.isBusiness()) { throw exc; } else { if (interfaceType.isLocal()) { throw new AccessLocalException(exc.getMessage()).initCause(exc.getCause()); } else { throw new AccessException(exc.getMessage()); } } } throw exc; /* * A system exception would be highly unusual and would indicate a sever * problem with the container system. */ } catch (org.apache.openejb.SystemException se) { invalidateReference(); exc = (se.getRootCause() != null) ? se.getRootCause() : se; logger.debug("The container received an unexpected exception: ", exc); throw new RemoteException("Container has suffered a SystemException", exc); } catch (org.apache.openejb.OpenEJBException oe) { exc = (oe.getRootCause() != null) ? oe.getRootCause() : oe; logger.debug("The container received an unexpected exception: ", exc); throw new RemoteException("Unknown Container Exception", oe.getRootCause()); } finally { if (logger.isDebugEnabled()) { if (exc == null) { String ret; try { // if it is a CDI (javassit proxy) it doesn't always work.... ret = retValue.toString(); } catch (Exception e) { ret = "can't get toString() value (" + e.getMessage() + ")"; } logger.debug("finished invoking method " + m.getName() + ". Return value:" + ret); } else { logger.debug("finished invoking method " + m.getName() + " with exception " + exc); } } } }
diff --git a/src/nl/nikhef/jgridstart/util/FileUtils.java b/src/nl/nikhef/jgridstart/util/FileUtils.java index a3ddc8a..4e4fb04 100644 --- a/src/nl/nikhef/jgridstart/util/FileUtils.java +++ b/src/nl/nikhef/jgridstart/util/FileUtils.java @@ -1,285 +1,284 @@ package nl.nikhef.jgridstart.util; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.logging.Level; import java.util.logging.Logger; /** Some file-related utilities */ public class FileUtils { static protected Logger logger = Logger.getLogger("nl.nikhef.jgridstart.util"); /** Copy a file from one place to another. This calls an external copy * program on the operating system to make sure it is properly copied and * permissions are retained. * @throws IOException */ public static boolean CopyFile(File in, File out) throws IOException { String[] cmd; if (System.getProperty("os.name").startsWith("Windows")) { boolean hasRobocopy = false; // windows: use special copy program to retain permissions. // on Vista, "xcopy /O" requires administrative rights, so we // have to resort to using robocopy there. try { int ret = Exec(new String[]{"robocopy.exe"}); - if (ret!=0 && ret!=16) throw new InterruptedException(); - hasRobocopy = true; - } catch (InterruptedException e) { } + if (ret==0 && ret==16) hasRobocopy = true; + } catch (Exception e) { } if (hasRobocopy) { // we have robocopy. But ... its destination filename // needs to be equal to the source filename :( // So we rename any existing file out of the way, copy // the new file, rename it to the new name, and restore // the optional original file. All this is required to // copy a file retaining its permissions. // TODO proper return value handling (!) // move old file out of the way File origFile = new File(out.getParentFile(), in.getName()); File origFileRenamed = null; if (origFile.exists()) { origFileRenamed = new File(origFile.getParentFile(), origFile.getName()+".xxx_tmp"); origFile.renameTo(origFileRenamed); } else { origFile = null; } // copy file to new place cmd = new String[]{"robocopy.exe", in.getParent(), out.getParent(), in.getName(), "/SEC", "/NP", "/NS", "/NC", "/NFL", "/NDL"}; int ret = Exec(cmd); boolean success = ret < 4 && ret >= 0; // rename new file if (success) { new File(out.getParentFile(), in.getName()).renameTo(out); } // move old file to original place again if (origFile!=null) origFileRenamed.renameTo(origFile); return success; } else { // use xcopy instead cmd = new String[]{"xcopy.exe", in.getAbsolutePath(), out.getAbsolutePath(), "/O", "/Q", "/Y"}; // If the file/ doesn't exist on copying, xcopy will ask whether you want // to create it as a directory or just copy a file, so we always // just put "F" in xcopy's stdin. return Exec(cmd, "F", null) == 1; } } else { // other, assume unix-like cmd = new String[]{"cp", "-f", "-p", in.getAbsolutePath(), out.getAbsolutePath()}; return Exec(cmd) == 0; } } /** * Return the contents of a text file as String */ public static String readFile(File file) throws IOException { String s = System.getProperty("line.separator"); BufferedReader r = new BufferedReader(new FileReader(file)); StringBuffer buf = new StringBuffer(); String line; while ( (line = r.readLine() ) != null) { buf.append(line); buf.append(s); } return buf.toString(); } /** * Change file permissions * <p> * Not supported natively until java 1.6. Bad Java. * Note that the ownerOnly argument differs from Java. When {@code ownerOnly} is * true for Java's {@link File#setReadable}, {@link File#setWritable} or * File.setExecutable(), the other/group permissions are left as they are. * This method resets them instead. When ownerOnly is false, behaviour is * as Java's. * * @param file File to set permissions on * @param read if reading should be allowed * @param write if writing should be allowed * @param exec if executing should be allowed * @param ownerOnly true to set group&world permissions to none, * false to set them all alike */ static public boolean chmod(File file, boolean read, boolean write, boolean exec, boolean ownerOnly) { try { // Try Java 1.6 method first. // This is also compilable on lower java versions boolean ret = true; Method setReadable = File.class.getDeclaredMethod("setReadable", new Class[] { boolean.class, boolean.class }); Method setWritable = File.class.getDeclaredMethod("setWritable", new Class[] { boolean.class, boolean.class }); Method setExecutable = File.class.getDeclaredMethod("setExecutable", new Class[] { boolean.class, boolean.class }); // first remove all permissions if ownerOnly is wanted, because File.set* // doesn't touch other/group permissions when ownerOnly is true. if (ownerOnly) { ret &= (Boolean)setReadable.invoke(file, new Object[]{ false, false }); ret &= (Boolean)setWritable.invoke(file, new Object[]{ false, false }); ret &= (Boolean)setExecutable.invoke(file, new Object[]{ false, false }); } // then set owner/all permissions ret &= (Boolean)setReadable.invoke(file, new Object[] { read, ownerOnly }); ret &= (Boolean)setWritable.invoke(file, new Object[] { write, ownerOnly }); ret &= (Boolean)setExecutable.invoke(file, new Object[] { exec, ownerOnly }); if (logger.isLoggable(Level.FINEST)) { String perms = new String(new char[] { read? 'r' : '-', write? 'w' : '-', exec? 'x' : '-' }) + (ownerOnly ? "user" : "all"); logger.finest("Java 1.6 chmod "+perms+" of "+file+" returns "+ret); } return ret; } catch (InvocationTargetException e) { // throw exceptions caused by set* methods throw (SecurityException)e.getTargetException(); // return false; // (would be unreachable code) } catch (NoSuchMethodException e) { } catch (IllegalAccessException e) { } catch (IllegalArgumentException e) { } try { // fallback to unix command int perm = 0; if (read) perm |= 4; if (write) perm |= 2; if (exec) perm |= 1; String[] chmodcmd = { "chmod", null, file.getPath() }; if (ownerOnly) { Object args[] = { new Integer(perm) }; chmodcmd[1] = String.format("0%1d00", args); } else { Object args[] = {new Integer(perm),new Integer(perm),new Integer(perm)}; chmodcmd[1] = String.format("0%1d%1d%1d", args); } return Exec(chmodcmd) == 0; } catch (Exception e2) { return false; } } /** Create a temporary directory with read-only permissions. * <p> * TODO Current code contains a race-condition. Please see Sun * bug <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4735419">4735419</a> * for a better solution. */ public static File createTempDir(String prefix, File directory) throws IOException { File d = File.createTempFile(prefix, null, directory); d.delete(); d.mkdirs(); chmod(d, true, true, true, true); return d; } public static File createTempDir(String prefix) throws IOException { return createTempDir(prefix, new File(System.getProperty("java.io.tmpdir"))); } /** Execute a command and return the exit code * @throws IOException */ public static int Exec(String[] cmd) throws IOException { // Windows needs to capture input/output or application will hang if (System.getProperty("os.name").startsWith("Windows")) { String foo = ""; return Exec(cmd, foo); } // log String scmd = ""; for (int i=0; i<cmd.length; i++) scmd += " "+cmd[i]; logger.finest("exec"+scmd); // run Process p = Runtime.getRuntime().exec(cmd); int ret = -1; try { ret = p.waitFor(); } catch (InterruptedException e) { // TODO verify this is the right thing to do throw new IOException(e.getMessage()); } // log and return logger.finest("exec"+scmd+" returns "+ret); return ret; } /** Execute a command, enter input on stdin, and return the exit code while storing stdout and stderr. * * @param cmd command to run * @param input String to feed to process's stdin * @param output String to which stdout and stderr is appended, or null * @return process exit code * * @throws IOException */ public static int Exec(String[] cmd, String input, StringBuffer output) throws IOException { // log String scmd = ""; for (int i=0; i<cmd.length; i++) scmd += " "+cmd[i]; logger.finest("exec"+scmd); // run Process p = Runtime.getRuntime().exec(cmd); if (input!=null) { p.getOutputStream().write(input.getBytes()); p.getOutputStream().close(); } // retrieve output String s = System.getProperty("line.separator"); String lineout = null, lineerr = null; BufferedReader stdout = new BufferedReader( new InputStreamReader(p.getInputStream())); BufferedReader stderr = new BufferedReader( new InputStreamReader(p.getErrorStream())); while ( (lineout=stdout.readLine()) != null || (lineerr=stderr.readLine()) != null) { if (lineout!=null && output!=null) output.append(lineout + s); if (lineerr!=null && output!=null) output.append(lineerr + s); } stdout.close(); // log and return int ret = -1; try { ret = p.waitFor(); } catch (InterruptedException e) { // TODO verify this is the right thing to do throw new IOException(e.getMessage()); } logger.finest("exec"+scmd+" returns "+ret); return ret; } /** Execute a command and return the exit code while storing stdout and stderr. * * @param cmd command to run * @param output String to which stdin and stdout is appended. * @return process exit code * * @throws IOException */ public static int Exec(String[] cmd, String output) throws IOException { return Exec(cmd, null, null); } }
true
true
public static boolean CopyFile(File in, File out) throws IOException { String[] cmd; if (System.getProperty("os.name").startsWith("Windows")) { boolean hasRobocopy = false; // windows: use special copy program to retain permissions. // on Vista, "xcopy /O" requires administrative rights, so we // have to resort to using robocopy there. try { int ret = Exec(new String[]{"robocopy.exe"}); if (ret!=0 && ret!=16) throw new InterruptedException(); hasRobocopy = true; } catch (InterruptedException e) { } if (hasRobocopy) { // we have robocopy. But ... its destination filename // needs to be equal to the source filename :( // So we rename any existing file out of the way, copy // the new file, rename it to the new name, and restore // the optional original file. All this is required to // copy a file retaining its permissions. // TODO proper return value handling (!) // move old file out of the way File origFile = new File(out.getParentFile(), in.getName()); File origFileRenamed = null; if (origFile.exists()) { origFileRenamed = new File(origFile.getParentFile(), origFile.getName()+".xxx_tmp"); origFile.renameTo(origFileRenamed); } else { origFile = null; } // copy file to new place cmd = new String[]{"robocopy.exe", in.getParent(), out.getParent(), in.getName(), "/SEC", "/NP", "/NS", "/NC", "/NFL", "/NDL"}; int ret = Exec(cmd); boolean success = ret < 4 && ret >= 0; // rename new file if (success) { new File(out.getParentFile(), in.getName()).renameTo(out); } // move old file to original place again if (origFile!=null) origFileRenamed.renameTo(origFile); return success; } else { // use xcopy instead cmd = new String[]{"xcopy.exe", in.getAbsolutePath(), out.getAbsolutePath(), "/O", "/Q", "/Y"}; // If the file/ doesn't exist on copying, xcopy will ask whether you want // to create it as a directory or just copy a file, so we always // just put "F" in xcopy's stdin. return Exec(cmd, "F", null) == 1; } } else { // other, assume unix-like cmd = new String[]{"cp", "-f", "-p", in.getAbsolutePath(), out.getAbsolutePath()}; return Exec(cmd) == 0; } }
public static boolean CopyFile(File in, File out) throws IOException { String[] cmd; if (System.getProperty("os.name").startsWith("Windows")) { boolean hasRobocopy = false; // windows: use special copy program to retain permissions. // on Vista, "xcopy /O" requires administrative rights, so we // have to resort to using robocopy there. try { int ret = Exec(new String[]{"robocopy.exe"}); if (ret==0 && ret==16) hasRobocopy = true; } catch (Exception e) { } if (hasRobocopy) { // we have robocopy. But ... its destination filename // needs to be equal to the source filename :( // So we rename any existing file out of the way, copy // the new file, rename it to the new name, and restore // the optional original file. All this is required to // copy a file retaining its permissions. // TODO proper return value handling (!) // move old file out of the way File origFile = new File(out.getParentFile(), in.getName()); File origFileRenamed = null; if (origFile.exists()) { origFileRenamed = new File(origFile.getParentFile(), origFile.getName()+".xxx_tmp"); origFile.renameTo(origFileRenamed); } else { origFile = null; } // copy file to new place cmd = new String[]{"robocopy.exe", in.getParent(), out.getParent(), in.getName(), "/SEC", "/NP", "/NS", "/NC", "/NFL", "/NDL"}; int ret = Exec(cmd); boolean success = ret < 4 && ret >= 0; // rename new file if (success) { new File(out.getParentFile(), in.getName()).renameTo(out); } // move old file to original place again if (origFile!=null) origFileRenamed.renameTo(origFile); return success; } else { // use xcopy instead cmd = new String[]{"xcopy.exe", in.getAbsolutePath(), out.getAbsolutePath(), "/O", "/Q", "/Y"}; // If the file/ doesn't exist on copying, xcopy will ask whether you want // to create it as a directory or just copy a file, so we always // just put "F" in xcopy's stdin. return Exec(cmd, "F", null) == 1; } } else { // other, assume unix-like cmd = new String[]{"cp", "-f", "-p", in.getAbsolutePath(), out.getAbsolutePath()}; return Exec(cmd) == 0; } }
diff --git a/netty-compiler/src/main/java/com/kalixia/rawsag/apt/jaxrs/UriTemplatePrecedenceComparator.java b/netty-compiler/src/main/java/com/kalixia/rawsag/apt/jaxrs/UriTemplatePrecedenceComparator.java index a8d8731..b09240d 100644 --- a/netty-compiler/src/main/java/com/kalixia/rawsag/apt/jaxrs/UriTemplatePrecedenceComparator.java +++ b/netty-compiler/src/main/java/com/kalixia/rawsag/apt/jaxrs/UriTemplatePrecedenceComparator.java @@ -1,35 +1,35 @@ package com.kalixia.rawsag.apt.jaxrs; import com.kalixia.rawsag.codecs.jaxrs.UriTemplateUtils; import java.io.Serializable; import java.util.Comparator; import java.util.List; /** * Comparator taking into account JAX-RS Path precedence. * * @see <a href="http://www.j2eeprogrammer.com/2010/11/jax-rs-path-precedence-rules.html">JAX-RS Path precedence rules</a> */ class UriTemplatePrecedenceComparator implements Comparator<String>, Serializable { @Override public int compare(String uriTemplate1, String uriTemplate2) { // sort by the number of literal characters contained within the expression if (uriTemplate1.length() > uriTemplate2.length()) { - return 1; + return -1; } // sort by the number of template expressions within the expression List<String> expressions1 = UriTemplateUtils.extractParametersNames(uriTemplate1); List<String> expressions2 = UriTemplateUtils.extractParametersNames(uriTemplate2); if (expressions1.size() > expressions2.size()) { - return 1; + return -1; } // sort by the number of regular expressions contained within the expression return Integer.compare( UriTemplateUtils.getNumberOfExplicitRegexes(uriTemplate1), UriTemplateUtils.getNumberOfExplicitRegexes(uriTemplate2)); } }
false
true
public int compare(String uriTemplate1, String uriTemplate2) { // sort by the number of literal characters contained within the expression if (uriTemplate1.length() > uriTemplate2.length()) { return 1; } // sort by the number of template expressions within the expression List<String> expressions1 = UriTemplateUtils.extractParametersNames(uriTemplate1); List<String> expressions2 = UriTemplateUtils.extractParametersNames(uriTemplate2); if (expressions1.size() > expressions2.size()) { return 1; } // sort by the number of regular expressions contained within the expression return Integer.compare( UriTemplateUtils.getNumberOfExplicitRegexes(uriTemplate1), UriTemplateUtils.getNumberOfExplicitRegexes(uriTemplate2)); }
public int compare(String uriTemplate1, String uriTemplate2) { // sort by the number of literal characters contained within the expression if (uriTemplate1.length() > uriTemplate2.length()) { return -1; } // sort by the number of template expressions within the expression List<String> expressions1 = UriTemplateUtils.extractParametersNames(uriTemplate1); List<String> expressions2 = UriTemplateUtils.extractParametersNames(uriTemplate2); if (expressions1.size() > expressions2.size()) { return -1; } // sort by the number of regular expressions contained within the expression return Integer.compare( UriTemplateUtils.getNumberOfExplicitRegexes(uriTemplate1), UriTemplateUtils.getNumberOfExplicitRegexes(uriTemplate2)); }
diff --git a/ngrinder-core/src/main/java/net/grinder/SingleConsole.java b/ngrinder-core/src/main/java/net/grinder/SingleConsole.java index c89cd4a1..7d7831f8 100644 --- a/ngrinder-core/src/main/java/net/grinder/SingleConsole.java +++ b/ngrinder-core/src/main/java/net/grinder/SingleConsole.java @@ -1,1023 +1,1019 @@ /* * Copyright (C) 2012 - 2012 NHN Corporation * All rights reserved. * * This file is part of The nGrinder software distribution. Refer to * the file LICENSE which is part of The nGrinder distribution for * licensing details. The nGrinder distribution is available on the * Internet at http://nhnopensource.org/ngrinder * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.grinder; import static org.ngrinder.common.util.Preconditions.checkNotNull; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import net.grinder.common.GrinderException; import net.grinder.common.GrinderProperties; import net.grinder.common.Test; import net.grinder.common.processidentity.AgentIdentity; import net.grinder.common.processidentity.WorkerProcessReport; import net.grinder.console.ConsoleFoundationEx; import net.grinder.console.common.Resources; import net.grinder.console.common.ResourcesImplementation; import net.grinder.console.communication.ProcessControl; import net.grinder.console.communication.ProcessControl.Listener; import net.grinder.console.communication.ProcessControl.ProcessReports; import net.grinder.console.communication.ProcessControlImplementation; import net.grinder.console.distribution.AgentCacheState; import net.grinder.console.distribution.FileDistribution; import net.grinder.console.distribution.FileDistributionHandler; import net.grinder.console.model.ConsoleProperties; import net.grinder.console.model.ModelTestIndex; import net.grinder.console.model.SampleListener; import net.grinder.console.model.SampleModel; import net.grinder.console.model.SampleModelImplementationEx; import net.grinder.console.model.SampleModelViews; import net.grinder.statistics.ExpressionView; import net.grinder.statistics.StatisticsSet; import net.grinder.util.AllocateLowestNumber; import net.grinder.util.ConsolePropertiesFactory; import net.grinder.util.Directory; import net.grinder.util.FileContents; import net.grinder.util.ListenerSupport; import net.grinder.util.ListenerSupport.Informer; import net.grinder.util.thread.Condition; import org.apache.commons.collections.MapUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.mutable.MutableDouble; import org.ngrinder.common.exception.NGrinderRuntimeException; import org.ngrinder.common.util.DateUtil; import org.ngrinder.common.util.ReflectionUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Single console for multiple test. This is the customized version of {@link Console} which grinder * has. * * * @author JunHo Yoon * @since 3.0 */ public class SingleConsole implements Listener, SampleListener { private Thread thread; private ConsoleFoundationEx consoleFoundation; public static final Resources RESOURCE = new ResourcesImplementation("net.grinder.console.common.resources.Console"); public static final Logger LOGGER = LoggerFactory.getLogger(SingleConsole.class); private static final String REPORT_CSV = "output.csv"; private static final String REPORT_DATA = ".data"; private Condition eventSyncCondition = new Condition(); private ProcessReports[] processReports; private boolean cancel = false; // for displaying tps graph in running page private double tpsValue = 0; // for displaying tps graph in running page private double peakTpsForGraph = 0; private SampleModel sampleModel; private SampleModelViews modelView; private long startTime = 0; private Date TPS_LESSTHAN_ZREO_TIME; private Date ERRORS_MORE_THAN_HALF_OF_TOTAL_TPS_TIME; private final ListenerSupport<ConsoleShutdownListener> m_shutdownListeners = new ListenerSupport<ConsoleShutdownListener>(); private final ListenerSupport<SamplingLifeCycleListener> m_samplingLifeCycleListener = new ListenerSupport<SamplingLifeCycleListener>(); private File reportPath; private NumberFormat formatter = new DecimalFormat("###.###"); // private NumberFormat simpleFormatter = new DecimalFormat("###"); private Map<String, Object> statisticData; private boolean sampling = false; //key list in statistic map, used to make sure the order private List<String> csvKeyList = new ArrayList<String>(); private boolean headerAdded = false; Map<String, BufferedWriter> fileWriterMap = new HashMap<String, BufferedWriter>(); /** Current count of sampling. */ private long samplingCount = 0; /** The count of ignoring sampling. */ private int ignoreSampleCount; private boolean firstSampling = true; /** * Currently running thread. */ private int runningThread = 0; /** * Currently running process. */ private int runningProcess = 0; /** * Currently not finished process count. */ private int currentNotFinishedProcessCount = 0; private static final int TOO_LOW_TPS_TIME = 60000; private static final int TOO_MANY_ERROR_TIME = 10000; /** * Constructor with console ip and port. * * @param ip * IP * @param port * PORT */ public SingleConsole(String ip, int port) { this(ip, port, ConsolePropertiesFactory.createEmptyConsoleProperties()); } /** * Constructor with console port and properties. * * @param port * PORT * @param consoleProperties * {@link ConsoleProperties} used. */ public SingleConsole(int port, ConsoleProperties consoleProperties) { this("", port, consoleProperties); } /** * Constructor with IP, port, and properties. * * @param ip * IP * @param port * PORT * @param consoleProperties * {@link ConsoleProperties} used. */ public SingleConsole(String ip, int port, ConsoleProperties consoleProperties) { try { consoleProperties.setConsoleHost(ip); consoleProperties.setConsolePort(port); this.consoleFoundation = new ConsoleFoundationEx(RESOURCE, LOGGER, consoleProperties, eventSyncCondition); modelView = getConsoleComponent(SampleModelViews.class); getConsoleComponent(ProcessControl.class).addProcessStatusListener(this); } catch (GrinderException e) { throw new NGrinderRuntimeException("Exception occurs while creating SingleConsole", e); } } /** * Simple constructor only setting port. It automatically binds all ip addresses. * * @param port * PORT number */ public SingleConsole(int port) { this("", port); } /** * Return the assigned console port. * * @return console port */ public int getConsolePort() { return this.getConsoleProperties().getConsolePort(); } /** * Return the assigned console host. If it's empty, it returns host IP * * @return console host */ public String getConsoleHost() { try { return StringUtils.defaultIfBlank(this.getConsoleProperties().getConsoleHost(), InetAddress.getLocalHost() .getHostAddress()); } catch (UnknownHostException e) { return ""; } } /** * Start console and wait until it's ready to get agent message. */ public void start() { synchronized (eventSyncCondition) { thread = new Thread(new Runnable() { public void run() { consoleFoundation.run(); } }, "SingleConsole on port " + getConsolePort()); thread.setDaemon(true); thread.start(); // 10 second is too big? eventSyncCondition.waitNoInterrruptException(10000); } } /** * For test. */ public void startSync() { consoleFoundation.run(); } /** * Shutdown console and wait until underlying console logic is stop to run. */ public void shutdown() { try { synchronized (this) { consoleFoundation.shutdown(); if (thread != null && !thread.isInterrupted()) { thread.interrupt(); thread.join(1000); } samplingCount = 0; } } catch (Exception e) { throw new NGrinderRuntimeException("Exception occurs while shutting down SingleConsole", e); } finally { // close all report file for (BufferedWriter bw : fileWriterMap.values()) { IOUtils.closeQuietly(bw); } fileWriterMap.clear(); } } /** * Get all attached agents count. * * @return count of agents */ public int getAllAttachedAgentsCount() { return ((ProcessControlImplementation) consoleFoundation.getComponent(ProcessControl.class)) .getNumberOfLiveAgents(); } /** * Get all attached agent list on this console. * * @return agent list */ public List<AgentIdentity> getAllAttachedAgents() { final List<AgentIdentity> agentIdentities = new ArrayList<AgentIdentity>(); AllocateLowestNumber agentIdentity = (AllocateLowestNumber) checkNotNull(ReflectionUtil.getFieldValue( (ProcessControlImplementation) consoleFoundation.getComponent(ProcessControl.class), "m_agentNumberMap"), "m_agentNumberMap on ProcessControlImplemenation is not available in this grinder version"); agentIdentity.forEach(new AllocateLowestNumber.IteratorCallback() { public void objectAndNumber(Object object, int number) { agentIdentities.add((AgentIdentity) object); } }); return agentIdentities; } /** * Get the console Component. * * @param <T> * componentType component type * @param componentType * component type * @return the consoleFoundation */ public <T> T getConsoleComponent(Class<T> componentType) { return consoleFoundation.getComponent(componentType); } /** * Get {@link ConsoleProperties} which is used to configure {@link SingleConsole}. * * @return {@link ConsoleProperties} */ public ConsoleProperties getConsoleProperties() { return getConsoleComponent(ConsoleProperties.class); } /** * Start test with given {@link GrinderProperties} * * @param properties * {@link GrinderProperties} * @return current time */ public long startTest(GrinderProperties properties) { properties.setInt(GrinderProperties.CONSOLE_PORT, getConsolePort()); getConsoleComponent(ProcessControl.class).startWorkerProcesses(properties); this.startTime = System.currentTimeMillis(); return this.startTime; } public void setDistributionDirectory(File filePath) { final ConsoleProperties properties = getConsoleComponent(ConsoleProperties.class); Directory directory; try { directory = new Directory(filePath); properties.setAndSaveDistributionDirectory(directory); } catch (Exception e) { LOGGER.error(e.getMessage(), e); throw new NGrinderRuntimeException(e.getMessage(), e); } } public void cancel() { cancel = true; } private boolean shouldEnable(FileDistribution fileDistribution) { return fileDistribution.getAgentCacheState().getOutOfDate(); } /** * Distribute files on given filePath to attached agents. * * @param filePath * the distribution files */ public void distributeFiles(File filePath) { setDistributionDirectory(filePath); distributFiles(); } /** * Distribute files on agents. */ public void distributFiles() { final FileDistribution fileDistribution = (FileDistribution) getConsoleComponent(FileDistribution.class); final AgentCacheState agentCacheState = fileDistribution.getAgentCacheState(); final Condition cacheStateCondition = new Condition(); agentCacheState.addListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent ignored) { synchronized (cacheStateCondition) { cacheStateCondition.notifyAll(); } } }); final FileDistributionHandler distributionHandler = fileDistribution.getHandler(); // When cancel is called.. stop processing. while (!cancel) { try { final FileDistributionHandler.Result result = distributionHandler.sendNextFile(); if (result == null) { break; } } catch (FileContents.FileContentsException e) { throw new NGrinderRuntimeException("Error while distribute files for " + getConsolePort()); } // The cache status is updated asynchronously by agent reports. // If we have a listener, we wait for up to five seconds for all // agents to indicate that they are up to date. synchronized (cacheStateCondition) { for (int i = 0; i < 5 && shouldEnable(fileDistribution); ++i) { cacheStateCondition.waitNoInterrruptException(1000); } } } } public void waitUntilAgentConnected(int size) { int trial = 1; while (trial++ < 10) { // when agent finished one test, processReports will be updated as // null if (processReports == null || this.processReports.length != size) { synchronized (eventSyncCondition) { eventSyncCondition.waitNoInterrruptException(1000); } } else if (isCanceled()) { return; } else { return; } } throw new NGrinderRuntimeException("Connection is not completed until 10 sec"); } /** * Wait until runningThread is 0. If it's over 10 seconds, Exception occurs */ public void waitUntilAllAgentDisconnected() { int trial = 1; while (trial++ < 20) { // when agent finished one test, processReports will be updated as // null if (this.runningThread != 0) { synchronized (eventSyncCondition) { eventSyncCondition.waitNoInterrruptException(500); } } else { return; } } throw new NGrinderRuntimeException("Connection is not completed until 10 sec"); } /** * Check all test is finished. To be safe, this counts thread count and not finished * workprocess. If one of them is 0, It thinks test is finished. * * @return true if finished */ public boolean isAllTestFinished() { synchronized (this) { // Mostly running thread count is ok to determine it's finished. if (this.runningThread == 0) { return true; // However sometimes runningThread is over 0 but all processs is // marked as // FINISHED.. It can be treated as finished status as well. } else if (this.currentNotFinishedProcessCount == 0) { return true; } return false; } } public void setTpsValue(double newValue) { peakTpsForGraph = Math.max(peakTpsForGraph, newValue); tpsValue = newValue; } public double getTpsValues() { return tpsValue; } public long getStartTime() { return startTime; } public long getCurrentRunningTime() { return new Date().getTime() - startTime; } @Override public void update(StatisticsSet intervalStatistics, StatisticsSet cumulativeStatistics) { LOGGER.info("update stat..."); if (!sampling) { return; } if (samplingCount++ < ignoreSampleCount) { return; } if (firstSampling == true) { firstSampling = false; informTestSamplingStart(); } setTpsValue(sampleModel.getTPSExpression().getDoubleValue(intervalStatistics)); checkTooLowTps(getTpsValues()); updateStatistics(); @SuppressWarnings("unchecked") List<Map<String, Object>> lastSampleStatistics = (List<Map<String, Object>>) statisticData .get("lastSampleStatistics"); // record the latest sample into report files. // in lastSampleStatistics, there could be several sub-tests. We // will record the separate and total statistic value. if (lastSampleStatistics != null && lastSampleStatistics.size() > 0) { double tpsSum = 0; double errors = 0; StringBuilder csvLine = new StringBuilder(); StringBuilder csvHeader = new StringBuilder(); csvHeader.append("DateTime"); //get the key list from lastStatistic map, use list to keep the order if (csvKeyList.size() == 0) { - LOGGER.info("add csv key in list ..."); for (String eachKey : lastSampleStatistics.get(0).keySet()) { if (!eachKey.equals("Peak_TPS")) { csvKeyList.add(eachKey); } } - LOGGER.info("csv key list size is :{}", csvKeyList.size()); } //store the total statistic value in valueMap Map<String, Object> totalValueMap = new HashMap<String, Object>(); // add date time into csv as first column // FIXME this date time interval should be 1 second. // but the system can not make sure about that. csvLine.append(DateUtil.dateToString(new Date())); int testIndex = 0; for (Map<String, Object> lastStatistic : lastSampleStatistics) { testIndex++; tpsSum += (Double) lastStatistic.get("TPS"); errors += (Double) lastStatistic.get("Errors"); //step.1 add separate statistic data into csv line string. And // calculate the total statistic data. for (Entry<String, Object> each : lastStatistic.entrySet()) { // Peak TPS is not meaningful for CSV report for every second. if (each.getKey().equals("Peak_TPS")) { continue; } if (!headerAdded) { csvHeader.append(","); csvHeader.append(each.getKey() + "-" + testIndex); } Object val = each.getValue(); Object valueInTotalMap = totalValueMap.get(each.getKey()); if (val instanceof Double) { // number value in lastStatistic is Double, we add every // test's double value into totalValueMap, so we use // MutableDouble in valueMap, to avoid creating too many // objects. MutableDouble mutableDouble = (MutableDouble) valueInTotalMap; if (mutableDouble == null) { mutableDouble = new MutableDouble(0); totalValueMap.put(each.getKey(), mutableDouble); } mutableDouble.add((Double) val); } else if (String.valueOf(val).equals("null")) { - LOGGER.info("There is a null value for:{}", each.getKey()); // if it is null, just assume it is 0. // The value is a String "null" // valueMap.put(each.getKey(), new MutableDouble(0)); if (valueInTotalMap == null) { totalValueMap.put(each.getKey(), new MutableDouble(0)); } //just skip it, if there is already one key for that } else { // there are some String type object like test description. totalValueMap.put(each.getKey(), val); } if (!each.getKey().equals("Peak_TPS")) { csvLine.append(","); csvLine.append(formatValue(val)); } } } - LOGGER.info("totalValueMap size is :{}", totalValueMap.size()); try { // add header into csv file. if (!headerAdded) { LOGGER.info("Add csv file header."); //add header for total data for (String key : csvKeyList) { csvHeader.append(","); csvHeader.append(key); } writeCSVDataLine(csvHeader.toString()); headerAdded = true; } for (Entry<String, Object> each : totalValueMap.entrySet()) { writeReportData(each.getKey() + REPORT_DATA, formatValue(each.getValue())); } // add total test report into csv file. for (String key : csvKeyList) { csvLine.append(","); csvLine.append(formatValue(totalValueMap.get(key))); } writeCSVDataLine(csvLine.toString()); } catch (IOException e) { LOGGER.error("Write report data failed :" + e.getMessage(), e); } // In case of error.. checkTooManyError(tpsSum, errors); } } /** * Check if the TPS is too low. the TPS is lower than 0.001 for 2 minutes, It notifies it to the * {@link ConsoleShutdownListener} * * @param tps * current TPS */ private void checkTooLowTps(double tps) { // If the tps is low that it's can be the agents or scripts goes wrong. if (tps < 0.001) { if (TPS_LESSTHAN_ZREO_TIME == null) { TPS_LESSTHAN_ZREO_TIME = new Date(); } else if (new Date().getTime() - TPS_LESSTHAN_ZREO_TIME.getTime() >= TOO_LOW_TPS_TIME) { LOGGER.warn("Stop the test because its tps is less than 0.001 for more than {} minitue.", TOO_LOW_TPS_TIME / 60000); getListeners().apply(new Informer<ConsoleShutdownListener>() { public void inform(ConsoleShutdownListener listener) { listener.readyToStop(StopReason.TOO_LOW_TPS); } }); TPS_LESSTHAN_ZREO_TIME = null; } } else { TPS_LESSTHAN_ZREO_TIME = null; // only if tps value is not too small ,It should be displayed } } /** * Check if too many error occurs. If the half of total transaction is error for 10 sec. It * notifies the {@link ConsoleShutdownListener} * * @param tpsSum * sum of tps * @param errors * count of errors. */ private void checkTooManyError(double tpsSum, double errors) { if (tpsSum / 2 < errors) { if (ERRORS_MORE_THAN_HALF_OF_TOTAL_TPS_TIME == null) { ERRORS_MORE_THAN_HALF_OF_TOTAL_TPS_TIME = new Date(); } else if (new Date().getTime() - ERRORS_MORE_THAN_HALF_OF_TOTAL_TPS_TIME.getTime() >= TOO_MANY_ERROR_TIME) { LOGGER.warn("Stop the test because test error is more than half of total tps for more than {} seconds.", TOO_MANY_ERROR_TIME / 1000); getListeners().apply(new Informer<ConsoleShutdownListener>() { public void inform(ConsoleShutdownListener listener) { listener.readyToStop(StopReason.TOO_MANY_ERRORS); } }); ERRORS_MORE_THAN_HALF_OF_TOTAL_TPS_TIME = null; } } } /** * To update statistics data while test is running */ private void updateStatistics() { Map<String, Object> result = new ConcurrentHashMap<String, Object>(); result.put("test_time", getCurrentRunningTime() / 1000); List<Map<String, Object>> cumulativeStatistics = new ArrayList<Map<String, Object>>(); List<Map<String, Object>> lastSampleStatistics = new ArrayList<Map<String, Object>>(); ExpressionView[] views = modelView.getCumulativeStatisticsView().getExpressionViews(); ModelTestIndex modelIndex = ((SampleModelImplementationEx) sampleModel).getModelTestIndex(); if (modelIndex != null) { for (int i = 0; i < modelIndex.getNumberOfTests(); i++) { Map<String, Object> statistics = new HashMap<String, Object>(); Map<String, Object> lastStatistics = new HashMap<String, Object>(); Test test = modelIndex.getTest(i); statistics.put("testNumber", test.getNumber()); // remove description from statistic, otherwise, it will be // saved in report data. // and the character like ',' in this field will affect the csv // file too. lastStatistics.put("testDescription", test.getDescription()); lastStatistics.put("testNumber", test.getNumber()); StatisticsSet set = modelIndex.getCumulativeStatistics(i); StatisticsSet lastSet = modelIndex.getLastSampleStatistics(i); for (ExpressionView expressionView : views) { statistics.put(expressionView.getDisplayName().replaceAll("\\s+", "_"), getRealDoubleValue(expressionView.getExpression().getDoubleValue(set))); lastStatistics.put(expressionView.getDisplayName().replaceAll("\\s+", "_"), getRealDoubleValue(expressionView.getExpression().getDoubleValue(lastSet))); } cumulativeStatistics.add(statistics); lastSampleStatistics.add(lastStatistics); } } StatisticsSet totalSet = sampleModel.getTotalCumulativeStatistics(); Map<String, Object> totalStatistics = new HashMap<String, Object>(); for (ExpressionView expressionView : views) { totalStatistics.put(expressionView.getDisplayName().replaceAll("\\s+", "_"), getRealDoubleValue(expressionView.getExpression().getDoubleValue(totalSet))); } result.put("totalStatistics", totalStatistics); result.put("cumulativeStatistics", cumulativeStatistics); result.put("lastSampleStatistics", lastSampleStatistics); result.put("tpsChartData", getTpsValues()); result.put("peakTpsForGraph", this.peakTpsForGraph); synchronized (this) { result.put(GrinderConstants.P_PROCESS, this.runningProcess); result.put(GrinderConstants.P_THREAD, this.runningThread); result.put("success", !isAllTestFinished()); } // Finally overwrite.. current one. this.statisticData = result; } public long getCurrentExecutionCount() { Map<?, ?> totalStatistics = (Map<?, ?>) getStatictisData().get("totalStatistics"); Double testCount = MapUtils.getDoubleValue(totalStatistics, "Tests", 0D); Double errorCount = MapUtils.getDoubleValue(totalStatistics, "Errors", 0D); return testCount.longValue() + errorCount.longValue(); } private static Object getRealDoubleValue(Double doubleValue) { return (doubleValue.isInfinite() || doubleValue.isNaN()) ? null : doubleValue; } /** * Listener interface to detect sampling start and end point. * * @author JunHo Yoon */ public interface SamplingLifeCycleListener { /** * Called when the sampling is started. */ void onSamplingStarted(); /** * Called when the sampling is started. */ void onSamplingEnded(); } /** * Listener interface to detect console shutdown condition. * * @author JunHo Yoon */ public interface ConsoleShutdownListener { /** * Called when the console should be shutdowned. * * @param stopReason * the reason of shutdown.. */ void readyToStop(StopReason stopReason); } /** * get the list of added {@link ConsoleShutdownListener}. + * * @return the list of added {@link ConsoleShutdownListener}. * @see ConsoleShutdownListener */ public ListenerSupport<ConsoleShutdownListener> getListeners() { return this.m_shutdownListeners; } /** * Add {@link ConsoleShutdownListener} to get notified when console is shutdowned. * * @param listener * listener to be used. */ public void addListener(ConsoleShutdownListener listener) { m_shutdownListeners.add(listener); } /** * Add {@link SamplingLifeCycleListener} to get notified when sampling is started and ended. * * @param listener * listener to be used. * */ public void addSamplingLifeCyleListener(SamplingLifeCycleListener listener) { m_samplingLifeCycleListener.add(listener); } /** * Update process status of agents. In this method */ @Override public void update(ProcessReports[] processReports) { synchronized (eventSyncCondition) { checkExeuctionErrors(processReports); this.processReports = processReports; // The reason I passed porcessReport as parameter here is to prevent // the synchronization problem. updateCurrentProcessAndThread(processReports); eventSyncCondition.notifyAll(); } } private void checkExeuctionErrors(ProcessReports[] processReports) { if (samplingCount == 0 && ArrayUtils.isNotEmpty(this.processReports) && ArrayUtils.isEmpty(processReports)) { getListeners().apply(new Informer<ConsoleShutdownListener>() { public void inform(ConsoleShutdownListener listener) { listener.readyToStop(StopReason.SCRIPT_ERROR); } }); } } /** * Update current processes and threads * * @param processReports * ProcessReports array. */ private void updateCurrentProcessAndThread(ProcessReports[] processReports) { int notFinishedWorkerCount = 0; int processCount = 0; int threadCount = 0; // Per agents for (ProcessReports agentReport : processReports) { // Per process for (WorkerProcessReport processReport : agentReport.getWorkerProcessReports()) { // There might be the processes which is not finished but no // running thread in it. if (processReport.getState() != 3) { notFinishedWorkerCount++; } processCount++; threadCount += processReport.getNumberOfRunningThreads(); } } synchronized (this) { this.runningProcess = processCount; this.runningThread = threadCount; this.currentNotFinishedProcessCount = notFinishedWorkerCount; } } private void writeReportData(String name, String value) throws IOException { try { BufferedWriter bw = fileWriterMap.get(name); if (bw == null) { bw = new BufferedWriter(new FileWriter(new File(this.reportPath, name), true)); fileWriterMap.put(name, bw); } bw.write(value); bw.newLine(); bw.flush(); } catch (Exception e) { LOGGER.error(e.getMessage(), e); throw new NGrinderRuntimeException(e.getMessage(), e); } finally { // IOUtils.closeQuietly(write); // IOUtils.closeQuietly(bw); } } private void writeCSVDataLine(String line) throws IOException { writeReportData(REPORT_CSV, line); } private String formatValue(Object val) { if (val instanceof Double) { return formatter.format(val); } else if (String.valueOf(val).equals("null")) { // if target server is too slow, there is no response in this // second, then the // statistic data // like mean time will be null. // currently, we set these kind of value as 0. return "0"; } return String.valueOf(val); } /** * Get the statistics data. This method returns the map whose key is string and it's mapped to * specific value. Please refer {@link #updateStatistics()} * * @return map which contains statistics data */ public Map<String, Object> getStatictisData() { return this.statisticData != null ? this.statisticData : getNullStatictisData(); } private Map<String, Object> getNullStatictisData() { Map<String, Object> result = new ConcurrentHashMap<String, Object>(); result.put("test_time", getCurrentRunningTime() / 1000); return result; } /** * Get report path * * @return report path */ public File getReportPath() { return reportPath; } /** * Set report path * * @param reportPath * path in which report will be stored. */ public void setReportPath(File reportPath) { checkNotNull(reportPath, "report folder should not be empty!").mkdirs(); this.reportPath = reportPath; } /** * Send stop message to attached agents to shutdown. */ public void sendStopMessageToAgents() { getConsoleComponent(ProcessControl.class).stopAgentAndWorkerProcesses(); } /** * Start sampling with ignore count. * * @param ignoreSampleCount * the count how many sample will be ignored. */ public void startSampling(int ignoreSampleCount) { this.ignoreSampleCount = ignoreSampleCount; this.sampling = true; LOGGER.info("Sampling is started"); this.sampleModel = getConsoleComponent(SampleModelImplementationEx.class); this.sampleModel.addTotalSampleListener(this); this.sampleModel.start(); } /** * Stop sampling */ public void unregisterSampling() { this.currentNotFinishedProcessCount = 0; this.sampling = false; this.sampleModel = getConsoleComponent(SampleModelImplementationEx.class); this.sampleModel.reset(); this.sampleModel.stop(); LOGGER.info("Sampling is stopped"); informTestSamplingEnd(); } private void informTestSamplingStart() { m_samplingLifeCycleListener.apply(new Informer<SamplingLifeCycleListener>() { @Override public void inform(SamplingLifeCycleListener listener) { listener.onSamplingStarted(); } }); } private void informTestSamplingEnd() { m_samplingLifeCycleListener.apply(new Informer<SamplingLifeCycleListener>() { @Override public void inform(SamplingLifeCycleListener listener) { listener.onSamplingEnded(); } }); } /** * If the test error is over 20%.. return true; * * @return true if error is over 20% */ public boolean hasTooManyError() { long currentTestsCount = getCurrentExecutionCount(); double errors = MapUtils.getDoubleValue((Map<?, ?>) getStatictisData().get("totalStatistics"), "Errors", 0D); return currentTestsCount == 0 ? false : (errors / currentTestsCount) > 0.2; } /** * Check this singleConsole is canceled. * * @return true if yes. */ public boolean isCanceled() { return cancel; } }
false
true
public void update(StatisticsSet intervalStatistics, StatisticsSet cumulativeStatistics) { LOGGER.info("update stat..."); if (!sampling) { return; } if (samplingCount++ < ignoreSampleCount) { return; } if (firstSampling == true) { firstSampling = false; informTestSamplingStart(); } setTpsValue(sampleModel.getTPSExpression().getDoubleValue(intervalStatistics)); checkTooLowTps(getTpsValues()); updateStatistics(); @SuppressWarnings("unchecked") List<Map<String, Object>> lastSampleStatistics = (List<Map<String, Object>>) statisticData .get("lastSampleStatistics"); // record the latest sample into report files. // in lastSampleStatistics, there could be several sub-tests. We // will record the separate and total statistic value. if (lastSampleStatistics != null && lastSampleStatistics.size() > 0) { double tpsSum = 0; double errors = 0; StringBuilder csvLine = new StringBuilder(); StringBuilder csvHeader = new StringBuilder(); csvHeader.append("DateTime"); //get the key list from lastStatistic map, use list to keep the order if (csvKeyList.size() == 0) { LOGGER.info("add csv key in list ..."); for (String eachKey : lastSampleStatistics.get(0).keySet()) { if (!eachKey.equals("Peak_TPS")) { csvKeyList.add(eachKey); } } LOGGER.info("csv key list size is :{}", csvKeyList.size()); } //store the total statistic value in valueMap Map<String, Object> totalValueMap = new HashMap<String, Object>(); // add date time into csv as first column // FIXME this date time interval should be 1 second. // but the system can not make sure about that. csvLine.append(DateUtil.dateToString(new Date())); int testIndex = 0; for (Map<String, Object> lastStatistic : lastSampleStatistics) { testIndex++; tpsSum += (Double) lastStatistic.get("TPS"); errors += (Double) lastStatistic.get("Errors"); //step.1 add separate statistic data into csv line string. And // calculate the total statistic data. for (Entry<String, Object> each : lastStatistic.entrySet()) { // Peak TPS is not meaningful for CSV report for every second. if (each.getKey().equals("Peak_TPS")) { continue; } if (!headerAdded) { csvHeader.append(","); csvHeader.append(each.getKey() + "-" + testIndex); } Object val = each.getValue(); Object valueInTotalMap = totalValueMap.get(each.getKey()); if (val instanceof Double) { // number value in lastStatistic is Double, we add every // test's double value into totalValueMap, so we use // MutableDouble in valueMap, to avoid creating too many // objects. MutableDouble mutableDouble = (MutableDouble) valueInTotalMap; if (mutableDouble == null) { mutableDouble = new MutableDouble(0); totalValueMap.put(each.getKey(), mutableDouble); } mutableDouble.add((Double) val); } else if (String.valueOf(val).equals("null")) { LOGGER.info("There is a null value for:{}", each.getKey()); // if it is null, just assume it is 0. // The value is a String "null" // valueMap.put(each.getKey(), new MutableDouble(0)); if (valueInTotalMap == null) { totalValueMap.put(each.getKey(), new MutableDouble(0)); } //just skip it, if there is already one key for that } else { // there are some String type object like test description. totalValueMap.put(each.getKey(), val); } if (!each.getKey().equals("Peak_TPS")) { csvLine.append(","); csvLine.append(formatValue(val)); } } } LOGGER.info("totalValueMap size is :{}", totalValueMap.size()); try { // add header into csv file. if (!headerAdded) { LOGGER.info("Add csv file header."); //add header for total data for (String key : csvKeyList) { csvHeader.append(","); csvHeader.append(key); } writeCSVDataLine(csvHeader.toString()); headerAdded = true; } for (Entry<String, Object> each : totalValueMap.entrySet()) { writeReportData(each.getKey() + REPORT_DATA, formatValue(each.getValue())); } // add total test report into csv file. for (String key : csvKeyList) { csvLine.append(","); csvLine.append(formatValue(totalValueMap.get(key))); } writeCSVDataLine(csvLine.toString()); } catch (IOException e) { LOGGER.error("Write report data failed :" + e.getMessage(), e); } // In case of error.. checkTooManyError(tpsSum, errors); } }
public void update(StatisticsSet intervalStatistics, StatisticsSet cumulativeStatistics) { LOGGER.info("update stat..."); if (!sampling) { return; } if (samplingCount++ < ignoreSampleCount) { return; } if (firstSampling == true) { firstSampling = false; informTestSamplingStart(); } setTpsValue(sampleModel.getTPSExpression().getDoubleValue(intervalStatistics)); checkTooLowTps(getTpsValues()); updateStatistics(); @SuppressWarnings("unchecked") List<Map<String, Object>> lastSampleStatistics = (List<Map<String, Object>>) statisticData .get("lastSampleStatistics"); // record the latest sample into report files. // in lastSampleStatistics, there could be several sub-tests. We // will record the separate and total statistic value. if (lastSampleStatistics != null && lastSampleStatistics.size() > 0) { double tpsSum = 0; double errors = 0; StringBuilder csvLine = new StringBuilder(); StringBuilder csvHeader = new StringBuilder(); csvHeader.append("DateTime"); //get the key list from lastStatistic map, use list to keep the order if (csvKeyList.size() == 0) { for (String eachKey : lastSampleStatistics.get(0).keySet()) { if (!eachKey.equals("Peak_TPS")) { csvKeyList.add(eachKey); } } } //store the total statistic value in valueMap Map<String, Object> totalValueMap = new HashMap<String, Object>(); // add date time into csv as first column // FIXME this date time interval should be 1 second. // but the system can not make sure about that. csvLine.append(DateUtil.dateToString(new Date())); int testIndex = 0; for (Map<String, Object> lastStatistic : lastSampleStatistics) { testIndex++; tpsSum += (Double) lastStatistic.get("TPS"); errors += (Double) lastStatistic.get("Errors"); //step.1 add separate statistic data into csv line string. And // calculate the total statistic data. for (Entry<String, Object> each : lastStatistic.entrySet()) { // Peak TPS is not meaningful for CSV report for every second. if (each.getKey().equals("Peak_TPS")) { continue; } if (!headerAdded) { csvHeader.append(","); csvHeader.append(each.getKey() + "-" + testIndex); } Object val = each.getValue(); Object valueInTotalMap = totalValueMap.get(each.getKey()); if (val instanceof Double) { // number value in lastStatistic is Double, we add every // test's double value into totalValueMap, so we use // MutableDouble in valueMap, to avoid creating too many // objects. MutableDouble mutableDouble = (MutableDouble) valueInTotalMap; if (mutableDouble == null) { mutableDouble = new MutableDouble(0); totalValueMap.put(each.getKey(), mutableDouble); } mutableDouble.add((Double) val); } else if (String.valueOf(val).equals("null")) { // if it is null, just assume it is 0. // The value is a String "null" // valueMap.put(each.getKey(), new MutableDouble(0)); if (valueInTotalMap == null) { totalValueMap.put(each.getKey(), new MutableDouble(0)); } //just skip it, if there is already one key for that } else { // there are some String type object like test description. totalValueMap.put(each.getKey(), val); } if (!each.getKey().equals("Peak_TPS")) { csvLine.append(","); csvLine.append(formatValue(val)); } } } try { // add header into csv file. if (!headerAdded) { LOGGER.info("Add csv file header."); //add header for total data for (String key : csvKeyList) { csvHeader.append(","); csvHeader.append(key); } writeCSVDataLine(csvHeader.toString()); headerAdded = true; } for (Entry<String, Object> each : totalValueMap.entrySet()) { writeReportData(each.getKey() + REPORT_DATA, formatValue(each.getValue())); } // add total test report into csv file. for (String key : csvKeyList) { csvLine.append(","); csvLine.append(formatValue(totalValueMap.get(key))); } writeCSVDataLine(csvLine.toString()); } catch (IOException e) { LOGGER.error("Write report data failed :" + e.getMessage(), e); } // In case of error.. checkTooManyError(tpsSum, errors); } }
diff --git a/BusesSpb/src/main/java/ru/slavabulgakov/busesspb/Network/StationsContainer.java b/BusesSpb/src/main/java/ru/slavabulgakov/busesspb/Network/StationsContainer.java index f71d00c..84177f4 100644 --- a/BusesSpb/src/main/java/ru/slavabulgakov/busesspb/Network/StationsContainer.java +++ b/BusesSpb/src/main/java/ru/slavabulgakov/busesspb/Network/StationsContainer.java @@ -1,71 +1,75 @@ package ru.slavabulgakov.busesspb.Network; import com.google.android.gms.maps.model.LatLng; import java.util.ArrayList; import ru.slavabulgakov.busesspb.model.TransportKind; import ru.slavabulgakov.busesspb.paths.Point; import ru.slavabulgakov.busesspb.paths.Station; public class StationsContainer extends LoaderContainer { /** * */ private static final long serialVersionUID = 1L; public StationsContainer() { super("http://futbix.ru/busesspb/v1_0/stationsdata/", "stationsNames.txt", "v2_stationsNames.ser"); } @SuppressWarnings("unchecked") @Override public void handler(Object obj) { super.handler(obj); ArrayList<String> strings = null; if (obj.getClass() == String.class) { String[] s = ((String)obj).split("\n"); strings = new ArrayList<String>(); for (int i = 0; i < s.length; i++) { strings.add(s[i]); } } else { strings = (ArrayList<String>)obj; } ArrayList<Object> data = new ArrayList<Object>(); strings.remove(0); for (String line : strings) { // 17609,17609,"ПР. АВИАКОНСТРУКТОРОВ, 38",60.027851,30.222640,0,2,bus String items[] = line.split(","); + int stationNameIndex = 5; + if (items.length - stationNameIndex < 0) { + continue; + } Station station = new Station(); station.id = items[0]; int length = 0; - for (int i = items.length - 5; i < items.length; i++) { + for (int i = items.length - stationNameIndex; i < items.length; i++) { length += items[i].length() + 1; } station.name = line.substring(items[0].length() + 1 + items[1].length() + 1, line.length() - length); double lat = Double.parseDouble(items[items.length - 5]); double lng = Double.parseDouble(items[items.length - 4]); station.point = new Point(new LatLng(lat, lng)); String kind = items[items.length - 1]; if (kind.equals("bus")) { station.kind = TransportKind.Bus; } else if (kind.equals("tram")) { station.kind = TransportKind.Tram; } else if (kind.equals("trolley")) { station.kind = TransportKind.Trolley; } else if (kind.equals("ship")) { station.kind = TransportKind.Ship; } else { station.kind = TransportKind.None; } data.add(station); } _data = data; } }
false
true
public void handler(Object obj) { super.handler(obj); ArrayList<String> strings = null; if (obj.getClass() == String.class) { String[] s = ((String)obj).split("\n"); strings = new ArrayList<String>(); for (int i = 0; i < s.length; i++) { strings.add(s[i]); } } else { strings = (ArrayList<String>)obj; } ArrayList<Object> data = new ArrayList<Object>(); strings.remove(0); for (String line : strings) { // 17609,17609,"ПР. АВИАКОНСТРУКТОРОВ, 38",60.027851,30.222640,0,2,bus String items[] = line.split(","); Station station = new Station(); station.id = items[0]; int length = 0; for (int i = items.length - 5; i < items.length; i++) { length += items[i].length() + 1; } station.name = line.substring(items[0].length() + 1 + items[1].length() + 1, line.length() - length); double lat = Double.parseDouble(items[items.length - 5]); double lng = Double.parseDouble(items[items.length - 4]); station.point = new Point(new LatLng(lat, lng)); String kind = items[items.length - 1]; if (kind.equals("bus")) { station.kind = TransportKind.Bus; } else if (kind.equals("tram")) { station.kind = TransportKind.Tram; } else if (kind.equals("trolley")) { station.kind = TransportKind.Trolley; } else if (kind.equals("ship")) { station.kind = TransportKind.Ship; } else { station.kind = TransportKind.None; } data.add(station); } _data = data; }
public void handler(Object obj) { super.handler(obj); ArrayList<String> strings = null; if (obj.getClass() == String.class) { String[] s = ((String)obj).split("\n"); strings = new ArrayList<String>(); for (int i = 0; i < s.length; i++) { strings.add(s[i]); } } else { strings = (ArrayList<String>)obj; } ArrayList<Object> data = new ArrayList<Object>(); strings.remove(0); for (String line : strings) { // 17609,17609,"ПР. АВИАКОНСТРУКТОРОВ, 38",60.027851,30.222640,0,2,bus String items[] = line.split(","); int stationNameIndex = 5; if (items.length - stationNameIndex < 0) { continue; } Station station = new Station(); station.id = items[0]; int length = 0; for (int i = items.length - stationNameIndex; i < items.length; i++) { length += items[i].length() + 1; } station.name = line.substring(items[0].length() + 1 + items[1].length() + 1, line.length() - length); double lat = Double.parseDouble(items[items.length - 5]); double lng = Double.parseDouble(items[items.length - 4]); station.point = new Point(new LatLng(lat, lng)); String kind = items[items.length - 1]; if (kind.equals("bus")) { station.kind = TransportKind.Bus; } else if (kind.equals("tram")) { station.kind = TransportKind.Tram; } else if (kind.equals("trolley")) { station.kind = TransportKind.Trolley; } else if (kind.equals("ship")) { station.kind = TransportKind.Ship; } else { station.kind = TransportKind.None; } data.add(station); } _data = data; }
diff --git a/src/uk/me/parabola/mkgmap/build/MapSplitter.java b/src/uk/me/parabola/mkgmap/build/MapSplitter.java index b9341b5a..a9e0ebd1 100644 --- a/src/uk/me/parabola/mkgmap/build/MapSplitter.java +++ b/src/uk/me/parabola/mkgmap/build/MapSplitter.java @@ -1,212 +1,211 @@ /* * Copyright (C) 2007 Steve Ratcliffe * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * 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. * * * Author: Steve Ratcliffe * Create date: 20-Jan-2007 */ package uk.me.parabola.mkgmap.build; import java.util.ArrayList; import java.util.List; import uk.me.parabola.imgfmt.app.Area; import uk.me.parabola.imgfmt.app.trergn.Zoom; import uk.me.parabola.log.Logger; import uk.me.parabola.mkgmap.general.MapDataSource; /** * The map must be split into subdivisions. To do this we start off with * one of these MapAreas containing all of the map and split it up into * smaller and smaller areas until each area is below a maximum size and * contains fewer than a maximum number of map features. * * @author Steve Ratcliffe */ class MapSplitter { private static final Logger log = Logger.getLogger(MapSplitter.class); private final MapDataSource mapSource; // There is an absolute largest size as offsets are in 16 bits, we are // staying safely inside it however. private static final int MAX_DIVISION_SIZE = 0x7fff; // The maximum region size. Note that the offset to the start of a section // has to fit into 16 bits, the end of the last section could be beyond the // 16 bit limit. Leave a little room for the region pointers private static final int MAX_RGN_SIZE = 0xfff8; // The maximum number of lines. NET points to lines in subdivision // using bytes. private static final int MAX_NUM_LINES = 0xff; private static final int MAX_NUM_POINTS = 0xff; // maximum allowed amounts of points/lines/shapes with extended types // real limits are not known but if these values are too large, data // goes missing (lines disappear, etc.) private static final int MAX_XT_POINTS_SIZE = 0xff00; private static final int MAX_XT_LINES_SIZE = 0xff00; private static final int MAX_XT_SHAPES_SIZE = 0xff00; private final Zoom zoom; /** * Creates a list of map areas and keeps splitting them down until they * are small enough. There is both a maximum size to an area and also * a maximum number of things that will fit inside each division. * * Since these are not well defined (it all depends on how complicated the * features are etc), we shall underestimate the maximum sizes and probably * make them configurable. * * @param mapSource The input map data source. * @param zoom The zoom level that we need to split for. */ MapSplitter(MapDataSource mapSource, Zoom zoom) { this.mapSource = mapSource; this.zoom = zoom; } /** * This splits the map into a series of smaller areas. There is both a * maximum size and a maximum number of features that can be contained * in a single area. * * This routine is not called recursively. * * @return An array of map areas, each of which is within the size limit * and the limit on the number of features. */ public MapArea[] split() { log.debug("orig area", mapSource.getBounds()); MapArea ma = initialArea(mapSource); MapArea[] areas = splitMaxSize(ma); // Now step through each area and see if any have too many map features // in them. For those that do, we further split them. This is done // recursively until everything fits. List<MapArea> alist = new ArrayList<MapArea>(); addAreasToList(areas, alist, 0); MapArea[] results = new MapArea[alist.size()]; return alist.toArray(results); } /** * Adds map areas to a list. If an area has too many features, then it * is split into 4 and this routine is called recusively to add the new * areas. * * @param areas The areas to add to the list (and possibly split up). * @param alist The list that will finally contain the complete list of * map areas. */ private void addAreasToList(MapArea[] areas, List<MapArea> alist, int depth) { int res = zoom.getResolution(); for (MapArea area : areas) { Area bounds = area.getBounds(); int[] sizes = area.getEstimatedSizes(); if(log.isInfoEnabled()) { String padding = depth + " "; log.info(padding.substring(0, (depth + 1) * 2) + bounds.getWidth() + "x" + bounds.getHeight() + ", res = " + res + ", points = " + area.getNumPoints() + "/" + sizes[MapArea.POINT_KIND] + ", lines = " + area.getNumLines() + "/" + sizes[MapArea.LINE_KIND] + ", shapes = " + area.getNumShapes() + "/" + sizes[MapArea.SHAPE_KIND]); } if (area.getNumLines() > MAX_NUM_LINES || area.getNumPoints() > MAX_NUM_POINTS || - (sizes[MapArea.POINT_KIND] > MAX_RGN_SIZE && - (area.hasIndPoints() || area.hasLines() || area.hasShapes())) || - (((sizes[MapArea.POINT_KIND] + sizes[MapArea.LINE_KIND]) > MAX_RGN_SIZE) && - area.hasShapes()) || + (sizes[MapArea.POINT_KIND] + + sizes[MapArea.LINE_KIND] + + sizes[MapArea.SHAPE_KIND]) > MAX_RGN_SIZE || sizes[MapArea.XT_POINT_KIND] > MAX_XT_POINTS_SIZE || sizes[MapArea.XT_LINE_KIND] > MAX_XT_LINES_SIZE || sizes[MapArea.XT_SHAPE_KIND] > MAX_XT_SHAPES_SIZE) { if (area.getBounds().getMaxDimention() > 100) { if (log.isDebugEnabled()) log.debug("splitting area", area); MapArea[] sublist; if(bounds.getWidth() > bounds.getHeight()) sublist = area.split(2, 1, res); else sublist = area.split(1, 2, res); addAreasToList(sublist, alist, depth + 1); continue; } else { - log.warn("area too small to split", area); + log.error("Area too small to split at " + area.getBounds().getCenter().toOSMURL() + " (reduce the density of points, length of lines, etc.)"); } } log.debug("adding area unsplit", ",has points" + area.hasPoints()); MapArea[] sublist = area.split(1, 1, res); assert sublist.length == 1: sublist.length; //assert sublist[0].getAreaResolution() == res: sublist[0].getAreaResolution(); alist.add(sublist[0]); } } /** * Split the area into portions that have the maximum size. There is a * maximum limit to the size of a subdivision (16 bits or about 1.4 degrees * at the most detailed zoom level). * * The size depends on the shift level. * * We are choosing a limit smaller than the real max to allow for * uncertaintly about what happens with features that extend beyond the box. * * If the area is already small enough then it will be returned unchanged. * * @param mapArea The area that needs to be split down. * @return An array of map areas. Each will be below the max size. */ private MapArea[] splitMaxSize(MapArea mapArea) { Area bounds = mapArea.getBounds(); int shift = zoom.getShiftValue(); int width = bounds.getWidth() >> shift; int height = bounds.getHeight() >> shift; log.info("splitMaxSize() bounds = " + bounds + " shift = " + shift + " width = " + width + " height = " + height); if (log.isDebugEnabled()) log.debug("shifted width", width, "shifted height", height); // There is an absolute maximum size that a division can be. Make sure // that we are well inside that. int xsplit = 1; if (width > MAX_DIVISION_SIZE) xsplit = width / MAX_DIVISION_SIZE + 1; int ysplit = 1; if (height > MAX_DIVISION_SIZE) ysplit = height / MAX_DIVISION_SIZE + 1; return mapArea.split(xsplit, ysplit, zoom.getResolution()); } /** * The initial area contains all the features of the map. * * @param src The map data source. * @return The initial map area covering the whole area and containing * all the map features that are visible. */ private MapArea initialArea(MapDataSource src) { return new MapArea(src, zoom.getResolution()); } }
false
true
private void addAreasToList(MapArea[] areas, List<MapArea> alist, int depth) { int res = zoom.getResolution(); for (MapArea area : areas) { Area bounds = area.getBounds(); int[] sizes = area.getEstimatedSizes(); if(log.isInfoEnabled()) { String padding = depth + " "; log.info(padding.substring(0, (depth + 1) * 2) + bounds.getWidth() + "x" + bounds.getHeight() + ", res = " + res + ", points = " + area.getNumPoints() + "/" + sizes[MapArea.POINT_KIND] + ", lines = " + area.getNumLines() + "/" + sizes[MapArea.LINE_KIND] + ", shapes = " + area.getNumShapes() + "/" + sizes[MapArea.SHAPE_KIND]); } if (area.getNumLines() > MAX_NUM_LINES || area.getNumPoints() > MAX_NUM_POINTS || (sizes[MapArea.POINT_KIND] > MAX_RGN_SIZE && (area.hasIndPoints() || area.hasLines() || area.hasShapes())) || (((sizes[MapArea.POINT_KIND] + sizes[MapArea.LINE_KIND]) > MAX_RGN_SIZE) && area.hasShapes()) || sizes[MapArea.XT_POINT_KIND] > MAX_XT_POINTS_SIZE || sizes[MapArea.XT_LINE_KIND] > MAX_XT_LINES_SIZE || sizes[MapArea.XT_SHAPE_KIND] > MAX_XT_SHAPES_SIZE) { if (area.getBounds().getMaxDimention() > 100) { if (log.isDebugEnabled()) log.debug("splitting area", area); MapArea[] sublist; if(bounds.getWidth() > bounds.getHeight()) sublist = area.split(2, 1, res); else sublist = area.split(1, 2, res); addAreasToList(sublist, alist, depth + 1); continue; } else { log.warn("area too small to split", area); } } log.debug("adding area unsplit", ",has points" + area.hasPoints()); MapArea[] sublist = area.split(1, 1, res); assert sublist.length == 1: sublist.length; //assert sublist[0].getAreaResolution() == res: sublist[0].getAreaResolution(); alist.add(sublist[0]); } }
private void addAreasToList(MapArea[] areas, List<MapArea> alist, int depth) { int res = zoom.getResolution(); for (MapArea area : areas) { Area bounds = area.getBounds(); int[] sizes = area.getEstimatedSizes(); if(log.isInfoEnabled()) { String padding = depth + " "; log.info(padding.substring(0, (depth + 1) * 2) + bounds.getWidth() + "x" + bounds.getHeight() + ", res = " + res + ", points = " + area.getNumPoints() + "/" + sizes[MapArea.POINT_KIND] + ", lines = " + area.getNumLines() + "/" + sizes[MapArea.LINE_KIND] + ", shapes = " + area.getNumShapes() + "/" + sizes[MapArea.SHAPE_KIND]); } if (area.getNumLines() > MAX_NUM_LINES || area.getNumPoints() > MAX_NUM_POINTS || (sizes[MapArea.POINT_KIND] + sizes[MapArea.LINE_KIND] + sizes[MapArea.SHAPE_KIND]) > MAX_RGN_SIZE || sizes[MapArea.XT_POINT_KIND] > MAX_XT_POINTS_SIZE || sizes[MapArea.XT_LINE_KIND] > MAX_XT_LINES_SIZE || sizes[MapArea.XT_SHAPE_KIND] > MAX_XT_SHAPES_SIZE) { if (area.getBounds().getMaxDimention() > 100) { if (log.isDebugEnabled()) log.debug("splitting area", area); MapArea[] sublist; if(bounds.getWidth() > bounds.getHeight()) sublist = area.split(2, 1, res); else sublist = area.split(1, 2, res); addAreasToList(sublist, alist, depth + 1); continue; } else { log.error("Area too small to split at " + area.getBounds().getCenter().toOSMURL() + " (reduce the density of points, length of lines, etc.)"); } } log.debug("adding area unsplit", ",has points" + area.hasPoints()); MapArea[] sublist = area.split(1, 1, res); assert sublist.length == 1: sublist.length; //assert sublist[0].getAreaResolution() == res: sublist[0].getAreaResolution(); alist.add(sublist[0]); } }
diff --git a/src/com/ichi2/libanki/Utils.java b/src/com/ichi2/libanki/Utils.java index 89e4e60d..3f9be24d 100644 --- a/src/com/ichi2/libanki/Utils.java +++ b/src/com/ichi2/libanki/Utils.java @@ -1,1179 +1,1179 @@ /**************************************************************************************** * Copyright (c) 2009 Daniel Sv�rd <[email protected]> * * Copyright (c) 2009 Edu Zamora <[email protected]> * * Copyright (c) 2011 Norbert Nagold <[email protected]> * * Copyright (c) 2012 Kostas Spyropoulos <[email protected]> * * * * 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 com.ichi2.libanki; import android.annotation.TargetApi; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.net.Uri; import android.text.Html; import android.util.Log; import android.view.View; import android.widget.FrameLayout; import android.widget.LinearLayout; import com.ichi2.anki.AnkiDb; import com.ichi2.anki.AnkiDroidApp; import com.ichi2.anki.AnkiFont; import com.ichi2.anki.R; import com.ichi2.async.Connection.OldAnkiDeckFilter; import com.mindprod.common11.BigDate; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.nio.channels.FileChannel; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.sql.Date; import java.text.Normalizer; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Random; import java.util.TimeZone; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.Deflater; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; /** * TODO comments */ public class Utils { enum SqlCommandType { SQL_INS, SQL_UPD, SQL_DEL }; // Used to format doubles with English's decimal separator system public static final Locale ENGLISH_LOCALE = new Locale("en_US"); public static final int CHUNK_SIZE = 32768; private static final int DAYS_BEFORE_1970 = 719163; private static NumberFormat mCurrentNumberFormat; private static NumberFormat mCurrentPercentageFormat; private static TreeSet<Long> sIdTree; private static long sIdTime; private static final int TIME_SECONDS = 0; private static final int TIME_MINUTES = 1; private static final int TIME_HOURS = 2; private static final int TIME_DAYS = 3; private static final int TIME_MONTHS = 4; private static final int TIME_YEARS = 5; public static final int TIME_FORMAT_DEFAULT = 0; public static final int TIME_FORMAT_IN = 1; public static final int TIME_FORMAT_BEFORE = 2; /* Prevent class from being instantiated */ private Utils() { } // Regex pattern used in removing tags from text before diff private static final Pattern stylePattern = Pattern.compile("(?s)<style.*?>.*?</style>"); private static final Pattern scriptPattern = Pattern.compile("(?s)<script.*?>.*?</script>"); private static final Pattern tagPattern = Pattern.compile("<.*?>"); private static final Pattern imgPattern = Pattern.compile("<img src=[\\\"']?([^\\\"'>]+)[\\\"']? ?/?>"); private static final Pattern htmlEntitiesPattern = Pattern.compile("&#?\\w+;"); private static final String ALL_CHARACTERS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; private static final String BASE91_EXTRA_CHARS = "!#$%&()*+,-./:;<=>?@[]^_`{|}~"; /**The time in integer seconds. Pass scale=1000 to get milliseconds. */ public static double now() { return (System.currentTimeMillis() / 1000.0); } /**The time in integer seconds. Pass scale=1000 to get milliseconds. */ public static long intNow() { return intNow(1); } public static long intNow(int scale) { return (long) (now() * scale); } // timetable // aftertimetable // shorttimetable /** * Return a string representing a time span (eg '2 days'). * @param inFormat: if true, return eg 'in 2 days' */ public static String fmtTimeSpan(int time) { return fmtTimeSpan(time, 0, false, false); } public static String fmtTimeSpan(int time, boolean _short) { return fmtTimeSpan(time, 0, _short, false); } public static String fmtTimeSpan(int time, int format, boolean _short, boolean boldNumber) { int type; int unit = 99; int point = 0; if (Math.abs(time) < 60 || unit < 1) { type = TIME_SECONDS; } else if (Math.abs(time) < 3600 || unit < 2) { type = TIME_MINUTES; } else if (Math.abs(time) < 60 * 60 * 24 || unit < 3) { type = TIME_HOURS; } else if (Math.abs(time) < 60 * 60 * 24 * 29.5 || unit < 4) { type = TIME_DAYS; } else if (Math.abs(time) < 60 * 60 * 24 * 30 * 11.95 || unit < 5) { type = TIME_MONTHS; point = 1; } else { type = TIME_YEARS; point = 1; } double ftime = convertSecondsTo(time, type); int formatId; if (false){//_short) { //formatId = R.array.next_review_short; } else { switch (format) { case TIME_FORMAT_IN: if (Math.round(ftime * 10) == 10) { formatId = R.array.next_review_in_s; } else { formatId = R.array.next_review_in_p; } break; case TIME_FORMAT_BEFORE: if (Math.round(ftime * 10) == 10) { formatId = R.array.next_review_before_s; } else { formatId = R.array.next_review_before_p; } break; case TIME_FORMAT_DEFAULT: default: if (Math.round(ftime * 10) == 10) { formatId = R.array.next_review_s; } else { formatId = R.array.next_review_p; } break; } } String timeString = String.format(AnkiDroidApp.getAppResources().getStringArray(formatId)[type], boldNumber ? "<b>" + fmtDouble(ftime, point) + "</b>" : fmtDouble(ftime, point)); if (boldNumber && time == 1) { timeString = timeString.replace("1", "<b>1</b>"); } return timeString; } private static double convertSecondsTo(int seconds, int type) { switch (type) { case TIME_SECONDS: return seconds; case TIME_MINUTES: return seconds / 60.0; case TIME_HOURS: return seconds / 3600.0; case TIME_DAYS: return seconds / 86400.0; case TIME_MONTHS: return seconds / 2592000.0; case TIME_YEARS: return seconds / 31536000.0; default: return 0; } } /** * Locale * *********************************************************************************************** */ /** * @return double with percentage sign */ public static String fmtPercentage(Double value) { return fmtPercentage(value, 0); } public static String fmtPercentage(Double value, int point) { // only retrieve the percentage format the first time if (mCurrentPercentageFormat == null) { mCurrentPercentageFormat = NumberFormat.getPercentInstance(Locale.getDefault()); } mCurrentNumberFormat.setMaximumFractionDigits(point); return mCurrentPercentageFormat.format(value); } /** * @return a string with decimal separator according to current locale */ public static String fmtDouble(Double value) { return fmtDouble(value, 1); } public static String fmtDouble(Double value, int point) { // only retrieve the number format the first time if (mCurrentNumberFormat == null) { mCurrentNumberFormat = NumberFormat.getInstance(Locale.getDefault()); } mCurrentNumberFormat.setMaximumFractionDigits(point); return mCurrentNumberFormat.format(value); } /** * HTML * *********************************************************************************************** */ /** * Strips a text from <style>...</style>, <script>...</script> and <_any_tag_> HTML tags. * @param The HTML text to be cleaned. * @return The text without the aforementioned tags. */ public static String stripHTML(String s) { Matcher htmlMatcher = stylePattern.matcher(s); s = htmlMatcher.replaceAll(""); htmlMatcher = scriptPattern.matcher(s); s = htmlMatcher.replaceAll(""); htmlMatcher = tagPattern.matcher(s); s = htmlMatcher.replaceAll(""); return entsToTxt(s); } /** * Strip HTML but keep media filenames */ public static String stripHTMLMedia(String s) { Matcher imgMatcher = imgPattern.matcher(s); return stripHTML(imgMatcher.replaceAll(" $1 ")); } private String minimizeHTML(String s) { // TODO return s; } /** * Takes a string and replaces all the HTML symbols in it with their unescaped representation. * This should only affect substrings of the form &something; and not tags. * Internet rumour says that Html.fromHtml() doesn't cover all cases, but it doesn't get less * vague than that. * @param html The HTML escaped text * @return The text with its HTML entities unescaped. */ private static String entsToTxt(String html) { Matcher htmlEntities = htmlEntitiesPattern.matcher(html); StringBuffer sb = new StringBuffer(); while (htmlEntities.find()) { htmlEntities.appendReplacement(sb, Html.fromHtml(htmlEntities.group()).toString()); } htmlEntities.appendTail(sb); return sb.toString(); } /** * IDs * *********************************************************************************************** */ public static String hexifyID(long id) { return Long.toHexString(id); } public static long dehexifyID(String id) { return Long.valueOf(id, 16); } /** Given a list of integers, return a string '(int1,int2,...)'. */ public static String ids2str(int[] ids) { StringBuilder sb = new StringBuilder(); sb.append("("); if (ids != null) { String s = Arrays.toString(ids); sb.append(s.substring(1, s.length() - 1)); } sb.append(")"); return sb.toString(); } /** Given a list of integers, return a string '(int1,int2,...)'. */ public static String ids2str(long[] ids) { StringBuilder sb = new StringBuilder(); sb.append("("); if (ids != null) { String s = Arrays.toString(ids); sb.append(s.substring(1, s.length() - 1)); } sb.append(")"); return sb.toString(); } /** Given a list of integers, return a string '(int1,int2,...)'. */ public static String ids2str(Long[] ids) { StringBuilder sb = new StringBuilder(); sb.append("("); if (ids != null) { String s = Arrays.toString(ids); sb.append(s.substring(1, s.length() - 1)); } sb.append(")"); return sb.toString(); } /** Given a list of integers, return a string '(int1,int2,...)'. */ public static <T> String ids2str(List<T> ids) { StringBuilder sb = new StringBuilder(512); sb.append("("); boolean isNotFirst = false; for (T id : ids) { if (isNotFirst) { sb.append(", "); } else { isNotFirst = true; } sb.append(id); } sb.append(")"); return sb.toString(); } /** Given a list of integers, return a string '(int1,int2,...)'. */ public static String ids2str(JSONArray ids) { StringBuilder str = new StringBuilder(512); str.append("("); if (ids != null) { int len = ids.length(); for (int i = 0; i < len; i++) { try { if (i == (len - 1)) { str.append(ids.get(i)); } else { str.append(ids.get(i)).append(","); } } catch (JSONException e) { Log.e(AnkiDroidApp.TAG, "JSONException = " + e.getMessage()); } } } str.append(")"); return str.toString(); } /** LIBANKI: not in libanki */ public static long[] arrayList2array(List<Long> list) { long[] ar = new long[list.size()]; int i = 0; for (long l : list) { ar[i++] = l; } return ar; } /** Return a non-conflicting timestamp for table. */ public static long timestampID(AnkiDb db, String table) { // be careful not to create multiple objects without flushing them, or they // may share an ID. long t = intNow(1000); while (db.queryScalar("SELECT id FROM " + table + " WHERE id = " + t, false) != 0) { t += 1; } return t; } /** Return the first safe ID to use. */ public static long maxID(AnkiDb db) { long now = intNow(1000); now = Math.max(now, db.queryLongScalar("SELECT MAX(id) FROM cards")); now = Math.max(now, db.queryLongScalar("SELECT MAX(id) FROM notes")); return now + 1; } // used in ankiweb public static String base62(int num, String extra) { String table = ALL_CHARACTERS + extra; int len = table.length(); String buf = ""; int mod = 0; while (num != 0) { mod = num % len; buf = buf + table.substring(mod, mod + 1); num = num / len; } return buf; } // all printable characters minus quotes, backslash and separators public static String base91(int num) { return base62(num, BASE91_EXTRA_CHARS); } /** return a base91-encoded 64bit random number */ public static String guid64() { return base91((new Random()).nextInt((int) (Math.pow(2, 61) - 1))); } // increment a guid by one, for note type conflicts public static String incGuid(String guid) { return new StringBuffer(_incGuid(new StringBuffer(guid).reverse().toString())).reverse().toString(); } private static String _incGuid(String guid) { String table = ALL_CHARACTERS + BASE91_EXTRA_CHARS; int idx = table.indexOf(guid.substring(0, 1)); if (idx + 1 == table.length()) { // overflow guid = table.substring(0, 1) + _incGuid(guid.substring(1, guid.length())); } else { guid = table.substring(idx + 1) + guid.substring(1, guid.length()); } return guid; } // public static JSONArray listToJSONArray(List<Object> list) { // JSONArray jsonArray = new JSONArray(); // // for (Object o : list) { // jsonArray.put(o); // } // // return jsonArray; // } // // // public static List<String> jsonArrayToListString(JSONArray jsonArray) throws JSONException { // ArrayList<String> list = new ArrayList<String>(); // // int len = jsonArray.length(); // for (int i = 0; i < len; i++) { // list.add(jsonArray.getString(i)); // } // // return list; // } public static long[] jsonArrayToLongArray(JSONArray jsonArray) throws JSONException { long[] ar = new long[jsonArray.length()]; for (int i = 0; i < jsonArray.length(); i++) { ar[i] = jsonArray.getLong(i); } return ar; } /** * Fields * *********************************************************************************************** */ public static String joinFields(String[] list) { StringBuilder result = new StringBuilder(128); for (int i = 0; i < list.length - 1; i++) { result.append(list[i]).append("\u001f"); } if (list.length > 0) { result.append(list[list.length - 1]); } return result.toString(); } public static String[] splitFields(String fields) { // do not drop empty fields fields = fields.replaceAll("\\x1f\\x1f", "\u001f\u001e\u001f"); fields = fields.replaceAll("\\x1f$", "\u001f\u001e"); String[] split = fields.split("\\x1f"); for (int i = 0; i < split.length; i++) { if (split[i].matches("\\x1e")) { split[i] = ""; } } return split; } /** * Checksums * *********************************************************************************************** */ /** * SHA1 checksum. * Equivalent to python sha1.hexdigest() * * @param data the string to generate hash from * @return A string of length 40 containing the hexadecimal representation of the MD5 checksum of data. */ public static String checksum(String data) { String result = ""; if (data != null) { MessageDigest md = null; byte[] digest = null; try { - md = MessageDigest.getInstance("SHA"); - digest = md.digest(stripHTML(data).getBytes("UTF-8")); + md = MessageDigest.getInstance("SHA1"); + digest = md.digest(data.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { Log.e(AnkiDroidApp.TAG, "Utils.checksum: No such algorithm. " + e.getMessage()); throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { Log.e(AnkiDroidApp.TAG, "Utils.checksum: " + e.getMessage()); e.printStackTrace(); } BigInteger biginteger = new BigInteger(1, digest); result = biginteger.toString(16); // pad with zeros to length of 40 This method used to pad // to the length of 32. As it turns out, sha1 has a digest // size of 160 bits, leading to a hex digest size of 40, // not 32. if (result.length() < 40) { String zeroes = "0000000000000000000000000000000000000000"; result = zeroes.substring(0, zeroes.length() - result.length()) + result; } } return result; } /** * @param data the string to generate hash from * @return 32 bit unsigned number from first 8 digits of sha1 hash */ public static long fieldChecksum(String data) { return Long.valueOf(checksum(stripHTMLMedia(data)).substring(0, 8), 16); } /** * Generate the SHA1 checksum of a file. * @param file The file to be checked * @return A string of length 32 containing the hexadecimal representation of the SHA1 checksum of the file's contents. */ public static String fileChecksum(String file) { byte[] buffer = new byte[1024]; byte[] digest = null; try { InputStream fis = new FileInputStream(file); MessageDigest md = MessageDigest.getInstance("SHA1"); int numRead = 0; do { numRead = fis.read(buffer); if (numRead > 0) { md.update(buffer, 0, numRead); } } while (numRead != -1); fis.close(); digest = md.digest(); } catch (FileNotFoundException e) { Log.e(AnkiDroidApp.TAG, "Utils.fileChecksum: File not found.", e); } catch (NoSuchAlgorithmException e) { Log.e(AnkiDroidApp.TAG, "Utils.fileChecksum: No such algorithm.", e); } catch (IOException e) { Log.e(AnkiDroidApp.TAG, "Utils.fileChecksum: IO exception.", e); } BigInteger biginteger = new BigInteger(1, digest); String result = biginteger.toString(16); // pad with zeros to length of 40 - SHA1 is 160bit long if (result.length() < 40) { result = "0000000000000000000000000000000000000000".substring(0, 40 - result.length()) + result; } return result; } /** Replace HTML line break tags with new lines. */ public static String replaceLineBreak(String text) { return text.replaceAll("<br(\\s*\\/*)>", "\n"); } // /** // * MD5 sum of file. // * Equivalent to checksum(open(os.path.join(mdir, file), "rb").read())) // * // * @param path The full path to the file // * @return A string of length 32 containing the hexadecimal representation of the MD5 checksum of the contents // * of the file // */ // public static String fileChecksum(String path) { // byte[] bytes = null; // try { // File file = new File(path); // if (file != null && file.isFile()) { // bytes = new byte[(int)file.length()]; // FileInputStream fin = new FileInputStream(file); // fin.read(bytes); // } // } catch (FileNotFoundException e) { // Log.e(AnkiDroidApp.TAG, "Can't find file " + path + " to calculate its checksum"); // } catch (IOException e) { // Log.e(AnkiDroidApp.TAG, "Can't read file " + path + " to calculate its checksum"); // } // if (bytes == null) { // Log.w(AnkiDroidApp.TAG, "File " + path + " appears to be empty"); // return ""; // } // MessageDigest md = null; // byte[] digest = null; // try { // md = MessageDigest.getInstance("MD5"); // digest = md.digest(bytes); // } catch (NoSuchAlgorithmException e) { // Log.e(AnkiDroidApp.TAG, "Utils.checksum: No such algorithm. " + e.getMessage()); // throw new RuntimeException(e); // } // BigInteger biginteger = new BigInteger(1, digest); // String result = biginteger.toString(16); // // pad with zeros to length of 32 // if (result.length() < 32) { // result = "00000000000000000000000000000000".substring(0, 32 - result.length()) + result; // } // return result; // } /** * Tempo files * *********************************************************************************************** */ // tmpdir // tmpfile // namedtmp /** * Converts an InputStream to a String. * @param is InputStream to convert * @return String version of the InputStream */ public static String convertStreamToString(InputStream is) { String contentOfMyInputStream = ""; try { BufferedReader rd = new BufferedReader(new InputStreamReader(is), 4096); String line; StringBuilder sb = new StringBuilder(); while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); contentOfMyInputStream = sb.toString(); } catch (Exception e) { e.printStackTrace(); } return contentOfMyInputStream; } public static boolean unzip(String filename, String targetDirectory) { try { File dir = new File(targetDirectory); if (!dir.exists() || !dir.isDirectory()) { dir.mkdirs(); } byte[] buf = new byte[1024]; ZipInputStream zis = new ZipInputStream(new FileInputStream(filename)); ZipEntry ze = zis.getNextEntry(); while (ze != null) { String name = ze.getName(); Log.i(AnkiDroidApp.TAG, "uncompress " + name); int n; FileOutputStream fos = new FileOutputStream(targetDirectory + "/" + name); while ((n = zis.read(buf, 0, 1024)) > -1) { fos.write(buf, 0, n); } fos.close(); zis.closeEntry(); ze = zis.getNextEntry(); } zis.close(); return true; } catch (IOException e) { Log.e(AnkiDroidApp.TAG, "IOException on decompressing file " + filename); return false; } } /** * Compress data. * @param bytesToCompress is the byte array to compress. * @return a compressed byte array. * @throws java.io.IOException */ public static byte[] compress(byte[] bytesToCompress, int comp) throws IOException { // Compressor with highest level of compression. Deflater compressor = new Deflater(comp, true); // Give the compressor the data to compress. compressor.setInput(bytesToCompress); compressor.finish(); // Create an expandable byte array to hold the compressed data. // It is not necessary that the compressed data will be smaller than // the uncompressed data. ByteArrayOutputStream bos = new ByteArrayOutputStream(bytesToCompress.length); // Compress the data byte[] buf = new byte[65536]; while (!compressor.finished()) { bos.write(buf, 0, compressor.deflate(buf)); } bos.close(); // Get the compressed data return bos.toByteArray(); } /** * Utility method to write to a file. * Throws the exception, so we can report it in syncing log * @throws IOException */ public static void writeToFile(InputStream source, String destination) throws IOException { Log.i(AnkiDroidApp.TAG, "Creating new file... = " + destination); new File(destination).createNewFile(); long startTimeMillis = System.currentTimeMillis(); OutputStream output = new BufferedOutputStream(new FileOutputStream(destination)); // Transfer bytes, from source to destination. byte[] buf = new byte[CHUNK_SIZE]; long sizeBytes = 0; int len; if (source == null) { Log.e(AnkiDroidApp.TAG, "source is null!"); } while ((len = source.read(buf)) >= 0) { output.write(buf, 0, len); sizeBytes += len; } long endTimeMillis = System.currentTimeMillis(); Log.i(AnkiDroidApp.TAG, "Finished writing!"); long durationSeconds = (endTimeMillis - startTimeMillis) / 1000; long sizeKb = sizeBytes / 1024; long speedKbSec = 0; if (endTimeMillis != startTimeMillis) { speedKbSec = sizeKb * 1000 / (endTimeMillis - startTimeMillis); } Log.d(AnkiDroidApp.TAG, "Utils.writeToFile: " + "Size: " + sizeKb + "Kb, " + "Duration: " + durationSeconds + "s, " + "Speed: " + speedKbSec + "Kb/s"); output.close(); } // Print methods public static void printJSONObject(JSONObject jsonObject) { printJSONObject(jsonObject, "-", null); } public static void printJSONObject(JSONObject jsonObject, boolean writeToFile) { BufferedWriter buff; try { buff = writeToFile ? new BufferedWriter(new FileWriter("/sdcard/payloadAndroid.txt"), 8192) : null; try { printJSONObject(jsonObject, "-", buff); } finally { if (buff != null) buff.close(); } } catch (IOException ioe) { Log.e(AnkiDroidApp.TAG, "IOException = " + ioe.getMessage()); } } private static void printJSONObject(JSONObject jsonObject, String indentation, BufferedWriter buff) { try { @SuppressWarnings("unchecked") Iterator<String> keys = (Iterator<String>) jsonObject.keys(); TreeSet<String> orderedKeysSet = new TreeSet<String>(); while (keys.hasNext()) { orderedKeysSet.add(keys.next()); } Iterator<String> orderedKeys = orderedKeysSet.iterator(); while (orderedKeys.hasNext()) { String key = orderedKeys.next(); try { Object value = jsonObject.get(key); if (value instanceof JSONObject) { if (buff != null) { buff.write(indentation + " " + key + " : "); buff.newLine(); } Log.i(AnkiDroidApp.TAG, " " + indentation + key + " : "); printJSONObject((JSONObject) value, indentation + "-", buff); } else { if (buff != null) { buff.write(indentation + " " + key + " = " + jsonObject.get(key).toString()); buff.newLine(); } Log.i(AnkiDroidApp.TAG, " " + indentation + key + " = " + jsonObject.get(key).toString()); } } catch (JSONException e) { Log.e(AnkiDroidApp.TAG, "JSONException = " + e.getMessage()); } } } catch (IOException e1) { Log.e(AnkiDroidApp.TAG, "IOException = " + e1.getMessage()); } } /* public static void saveJSONObject(JSONObject jsonObject) throws IOException { Log.i(AnkiDroidApp.TAG, "saveJSONObject"); BufferedWriter buff = new BufferedWriter(new FileWriter("/sdcard/jsonObjectAndroid.txt", true)); buff.write(jsonObject.toString()); buff.close(); } */ /** * Returns 1 if true, 0 if false * * @param b The boolean to convert to integer * @return 1 if b is true, 0 otherwise */ public static int booleanToInt(boolean b) { return (b) ? 1 : 0; } /** * Returns the effective date of the present moment. * If the time is prior the cut-off time (9:00am by default as of 11/02/10) return yesterday, * otherwise today * Note that the Date class is java.sql.Date whose constructor sets hours, minutes etc to zero * * @param utcOffset The UTC offset in seconds we are going to use to determine today or yesterday. * @return The date (with time set to 00:00:00) that corresponds to today in Anki terms */ public static Date genToday(double utcOffset) { // The result is not adjusted for timezone anymore, following libanki model // Timezone adjustment happens explicitly in Deck.updateCutoff(), but not in Deck.checkDailyStats() SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); df.setTimeZone(TimeZone.getTimeZone("GMT")); Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT")); cal.setTimeInMillis(System.currentTimeMillis() - (long) utcOffset * 1000l); Date today = Date.valueOf(df.format(cal.getTime())); return today; } public static void printDate(String name, double date) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss"); df.setTimeZone(TimeZone.getTimeZone("GMT")); Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT")); cal.setTimeInMillis((long)date * 1000); Log.d(AnkiDroidApp.TAG, "Value of " + name + ": " + cal.getTime().toGMTString()); } public static String doubleToTime(double value) { int time = (int) Math.round(value); int seconds = time % 60; int minutes = (time - seconds) / 60; String formattedTime; if (seconds < 10) { formattedTime = Integer.toString(minutes) + ":0" + Integer.toString(seconds); } else { formattedTime = Integer.toString(minutes) + ":" + Integer.toString(seconds); } return formattedTime; } /** * Returns the proleptic Gregorian ordinal of the date, where January 1 of year 1 has ordinal 1. * @param date Date to convert to ordinal, since 01/01/01 * @return The ordinal representing the date */ public static int dateToOrdinal(Date date) { // BigDate.toOrdinal returns the ordinal since 1970, so we add up the days from 01/01/01 to 1970 return BigDate.toOrdinal(date.getYear() + 1900, date.getMonth() + 1, date.getDate()) + DAYS_BEFORE_1970; } /** * Return the date corresponding to the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1. * @param ordinal representing the days since 01/01/01 * @return Date converted from the ordinal */ public static Date ordinalToDate(int ordinal) { return new Date((new BigDate(ordinal - DAYS_BEFORE_1970)).getLocalDate().getTime()); } /** * Indicates whether the specified action can be used as an intent. This method queries the package manager for * installed packages that can respond to an intent with the specified action. If no suitable package is found, this * method returns false. * @param context The application's environment. * @param action The Intent action to check for availability. * @return True if an Intent with the specified action can be sent and responded to, false otherwise. */ public static boolean isIntentAvailable(Context context, String action) { return isIntentAvailable(context, action, null); } public static boolean isIntentAvailable(Context context, String action, ComponentName componentName) { final PackageManager packageManager = context.getPackageManager(); final Intent intent = new Intent(action); intent.setComponent(componentName); List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); return list.size() > 0; } /** * @param mediaDir media directory path on SD card * @return path converted to file URL, properly UTF-8 URL encoded */ public static String getBaseUrl(String mediaDir) { // Use android.net.Uri class to ensure whole path is properly encoded // File.toURL() does not work here, and URLEncoder class is not directly usable // with existing slashes if (mediaDir.length() != 0 && !mediaDir.equalsIgnoreCase("null")) { Uri mediaDirUri = Uri.fromFile(new File(mediaDir)); return mediaDirUri.toString() +"/"; } return ""; } /** * Take an array of Long and return an array of long * * @param array The input with type Long[] * @return The output with type long[] */ public static long[] toPrimitive(Long[] array) { long[] results = new long[array.length]; if (array != null) { for (int i = 0; i < array.length; i++) { results[i] = array[i].longValue(); } } return results; } public static long[] toPrimitive(Collection<Long> array) { long[] results = new long[array.size()]; if (array != null) { int i = 0; for (Long item : array) { results[i++] = item.longValue(); } } return results; } public static void updateProgressBars(View view, int x, int y) { if (view == null) { return; } if (view.getParent() instanceof LinearLayout) { LinearLayout.LayoutParams lparam = new LinearLayout.LayoutParams(0, 0); lparam.height = y; lparam.width = x; view.setLayoutParams(lparam); } else if (view.getParent() instanceof FrameLayout) { FrameLayout.LayoutParams lparam = new FrameLayout.LayoutParams(0, 0); lparam.height = y; lparam.width = x; view.setLayoutParams(lparam); } } /** * Calculate the UTC offset */ public static double utcOffset() { Calendar cal = Calendar.getInstance(); // 4am return 4 * 60 * 60 - (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET)) / 1000; } /** Returns the filename without the extension. */ public static String removeExtension(String filename) { int dotPosition = filename.lastIndexOf('.'); if (dotPosition == -1) { return filename; } return filename.substring(0, dotPosition); } /** Removes any character that are not valid as deck names. */ public static String removeInvalidDeckNameCharacters(String name) { if (name == null) { return null; } // The only characters that we cannot absolutely allow to appear in the filename are the ones reserved in some // file system. Currently these are \, /, and :, in order to cover Linux, OSX, and Windows. return name.replaceAll("[:/\\\\]", ""); } /** Returns a list of files for the installed custom fonts. */ public static List<AnkiFont> getCustomFonts(Context context) { String deckPath = AnkiDroidApp.getCurrentAnkiDroidDirectory(); String fontsPath = deckPath + "/fonts/"; File fontsDir = new File(fontsPath); int fontsCount = 0; File[] fontsList = null; if (fontsDir.exists() && fontsDir.isDirectory()) { fontsCount = fontsDir.listFiles().length; fontsList = fontsDir.listFiles(); } String[] ankiDroidFonts = null; try { ankiDroidFonts = context.getAssets().list("fonts"); } catch (IOException e) { Log.e(AnkiDroidApp.TAG, "Error on retrieving ankidroid fonts: " + e); } List<AnkiFont> fonts = new ArrayList<AnkiFont>(); for (int i = 0; i < fontsCount; i++) { AnkiFont font = AnkiFont.createAnkiFont(context, fontsList[i].getAbsolutePath(), false); if (font != null) { fonts.add(font); } } for (int i = 0; i < ankiDroidFonts.length; i++) { AnkiFont font = AnkiFont.createAnkiFont(context, ankiDroidFonts[i], true); if (font != null) { fonts.add(font); } } return fonts; } /** Returns a list of apkg-files. */ public static List<File> getImportableDecks() { String deckPath = AnkiDroidApp.getCurrentAnkiDroidDirectory(); File dir = new File(deckPath); int deckCount = 0; File[] deckList = null; if (dir.exists() && dir.isDirectory()) { deckList = dir.listFiles(new FileFilter(){ @Override public boolean accept(File pathname) { if (pathname.isFile() && pathname.getName().endsWith(".apkg")) { return true; } return false; } }); deckCount = deckList.length; } List<File> decks = new ArrayList<File>(); for (int i = 0; i < deckCount; i++) { decks.add(deckList[i]); } return decks; } /** Joins the given string values using the delimiter between them. */ public static String join(String delimiter, String... values) { StringBuilder sb = new StringBuilder(); for (String value : values) { if (sb.length() != 0) { sb.append(delimiter); } sb.append(value); } return sb.toString(); } /** * Simply copy a file to another location * @param sourceFile The source file * @param destFile The destination file, doesn't need to exist yet. * @throws IOException */ public static void copyFile(File sourceFile, File destFile) throws IOException { if(!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } }
true
true
public static String fmtTimeSpan(int time, int format, boolean _short, boolean boldNumber) { int type; int unit = 99; int point = 0; if (Math.abs(time) < 60 || unit < 1) { type = TIME_SECONDS; } else if (Math.abs(time) < 3600 || unit < 2) { type = TIME_MINUTES; } else if (Math.abs(time) < 60 * 60 * 24 || unit < 3) { type = TIME_HOURS; } else if (Math.abs(time) < 60 * 60 * 24 * 29.5 || unit < 4) { type = TIME_DAYS; } else if (Math.abs(time) < 60 * 60 * 24 * 30 * 11.95 || unit < 5) { type = TIME_MONTHS; point = 1; } else { type = TIME_YEARS; point = 1; } double ftime = convertSecondsTo(time, type); int formatId; if (false){//_short) { //formatId = R.array.next_review_short; } else { switch (format) { case TIME_FORMAT_IN: if (Math.round(ftime * 10) == 10) { formatId = R.array.next_review_in_s; } else { formatId = R.array.next_review_in_p; } break; case TIME_FORMAT_BEFORE: if (Math.round(ftime * 10) == 10) { formatId = R.array.next_review_before_s; } else { formatId = R.array.next_review_before_p; } break; case TIME_FORMAT_DEFAULT: default: if (Math.round(ftime * 10) == 10) { formatId = R.array.next_review_s; } else { formatId = R.array.next_review_p; } break; } } String timeString = String.format(AnkiDroidApp.getAppResources().getStringArray(formatId)[type], boldNumber ? "<b>" + fmtDouble(ftime, point) + "</b>" : fmtDouble(ftime, point)); if (boldNumber && time == 1) { timeString = timeString.replace("1", "<b>1</b>"); } return timeString; } private static double convertSecondsTo(int seconds, int type) { switch (type) { case TIME_SECONDS: return seconds; case TIME_MINUTES: return seconds / 60.0; case TIME_HOURS: return seconds / 3600.0; case TIME_DAYS: return seconds / 86400.0; case TIME_MONTHS: return seconds / 2592000.0; case TIME_YEARS: return seconds / 31536000.0; default: return 0; } } /** * Locale * *********************************************************************************************** */ /** * @return double with percentage sign */ public static String fmtPercentage(Double value) { return fmtPercentage(value, 0); } public static String fmtPercentage(Double value, int point) { // only retrieve the percentage format the first time if (mCurrentPercentageFormat == null) { mCurrentPercentageFormat = NumberFormat.getPercentInstance(Locale.getDefault()); } mCurrentNumberFormat.setMaximumFractionDigits(point); return mCurrentPercentageFormat.format(value); } /** * @return a string with decimal separator according to current locale */ public static String fmtDouble(Double value) { return fmtDouble(value, 1); } public static String fmtDouble(Double value, int point) { // only retrieve the number format the first time if (mCurrentNumberFormat == null) { mCurrentNumberFormat = NumberFormat.getInstance(Locale.getDefault()); } mCurrentNumberFormat.setMaximumFractionDigits(point); return mCurrentNumberFormat.format(value); } /** * HTML * *********************************************************************************************** */ /** * Strips a text from <style>...</style>, <script>...</script> and <_any_tag_> HTML tags. * @param The HTML text to be cleaned. * @return The text without the aforementioned tags. */ public static String stripHTML(String s) { Matcher htmlMatcher = stylePattern.matcher(s); s = htmlMatcher.replaceAll(""); htmlMatcher = scriptPattern.matcher(s); s = htmlMatcher.replaceAll(""); htmlMatcher = tagPattern.matcher(s); s = htmlMatcher.replaceAll(""); return entsToTxt(s); } /** * Strip HTML but keep media filenames */ public static String stripHTMLMedia(String s) { Matcher imgMatcher = imgPattern.matcher(s); return stripHTML(imgMatcher.replaceAll(" $1 ")); } private String minimizeHTML(String s) { // TODO return s; } /** * Takes a string and replaces all the HTML symbols in it with their unescaped representation. * This should only affect substrings of the form &something; and not tags. * Internet rumour says that Html.fromHtml() doesn't cover all cases, but it doesn't get less * vague than that. * @param html The HTML escaped text * @return The text with its HTML entities unescaped. */ private static String entsToTxt(String html) { Matcher htmlEntities = htmlEntitiesPattern.matcher(html); StringBuffer sb = new StringBuffer(); while (htmlEntities.find()) { htmlEntities.appendReplacement(sb, Html.fromHtml(htmlEntities.group()).toString()); } htmlEntities.appendTail(sb); return sb.toString(); } /** * IDs * *********************************************************************************************** */ public static String hexifyID(long id) { return Long.toHexString(id); } public static long dehexifyID(String id) { return Long.valueOf(id, 16); } /** Given a list of integers, return a string '(int1,int2,...)'. */ public static String ids2str(int[] ids) { StringBuilder sb = new StringBuilder(); sb.append("("); if (ids != null) { String s = Arrays.toString(ids); sb.append(s.substring(1, s.length() - 1)); } sb.append(")"); return sb.toString(); } /** Given a list of integers, return a string '(int1,int2,...)'. */ public static String ids2str(long[] ids) { StringBuilder sb = new StringBuilder(); sb.append("("); if (ids != null) { String s = Arrays.toString(ids); sb.append(s.substring(1, s.length() - 1)); } sb.append(")"); return sb.toString(); } /** Given a list of integers, return a string '(int1,int2,...)'. */ public static String ids2str(Long[] ids) { StringBuilder sb = new StringBuilder(); sb.append("("); if (ids != null) { String s = Arrays.toString(ids); sb.append(s.substring(1, s.length() - 1)); } sb.append(")"); return sb.toString(); } /** Given a list of integers, return a string '(int1,int2,...)'. */ public static <T> String ids2str(List<T> ids) { StringBuilder sb = new StringBuilder(512); sb.append("("); boolean isNotFirst = false; for (T id : ids) { if (isNotFirst) { sb.append(", "); } else { isNotFirst = true; } sb.append(id); } sb.append(")"); return sb.toString(); } /** Given a list of integers, return a string '(int1,int2,...)'. */ public static String ids2str(JSONArray ids) { StringBuilder str = new StringBuilder(512); str.append("("); if (ids != null) { int len = ids.length(); for (int i = 0; i < len; i++) { try { if (i == (len - 1)) { str.append(ids.get(i)); } else { str.append(ids.get(i)).append(","); } } catch (JSONException e) { Log.e(AnkiDroidApp.TAG, "JSONException = " + e.getMessage()); } } } str.append(")"); return str.toString(); } /** LIBANKI: not in libanki */ public static long[] arrayList2array(List<Long> list) { long[] ar = new long[list.size()]; int i = 0; for (long l : list) { ar[i++] = l; } return ar; } /** Return a non-conflicting timestamp for table. */ public static long timestampID(AnkiDb db, String table) { // be careful not to create multiple objects without flushing them, or they // may share an ID. long t = intNow(1000); while (db.queryScalar("SELECT id FROM " + table + " WHERE id = " + t, false) != 0) { t += 1; } return t; } /** Return the first safe ID to use. */ public static long maxID(AnkiDb db) { long now = intNow(1000); now = Math.max(now, db.queryLongScalar("SELECT MAX(id) FROM cards")); now = Math.max(now, db.queryLongScalar("SELECT MAX(id) FROM notes")); return now + 1; } // used in ankiweb public static String base62(int num, String extra) { String table = ALL_CHARACTERS + extra; int len = table.length(); String buf = ""; int mod = 0; while (num != 0) { mod = num % len; buf = buf + table.substring(mod, mod + 1); num = num / len; } return buf; } // all printable characters minus quotes, backslash and separators public static String base91(int num) { return base62(num, BASE91_EXTRA_CHARS); } /** return a base91-encoded 64bit random number */ public static String guid64() { return base91((new Random()).nextInt((int) (Math.pow(2, 61) - 1))); } // increment a guid by one, for note type conflicts public static String incGuid(String guid) { return new StringBuffer(_incGuid(new StringBuffer(guid).reverse().toString())).reverse().toString(); } private static String _incGuid(String guid) { String table = ALL_CHARACTERS + BASE91_EXTRA_CHARS; int idx = table.indexOf(guid.substring(0, 1)); if (idx + 1 == table.length()) { // overflow guid = table.substring(0, 1) + _incGuid(guid.substring(1, guid.length())); } else { guid = table.substring(idx + 1) + guid.substring(1, guid.length()); } return guid; } // public static JSONArray listToJSONArray(List<Object> list) { // JSONArray jsonArray = new JSONArray(); // // for (Object o : list) { // jsonArray.put(o); // } // // return jsonArray; // } // // // public static List<String> jsonArrayToListString(JSONArray jsonArray) throws JSONException { // ArrayList<String> list = new ArrayList<String>(); // // int len = jsonArray.length(); // for (int i = 0; i < len; i++) { // list.add(jsonArray.getString(i)); // } // // return list; // } public static long[] jsonArrayToLongArray(JSONArray jsonArray) throws JSONException { long[] ar = new long[jsonArray.length()]; for (int i = 0; i < jsonArray.length(); i++) { ar[i] = jsonArray.getLong(i); } return ar; } /** * Fields * *********************************************************************************************** */ public static String joinFields(String[] list) { StringBuilder result = new StringBuilder(128); for (int i = 0; i < list.length - 1; i++) { result.append(list[i]).append("\u001f"); } if (list.length > 0) { result.append(list[list.length - 1]); } return result.toString(); } public static String[] splitFields(String fields) { // do not drop empty fields fields = fields.replaceAll("\\x1f\\x1f", "\u001f\u001e\u001f"); fields = fields.replaceAll("\\x1f$", "\u001f\u001e"); String[] split = fields.split("\\x1f"); for (int i = 0; i < split.length; i++) { if (split[i].matches("\\x1e")) { split[i] = ""; } } return split; } /** * Checksums * *********************************************************************************************** */ /** * SHA1 checksum. * Equivalent to python sha1.hexdigest() * * @param data the string to generate hash from * @return A string of length 40 containing the hexadecimal representation of the MD5 checksum of data. */ public static String checksum(String data) { String result = ""; if (data != null) { MessageDigest md = null; byte[] digest = null; try { md = MessageDigest.getInstance("SHA"); digest = md.digest(stripHTML(data).getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { Log.e(AnkiDroidApp.TAG, "Utils.checksum: No such algorithm. " + e.getMessage()); throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { Log.e(AnkiDroidApp.TAG, "Utils.checksum: " + e.getMessage()); e.printStackTrace(); } BigInteger biginteger = new BigInteger(1, digest); result = biginteger.toString(16); // pad with zeros to length of 40 This method used to pad // to the length of 32. As it turns out, sha1 has a digest // size of 160 bits, leading to a hex digest size of 40, // not 32. if (result.length() < 40) { String zeroes = "0000000000000000000000000000000000000000"; result = zeroes.substring(0, zeroes.length() - result.length()) + result; } } return result; } /** * @param data the string to generate hash from * @return 32 bit unsigned number from first 8 digits of sha1 hash */ public static long fieldChecksum(String data) { return Long.valueOf(checksum(stripHTMLMedia(data)).substring(0, 8), 16); } /** * Generate the SHA1 checksum of a file. * @param file The file to be checked * @return A string of length 32 containing the hexadecimal representation of the SHA1 checksum of the file's contents. */ public static String fileChecksum(String file) { byte[] buffer = new byte[1024]; byte[] digest = null; try { InputStream fis = new FileInputStream(file); MessageDigest md = MessageDigest.getInstance("SHA1"); int numRead = 0; do { numRead = fis.read(buffer); if (numRead > 0) { md.update(buffer, 0, numRead); } } while (numRead != -1); fis.close(); digest = md.digest(); } catch (FileNotFoundException e) { Log.e(AnkiDroidApp.TAG, "Utils.fileChecksum: File not found.", e); } catch (NoSuchAlgorithmException e) { Log.e(AnkiDroidApp.TAG, "Utils.fileChecksum: No such algorithm.", e); } catch (IOException e) { Log.e(AnkiDroidApp.TAG, "Utils.fileChecksum: IO exception.", e); } BigInteger biginteger = new BigInteger(1, digest); String result = biginteger.toString(16); // pad with zeros to length of 40 - SHA1 is 160bit long if (result.length() < 40) { result = "0000000000000000000000000000000000000000".substring(0, 40 - result.length()) + result; } return result; } /** Replace HTML line break tags with new lines. */ public static String replaceLineBreak(String text) { return text.replaceAll("<br(\\s*\\/*)>", "\n"); } // /** // * MD5 sum of file. // * Equivalent to checksum(open(os.path.join(mdir, file), "rb").read())) // * // * @param path The full path to the file // * @return A string of length 32 containing the hexadecimal representation of the MD5 checksum of the contents // * of the file // */ // public static String fileChecksum(String path) { // byte[] bytes = null; // try { // File file = new File(path); // if (file != null && file.isFile()) { // bytes = new byte[(int)file.length()]; // FileInputStream fin = new FileInputStream(file); // fin.read(bytes); // } // } catch (FileNotFoundException e) { // Log.e(AnkiDroidApp.TAG, "Can't find file " + path + " to calculate its checksum"); // } catch (IOException e) { // Log.e(AnkiDroidApp.TAG, "Can't read file " + path + " to calculate its checksum"); // } // if (bytes == null) { // Log.w(AnkiDroidApp.TAG, "File " + path + " appears to be empty"); // return ""; // } // MessageDigest md = null; // byte[] digest = null; // try { // md = MessageDigest.getInstance("MD5"); // digest = md.digest(bytes); // } catch (NoSuchAlgorithmException e) { // Log.e(AnkiDroidApp.TAG, "Utils.checksum: No such algorithm. " + e.getMessage()); // throw new RuntimeException(e); // } // BigInteger biginteger = new BigInteger(1, digest); // String result = biginteger.toString(16); // // pad with zeros to length of 32 // if (result.length() < 32) { // result = "00000000000000000000000000000000".substring(0, 32 - result.length()) + result; // } // return result; // } /** * Tempo files * *********************************************************************************************** */ // tmpdir // tmpfile // namedtmp /** * Converts an InputStream to a String. * @param is InputStream to convert * @return String version of the InputStream */ public static String convertStreamToString(InputStream is) { String contentOfMyInputStream = ""; try { BufferedReader rd = new BufferedReader(new InputStreamReader(is), 4096); String line; StringBuilder sb = new StringBuilder(); while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); contentOfMyInputStream = sb.toString(); } catch (Exception e) { e.printStackTrace(); } return contentOfMyInputStream; } public static boolean unzip(String filename, String targetDirectory) { try { File dir = new File(targetDirectory); if (!dir.exists() || !dir.isDirectory()) { dir.mkdirs(); } byte[] buf = new byte[1024]; ZipInputStream zis = new ZipInputStream(new FileInputStream(filename)); ZipEntry ze = zis.getNextEntry(); while (ze != null) { String name = ze.getName(); Log.i(AnkiDroidApp.TAG, "uncompress " + name); int n; FileOutputStream fos = new FileOutputStream(targetDirectory + "/" + name); while ((n = zis.read(buf, 0, 1024)) > -1) { fos.write(buf, 0, n); } fos.close(); zis.closeEntry(); ze = zis.getNextEntry(); } zis.close(); return true; } catch (IOException e) { Log.e(AnkiDroidApp.TAG, "IOException on decompressing file " + filename); return false; } } /** * Compress data. * @param bytesToCompress is the byte array to compress. * @return a compressed byte array. * @throws java.io.IOException */ public static byte[] compress(byte[] bytesToCompress, int comp) throws IOException { // Compressor with highest level of compression. Deflater compressor = new Deflater(comp, true); // Give the compressor the data to compress. compressor.setInput(bytesToCompress); compressor.finish(); // Create an expandable byte array to hold the compressed data. // It is not necessary that the compressed data will be smaller than // the uncompressed data. ByteArrayOutputStream bos = new ByteArrayOutputStream(bytesToCompress.length); // Compress the data byte[] buf = new byte[65536]; while (!compressor.finished()) { bos.write(buf, 0, compressor.deflate(buf)); } bos.close(); // Get the compressed data return bos.toByteArray(); } /** * Utility method to write to a file. * Throws the exception, so we can report it in syncing log * @throws IOException */ public static void writeToFile(InputStream source, String destination) throws IOException { Log.i(AnkiDroidApp.TAG, "Creating new file... = " + destination); new File(destination).createNewFile(); long startTimeMillis = System.currentTimeMillis(); OutputStream output = new BufferedOutputStream(new FileOutputStream(destination)); // Transfer bytes, from source to destination. byte[] buf = new byte[CHUNK_SIZE]; long sizeBytes = 0; int len; if (source == null) { Log.e(AnkiDroidApp.TAG, "source is null!"); } while ((len = source.read(buf)) >= 0) { output.write(buf, 0, len); sizeBytes += len; } long endTimeMillis = System.currentTimeMillis(); Log.i(AnkiDroidApp.TAG, "Finished writing!"); long durationSeconds = (endTimeMillis - startTimeMillis) / 1000; long sizeKb = sizeBytes / 1024; long speedKbSec = 0; if (endTimeMillis != startTimeMillis) { speedKbSec = sizeKb * 1000 / (endTimeMillis - startTimeMillis); } Log.d(AnkiDroidApp.TAG, "Utils.writeToFile: " + "Size: " + sizeKb + "Kb, " + "Duration: " + durationSeconds + "s, " + "Speed: " + speedKbSec + "Kb/s"); output.close(); } // Print methods public static void printJSONObject(JSONObject jsonObject) { printJSONObject(jsonObject, "-", null); } public static void printJSONObject(JSONObject jsonObject, boolean writeToFile) { BufferedWriter buff; try { buff = writeToFile ? new BufferedWriter(new FileWriter("/sdcard/payloadAndroid.txt"), 8192) : null; try { printJSONObject(jsonObject, "-", buff); } finally { if (buff != null) buff.close(); } } catch (IOException ioe) { Log.e(AnkiDroidApp.TAG, "IOException = " + ioe.getMessage()); } } private static void printJSONObject(JSONObject jsonObject, String indentation, BufferedWriter buff) { try { @SuppressWarnings("unchecked") Iterator<String> keys = (Iterator<String>) jsonObject.keys(); TreeSet<String> orderedKeysSet = new TreeSet<String>(); while (keys.hasNext()) { orderedKeysSet.add(keys.next()); } Iterator<String> orderedKeys = orderedKeysSet.iterator(); while (orderedKeys.hasNext()) { String key = orderedKeys.next(); try { Object value = jsonObject.get(key); if (value instanceof JSONObject) { if (buff != null) { buff.write(indentation + " " + key + " : "); buff.newLine(); } Log.i(AnkiDroidApp.TAG, " " + indentation + key + " : "); printJSONObject((JSONObject) value, indentation + "-", buff); } else { if (buff != null) { buff.write(indentation + " " + key + " = " + jsonObject.get(key).toString()); buff.newLine(); } Log.i(AnkiDroidApp.TAG, " " + indentation + key + " = " + jsonObject.get(key).toString()); } } catch (JSONException e) { Log.e(AnkiDroidApp.TAG, "JSONException = " + e.getMessage()); } } } catch (IOException e1) { Log.e(AnkiDroidApp.TAG, "IOException = " + e1.getMessage()); } } /* public static void saveJSONObject(JSONObject jsonObject) throws IOException { Log.i(AnkiDroidApp.TAG, "saveJSONObject"); BufferedWriter buff = new BufferedWriter(new FileWriter("/sdcard/jsonObjectAndroid.txt", true)); buff.write(jsonObject.toString()); buff.close(); } */ /** * Returns 1 if true, 0 if false * * @param b The boolean to convert to integer * @return 1 if b is true, 0 otherwise */ public static int booleanToInt(boolean b) { return (b) ? 1 : 0; } /** * Returns the effective date of the present moment. * If the time is prior the cut-off time (9:00am by default as of 11/02/10) return yesterday, * otherwise today * Note that the Date class is java.sql.Date whose constructor sets hours, minutes etc to zero * * @param utcOffset The UTC offset in seconds we are going to use to determine today or yesterday. * @return The date (with time set to 00:00:00) that corresponds to today in Anki terms */ public static Date genToday(double utcOffset) { // The result is not adjusted for timezone anymore, following libanki model // Timezone adjustment happens explicitly in Deck.updateCutoff(), but not in Deck.checkDailyStats() SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); df.setTimeZone(TimeZone.getTimeZone("GMT")); Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT")); cal.setTimeInMillis(System.currentTimeMillis() - (long) utcOffset * 1000l); Date today = Date.valueOf(df.format(cal.getTime())); return today; } public static void printDate(String name, double date) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss"); df.setTimeZone(TimeZone.getTimeZone("GMT")); Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT")); cal.setTimeInMillis((long)date * 1000); Log.d(AnkiDroidApp.TAG, "Value of " + name + ": " + cal.getTime().toGMTString()); } public static String doubleToTime(double value) { int time = (int) Math.round(value); int seconds = time % 60; int minutes = (time - seconds) / 60; String formattedTime; if (seconds < 10) { formattedTime = Integer.toString(minutes) + ":0" + Integer.toString(seconds); } else { formattedTime = Integer.toString(minutes) + ":" + Integer.toString(seconds); } return formattedTime; } /** * Returns the proleptic Gregorian ordinal of the date, where January 1 of year 1 has ordinal 1. * @param date Date to convert to ordinal, since 01/01/01 * @return The ordinal representing the date */ public static int dateToOrdinal(Date date) { // BigDate.toOrdinal returns the ordinal since 1970, so we add up the days from 01/01/01 to 1970 return BigDate.toOrdinal(date.getYear() + 1900, date.getMonth() + 1, date.getDate()) + DAYS_BEFORE_1970; } /** * Return the date corresponding to the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1. * @param ordinal representing the days since 01/01/01 * @return Date converted from the ordinal */ public static Date ordinalToDate(int ordinal) { return new Date((new BigDate(ordinal - DAYS_BEFORE_1970)).getLocalDate().getTime()); } /** * Indicates whether the specified action can be used as an intent. This method queries the package manager for * installed packages that can respond to an intent with the specified action. If no suitable package is found, this * method returns false. * @param context The application's environment. * @param action The Intent action to check for availability. * @return True if an Intent with the specified action can be sent and responded to, false otherwise. */ public static boolean isIntentAvailable(Context context, String action) { return isIntentAvailable(context, action, null); } public static boolean isIntentAvailable(Context context, String action, ComponentName componentName) { final PackageManager packageManager = context.getPackageManager(); final Intent intent = new Intent(action); intent.setComponent(componentName); List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); return list.size() > 0; } /** * @param mediaDir media directory path on SD card * @return path converted to file URL, properly UTF-8 URL encoded */ public static String getBaseUrl(String mediaDir) { // Use android.net.Uri class to ensure whole path is properly encoded // File.toURL() does not work here, and URLEncoder class is not directly usable // with existing slashes if (mediaDir.length() != 0 && !mediaDir.equalsIgnoreCase("null")) { Uri mediaDirUri = Uri.fromFile(new File(mediaDir)); return mediaDirUri.toString() +"/"; } return ""; } /** * Take an array of Long and return an array of long * * @param array The input with type Long[] * @return The output with type long[] */ public static long[] toPrimitive(Long[] array) { long[] results = new long[array.length]; if (array != null) { for (int i = 0; i < array.length; i++) { results[i] = array[i].longValue(); } } return results; } public static long[] toPrimitive(Collection<Long> array) { long[] results = new long[array.size()]; if (array != null) { int i = 0; for (Long item : array) { results[i++] = item.longValue(); } } return results; } public static void updateProgressBars(View view, int x, int y) { if (view == null) { return; } if (view.getParent() instanceof LinearLayout) { LinearLayout.LayoutParams lparam = new LinearLayout.LayoutParams(0, 0); lparam.height = y; lparam.width = x; view.setLayoutParams(lparam); } else if (view.getParent() instanceof FrameLayout) { FrameLayout.LayoutParams lparam = new FrameLayout.LayoutParams(0, 0); lparam.height = y; lparam.width = x; view.setLayoutParams(lparam); } } /** * Calculate the UTC offset */ public static double utcOffset() { Calendar cal = Calendar.getInstance(); // 4am return 4 * 60 * 60 - (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET)) / 1000; } /** Returns the filename without the extension. */ public static String removeExtension(String filename) { int dotPosition = filename.lastIndexOf('.'); if (dotPosition == -1) { return filename; } return filename.substring(0, dotPosition); } /** Removes any character that are not valid as deck names. */ public static String removeInvalidDeckNameCharacters(String name) { if (name == null) { return null; } // The only characters that we cannot absolutely allow to appear in the filename are the ones reserved in some // file system. Currently these are \, /, and :, in order to cover Linux, OSX, and Windows. return name.replaceAll("[:/\\\\]", ""); } /** Returns a list of files for the installed custom fonts. */ public static List<AnkiFont> getCustomFonts(Context context) { String deckPath = AnkiDroidApp.getCurrentAnkiDroidDirectory(); String fontsPath = deckPath + "/fonts/"; File fontsDir = new File(fontsPath); int fontsCount = 0; File[] fontsList = null; if (fontsDir.exists() && fontsDir.isDirectory()) { fontsCount = fontsDir.listFiles().length; fontsList = fontsDir.listFiles(); } String[] ankiDroidFonts = null; try { ankiDroidFonts = context.getAssets().list("fonts"); } catch (IOException e) { Log.e(AnkiDroidApp.TAG, "Error on retrieving ankidroid fonts: " + e); } List<AnkiFont> fonts = new ArrayList<AnkiFont>(); for (int i = 0; i < fontsCount; i++) { AnkiFont font = AnkiFont.createAnkiFont(context, fontsList[i].getAbsolutePath(), false); if (font != null) { fonts.add(font); } } for (int i = 0; i < ankiDroidFonts.length; i++) { AnkiFont font = AnkiFont.createAnkiFont(context, ankiDroidFonts[i], true); if (font != null) { fonts.add(font); } } return fonts; } /** Returns a list of apkg-files. */ public static List<File> getImportableDecks() { String deckPath = AnkiDroidApp.getCurrentAnkiDroidDirectory(); File dir = new File(deckPath); int deckCount = 0; File[] deckList = null; if (dir.exists() && dir.isDirectory()) { deckList = dir.listFiles(new FileFilter(){ @Override public boolean accept(File pathname) { if (pathname.isFile() && pathname.getName().endsWith(".apkg")) { return true; } return false; } }); deckCount = deckList.length; } List<File> decks = new ArrayList<File>(); for (int i = 0; i < deckCount; i++) { decks.add(deckList[i]); } return decks; } /** Joins the given string values using the delimiter between them. */ public static String join(String delimiter, String... values) { StringBuilder sb = new StringBuilder(); for (String value : values) { if (sb.length() != 0) { sb.append(delimiter); } sb.append(value); } return sb.toString(); } /** * Simply copy a file to another location * @param sourceFile The source file * @param destFile The destination file, doesn't need to exist yet. * @throws IOException */ public static void copyFile(File sourceFile, File destFile) throws IOException { if(!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } }
public static String fmtTimeSpan(int time, int format, boolean _short, boolean boldNumber) { int type; int unit = 99; int point = 0; if (Math.abs(time) < 60 || unit < 1) { type = TIME_SECONDS; } else if (Math.abs(time) < 3600 || unit < 2) { type = TIME_MINUTES; } else if (Math.abs(time) < 60 * 60 * 24 || unit < 3) { type = TIME_HOURS; } else if (Math.abs(time) < 60 * 60 * 24 * 29.5 || unit < 4) { type = TIME_DAYS; } else if (Math.abs(time) < 60 * 60 * 24 * 30 * 11.95 || unit < 5) { type = TIME_MONTHS; point = 1; } else { type = TIME_YEARS; point = 1; } double ftime = convertSecondsTo(time, type); int formatId; if (false){//_short) { //formatId = R.array.next_review_short; } else { switch (format) { case TIME_FORMAT_IN: if (Math.round(ftime * 10) == 10) { formatId = R.array.next_review_in_s; } else { formatId = R.array.next_review_in_p; } break; case TIME_FORMAT_BEFORE: if (Math.round(ftime * 10) == 10) { formatId = R.array.next_review_before_s; } else { formatId = R.array.next_review_before_p; } break; case TIME_FORMAT_DEFAULT: default: if (Math.round(ftime * 10) == 10) { formatId = R.array.next_review_s; } else { formatId = R.array.next_review_p; } break; } } String timeString = String.format(AnkiDroidApp.getAppResources().getStringArray(formatId)[type], boldNumber ? "<b>" + fmtDouble(ftime, point) + "</b>" : fmtDouble(ftime, point)); if (boldNumber && time == 1) { timeString = timeString.replace("1", "<b>1</b>"); } return timeString; } private static double convertSecondsTo(int seconds, int type) { switch (type) { case TIME_SECONDS: return seconds; case TIME_MINUTES: return seconds / 60.0; case TIME_HOURS: return seconds / 3600.0; case TIME_DAYS: return seconds / 86400.0; case TIME_MONTHS: return seconds / 2592000.0; case TIME_YEARS: return seconds / 31536000.0; default: return 0; } } /** * Locale * *********************************************************************************************** */ /** * @return double with percentage sign */ public static String fmtPercentage(Double value) { return fmtPercentage(value, 0); } public static String fmtPercentage(Double value, int point) { // only retrieve the percentage format the first time if (mCurrentPercentageFormat == null) { mCurrentPercentageFormat = NumberFormat.getPercentInstance(Locale.getDefault()); } mCurrentNumberFormat.setMaximumFractionDigits(point); return mCurrentPercentageFormat.format(value); } /** * @return a string with decimal separator according to current locale */ public static String fmtDouble(Double value) { return fmtDouble(value, 1); } public static String fmtDouble(Double value, int point) { // only retrieve the number format the first time if (mCurrentNumberFormat == null) { mCurrentNumberFormat = NumberFormat.getInstance(Locale.getDefault()); } mCurrentNumberFormat.setMaximumFractionDigits(point); return mCurrentNumberFormat.format(value); } /** * HTML * *********************************************************************************************** */ /** * Strips a text from <style>...</style>, <script>...</script> and <_any_tag_> HTML tags. * @param The HTML text to be cleaned. * @return The text without the aforementioned tags. */ public static String stripHTML(String s) { Matcher htmlMatcher = stylePattern.matcher(s); s = htmlMatcher.replaceAll(""); htmlMatcher = scriptPattern.matcher(s); s = htmlMatcher.replaceAll(""); htmlMatcher = tagPattern.matcher(s); s = htmlMatcher.replaceAll(""); return entsToTxt(s); } /** * Strip HTML but keep media filenames */ public static String stripHTMLMedia(String s) { Matcher imgMatcher = imgPattern.matcher(s); return stripHTML(imgMatcher.replaceAll(" $1 ")); } private String minimizeHTML(String s) { // TODO return s; } /** * Takes a string and replaces all the HTML symbols in it with their unescaped representation. * This should only affect substrings of the form &something; and not tags. * Internet rumour says that Html.fromHtml() doesn't cover all cases, but it doesn't get less * vague than that. * @param html The HTML escaped text * @return The text with its HTML entities unescaped. */ private static String entsToTxt(String html) { Matcher htmlEntities = htmlEntitiesPattern.matcher(html); StringBuffer sb = new StringBuffer(); while (htmlEntities.find()) { htmlEntities.appendReplacement(sb, Html.fromHtml(htmlEntities.group()).toString()); } htmlEntities.appendTail(sb); return sb.toString(); } /** * IDs * *********************************************************************************************** */ public static String hexifyID(long id) { return Long.toHexString(id); } public static long dehexifyID(String id) { return Long.valueOf(id, 16); } /** Given a list of integers, return a string '(int1,int2,...)'. */ public static String ids2str(int[] ids) { StringBuilder sb = new StringBuilder(); sb.append("("); if (ids != null) { String s = Arrays.toString(ids); sb.append(s.substring(1, s.length() - 1)); } sb.append(")"); return sb.toString(); } /** Given a list of integers, return a string '(int1,int2,...)'. */ public static String ids2str(long[] ids) { StringBuilder sb = new StringBuilder(); sb.append("("); if (ids != null) { String s = Arrays.toString(ids); sb.append(s.substring(1, s.length() - 1)); } sb.append(")"); return sb.toString(); } /** Given a list of integers, return a string '(int1,int2,...)'. */ public static String ids2str(Long[] ids) { StringBuilder sb = new StringBuilder(); sb.append("("); if (ids != null) { String s = Arrays.toString(ids); sb.append(s.substring(1, s.length() - 1)); } sb.append(")"); return sb.toString(); } /** Given a list of integers, return a string '(int1,int2,...)'. */ public static <T> String ids2str(List<T> ids) { StringBuilder sb = new StringBuilder(512); sb.append("("); boolean isNotFirst = false; for (T id : ids) { if (isNotFirst) { sb.append(", "); } else { isNotFirst = true; } sb.append(id); } sb.append(")"); return sb.toString(); } /** Given a list of integers, return a string '(int1,int2,...)'. */ public static String ids2str(JSONArray ids) { StringBuilder str = new StringBuilder(512); str.append("("); if (ids != null) { int len = ids.length(); for (int i = 0; i < len; i++) { try { if (i == (len - 1)) { str.append(ids.get(i)); } else { str.append(ids.get(i)).append(","); } } catch (JSONException e) { Log.e(AnkiDroidApp.TAG, "JSONException = " + e.getMessage()); } } } str.append(")"); return str.toString(); } /** LIBANKI: not in libanki */ public static long[] arrayList2array(List<Long> list) { long[] ar = new long[list.size()]; int i = 0; for (long l : list) { ar[i++] = l; } return ar; } /** Return a non-conflicting timestamp for table. */ public static long timestampID(AnkiDb db, String table) { // be careful not to create multiple objects without flushing them, or they // may share an ID. long t = intNow(1000); while (db.queryScalar("SELECT id FROM " + table + " WHERE id = " + t, false) != 0) { t += 1; } return t; } /** Return the first safe ID to use. */ public static long maxID(AnkiDb db) { long now = intNow(1000); now = Math.max(now, db.queryLongScalar("SELECT MAX(id) FROM cards")); now = Math.max(now, db.queryLongScalar("SELECT MAX(id) FROM notes")); return now + 1; } // used in ankiweb public static String base62(int num, String extra) { String table = ALL_CHARACTERS + extra; int len = table.length(); String buf = ""; int mod = 0; while (num != 0) { mod = num % len; buf = buf + table.substring(mod, mod + 1); num = num / len; } return buf; } // all printable characters minus quotes, backslash and separators public static String base91(int num) { return base62(num, BASE91_EXTRA_CHARS); } /** return a base91-encoded 64bit random number */ public static String guid64() { return base91((new Random()).nextInt((int) (Math.pow(2, 61) - 1))); } // increment a guid by one, for note type conflicts public static String incGuid(String guid) { return new StringBuffer(_incGuid(new StringBuffer(guid).reverse().toString())).reverse().toString(); } private static String _incGuid(String guid) { String table = ALL_CHARACTERS + BASE91_EXTRA_CHARS; int idx = table.indexOf(guid.substring(0, 1)); if (idx + 1 == table.length()) { // overflow guid = table.substring(0, 1) + _incGuid(guid.substring(1, guid.length())); } else { guid = table.substring(idx + 1) + guid.substring(1, guid.length()); } return guid; } // public static JSONArray listToJSONArray(List<Object> list) { // JSONArray jsonArray = new JSONArray(); // // for (Object o : list) { // jsonArray.put(o); // } // // return jsonArray; // } // // // public static List<String> jsonArrayToListString(JSONArray jsonArray) throws JSONException { // ArrayList<String> list = new ArrayList<String>(); // // int len = jsonArray.length(); // for (int i = 0; i < len; i++) { // list.add(jsonArray.getString(i)); // } // // return list; // } public static long[] jsonArrayToLongArray(JSONArray jsonArray) throws JSONException { long[] ar = new long[jsonArray.length()]; for (int i = 0; i < jsonArray.length(); i++) { ar[i] = jsonArray.getLong(i); } return ar; } /** * Fields * *********************************************************************************************** */ public static String joinFields(String[] list) { StringBuilder result = new StringBuilder(128); for (int i = 0; i < list.length - 1; i++) { result.append(list[i]).append("\u001f"); } if (list.length > 0) { result.append(list[list.length - 1]); } return result.toString(); } public static String[] splitFields(String fields) { // do not drop empty fields fields = fields.replaceAll("\\x1f\\x1f", "\u001f\u001e\u001f"); fields = fields.replaceAll("\\x1f$", "\u001f\u001e"); String[] split = fields.split("\\x1f"); for (int i = 0; i < split.length; i++) { if (split[i].matches("\\x1e")) { split[i] = ""; } } return split; } /** * Checksums * *********************************************************************************************** */ /** * SHA1 checksum. * Equivalent to python sha1.hexdigest() * * @param data the string to generate hash from * @return A string of length 40 containing the hexadecimal representation of the MD5 checksum of data. */ public static String checksum(String data) { String result = ""; if (data != null) { MessageDigest md = null; byte[] digest = null; try { md = MessageDigest.getInstance("SHA1"); digest = md.digest(data.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { Log.e(AnkiDroidApp.TAG, "Utils.checksum: No such algorithm. " + e.getMessage()); throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { Log.e(AnkiDroidApp.TAG, "Utils.checksum: " + e.getMessage()); e.printStackTrace(); } BigInteger biginteger = new BigInteger(1, digest); result = biginteger.toString(16); // pad with zeros to length of 40 This method used to pad // to the length of 32. As it turns out, sha1 has a digest // size of 160 bits, leading to a hex digest size of 40, // not 32. if (result.length() < 40) { String zeroes = "0000000000000000000000000000000000000000"; result = zeroes.substring(0, zeroes.length() - result.length()) + result; } } return result; } /** * @param data the string to generate hash from * @return 32 bit unsigned number from first 8 digits of sha1 hash */ public static long fieldChecksum(String data) { return Long.valueOf(checksum(stripHTMLMedia(data)).substring(0, 8), 16); } /** * Generate the SHA1 checksum of a file. * @param file The file to be checked * @return A string of length 32 containing the hexadecimal representation of the SHA1 checksum of the file's contents. */ public static String fileChecksum(String file) { byte[] buffer = new byte[1024]; byte[] digest = null; try { InputStream fis = new FileInputStream(file); MessageDigest md = MessageDigest.getInstance("SHA1"); int numRead = 0; do { numRead = fis.read(buffer); if (numRead > 0) { md.update(buffer, 0, numRead); } } while (numRead != -1); fis.close(); digest = md.digest(); } catch (FileNotFoundException e) { Log.e(AnkiDroidApp.TAG, "Utils.fileChecksum: File not found.", e); } catch (NoSuchAlgorithmException e) { Log.e(AnkiDroidApp.TAG, "Utils.fileChecksum: No such algorithm.", e); } catch (IOException e) { Log.e(AnkiDroidApp.TAG, "Utils.fileChecksum: IO exception.", e); } BigInteger biginteger = new BigInteger(1, digest); String result = biginteger.toString(16); // pad with zeros to length of 40 - SHA1 is 160bit long if (result.length() < 40) { result = "0000000000000000000000000000000000000000".substring(0, 40 - result.length()) + result; } return result; } /** Replace HTML line break tags with new lines. */ public static String replaceLineBreak(String text) { return text.replaceAll("<br(\\s*\\/*)>", "\n"); } // /** // * MD5 sum of file. // * Equivalent to checksum(open(os.path.join(mdir, file), "rb").read())) // * // * @param path The full path to the file // * @return A string of length 32 containing the hexadecimal representation of the MD5 checksum of the contents // * of the file // */ // public static String fileChecksum(String path) { // byte[] bytes = null; // try { // File file = new File(path); // if (file != null && file.isFile()) { // bytes = new byte[(int)file.length()]; // FileInputStream fin = new FileInputStream(file); // fin.read(bytes); // } // } catch (FileNotFoundException e) { // Log.e(AnkiDroidApp.TAG, "Can't find file " + path + " to calculate its checksum"); // } catch (IOException e) { // Log.e(AnkiDroidApp.TAG, "Can't read file " + path + " to calculate its checksum"); // } // if (bytes == null) { // Log.w(AnkiDroidApp.TAG, "File " + path + " appears to be empty"); // return ""; // } // MessageDigest md = null; // byte[] digest = null; // try { // md = MessageDigest.getInstance("MD5"); // digest = md.digest(bytes); // } catch (NoSuchAlgorithmException e) { // Log.e(AnkiDroidApp.TAG, "Utils.checksum: No such algorithm. " + e.getMessage()); // throw new RuntimeException(e); // } // BigInteger biginteger = new BigInteger(1, digest); // String result = biginteger.toString(16); // // pad with zeros to length of 32 // if (result.length() < 32) { // result = "00000000000000000000000000000000".substring(0, 32 - result.length()) + result; // } // return result; // } /** * Tempo files * *********************************************************************************************** */ // tmpdir // tmpfile // namedtmp /** * Converts an InputStream to a String. * @param is InputStream to convert * @return String version of the InputStream */ public static String convertStreamToString(InputStream is) { String contentOfMyInputStream = ""; try { BufferedReader rd = new BufferedReader(new InputStreamReader(is), 4096); String line; StringBuilder sb = new StringBuilder(); while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); contentOfMyInputStream = sb.toString(); } catch (Exception e) { e.printStackTrace(); } return contentOfMyInputStream; } public static boolean unzip(String filename, String targetDirectory) { try { File dir = new File(targetDirectory); if (!dir.exists() || !dir.isDirectory()) { dir.mkdirs(); } byte[] buf = new byte[1024]; ZipInputStream zis = new ZipInputStream(new FileInputStream(filename)); ZipEntry ze = zis.getNextEntry(); while (ze != null) { String name = ze.getName(); Log.i(AnkiDroidApp.TAG, "uncompress " + name); int n; FileOutputStream fos = new FileOutputStream(targetDirectory + "/" + name); while ((n = zis.read(buf, 0, 1024)) > -1) { fos.write(buf, 0, n); } fos.close(); zis.closeEntry(); ze = zis.getNextEntry(); } zis.close(); return true; } catch (IOException e) { Log.e(AnkiDroidApp.TAG, "IOException on decompressing file " + filename); return false; } } /** * Compress data. * @param bytesToCompress is the byte array to compress. * @return a compressed byte array. * @throws java.io.IOException */ public static byte[] compress(byte[] bytesToCompress, int comp) throws IOException { // Compressor with highest level of compression. Deflater compressor = new Deflater(comp, true); // Give the compressor the data to compress. compressor.setInput(bytesToCompress); compressor.finish(); // Create an expandable byte array to hold the compressed data. // It is not necessary that the compressed data will be smaller than // the uncompressed data. ByteArrayOutputStream bos = new ByteArrayOutputStream(bytesToCompress.length); // Compress the data byte[] buf = new byte[65536]; while (!compressor.finished()) { bos.write(buf, 0, compressor.deflate(buf)); } bos.close(); // Get the compressed data return bos.toByteArray(); } /** * Utility method to write to a file. * Throws the exception, so we can report it in syncing log * @throws IOException */ public static void writeToFile(InputStream source, String destination) throws IOException { Log.i(AnkiDroidApp.TAG, "Creating new file... = " + destination); new File(destination).createNewFile(); long startTimeMillis = System.currentTimeMillis(); OutputStream output = new BufferedOutputStream(new FileOutputStream(destination)); // Transfer bytes, from source to destination. byte[] buf = new byte[CHUNK_SIZE]; long sizeBytes = 0; int len; if (source == null) { Log.e(AnkiDroidApp.TAG, "source is null!"); } while ((len = source.read(buf)) >= 0) { output.write(buf, 0, len); sizeBytes += len; } long endTimeMillis = System.currentTimeMillis(); Log.i(AnkiDroidApp.TAG, "Finished writing!"); long durationSeconds = (endTimeMillis - startTimeMillis) / 1000; long sizeKb = sizeBytes / 1024; long speedKbSec = 0; if (endTimeMillis != startTimeMillis) { speedKbSec = sizeKb * 1000 / (endTimeMillis - startTimeMillis); } Log.d(AnkiDroidApp.TAG, "Utils.writeToFile: " + "Size: " + sizeKb + "Kb, " + "Duration: " + durationSeconds + "s, " + "Speed: " + speedKbSec + "Kb/s"); output.close(); } // Print methods public static void printJSONObject(JSONObject jsonObject) { printJSONObject(jsonObject, "-", null); } public static void printJSONObject(JSONObject jsonObject, boolean writeToFile) { BufferedWriter buff; try { buff = writeToFile ? new BufferedWriter(new FileWriter("/sdcard/payloadAndroid.txt"), 8192) : null; try { printJSONObject(jsonObject, "-", buff); } finally { if (buff != null) buff.close(); } } catch (IOException ioe) { Log.e(AnkiDroidApp.TAG, "IOException = " + ioe.getMessage()); } } private static void printJSONObject(JSONObject jsonObject, String indentation, BufferedWriter buff) { try { @SuppressWarnings("unchecked") Iterator<String> keys = (Iterator<String>) jsonObject.keys(); TreeSet<String> orderedKeysSet = new TreeSet<String>(); while (keys.hasNext()) { orderedKeysSet.add(keys.next()); } Iterator<String> orderedKeys = orderedKeysSet.iterator(); while (orderedKeys.hasNext()) { String key = orderedKeys.next(); try { Object value = jsonObject.get(key); if (value instanceof JSONObject) { if (buff != null) { buff.write(indentation + " " + key + " : "); buff.newLine(); } Log.i(AnkiDroidApp.TAG, " " + indentation + key + " : "); printJSONObject((JSONObject) value, indentation + "-", buff); } else { if (buff != null) { buff.write(indentation + " " + key + " = " + jsonObject.get(key).toString()); buff.newLine(); } Log.i(AnkiDroidApp.TAG, " " + indentation + key + " = " + jsonObject.get(key).toString()); } } catch (JSONException e) { Log.e(AnkiDroidApp.TAG, "JSONException = " + e.getMessage()); } } } catch (IOException e1) { Log.e(AnkiDroidApp.TAG, "IOException = " + e1.getMessage()); } } /* public static void saveJSONObject(JSONObject jsonObject) throws IOException { Log.i(AnkiDroidApp.TAG, "saveJSONObject"); BufferedWriter buff = new BufferedWriter(new FileWriter("/sdcard/jsonObjectAndroid.txt", true)); buff.write(jsonObject.toString()); buff.close(); } */ /** * Returns 1 if true, 0 if false * * @param b The boolean to convert to integer * @return 1 if b is true, 0 otherwise */ public static int booleanToInt(boolean b) { return (b) ? 1 : 0; } /** * Returns the effective date of the present moment. * If the time is prior the cut-off time (9:00am by default as of 11/02/10) return yesterday, * otherwise today * Note that the Date class is java.sql.Date whose constructor sets hours, minutes etc to zero * * @param utcOffset The UTC offset in seconds we are going to use to determine today or yesterday. * @return The date (with time set to 00:00:00) that corresponds to today in Anki terms */ public static Date genToday(double utcOffset) { // The result is not adjusted for timezone anymore, following libanki model // Timezone adjustment happens explicitly in Deck.updateCutoff(), but not in Deck.checkDailyStats() SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); df.setTimeZone(TimeZone.getTimeZone("GMT")); Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT")); cal.setTimeInMillis(System.currentTimeMillis() - (long) utcOffset * 1000l); Date today = Date.valueOf(df.format(cal.getTime())); return today; } public static void printDate(String name, double date) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss"); df.setTimeZone(TimeZone.getTimeZone("GMT")); Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT")); cal.setTimeInMillis((long)date * 1000); Log.d(AnkiDroidApp.TAG, "Value of " + name + ": " + cal.getTime().toGMTString()); } public static String doubleToTime(double value) { int time = (int) Math.round(value); int seconds = time % 60; int minutes = (time - seconds) / 60; String formattedTime; if (seconds < 10) { formattedTime = Integer.toString(minutes) + ":0" + Integer.toString(seconds); } else { formattedTime = Integer.toString(minutes) + ":" + Integer.toString(seconds); } return formattedTime; } /** * Returns the proleptic Gregorian ordinal of the date, where January 1 of year 1 has ordinal 1. * @param date Date to convert to ordinal, since 01/01/01 * @return The ordinal representing the date */ public static int dateToOrdinal(Date date) { // BigDate.toOrdinal returns the ordinal since 1970, so we add up the days from 01/01/01 to 1970 return BigDate.toOrdinal(date.getYear() + 1900, date.getMonth() + 1, date.getDate()) + DAYS_BEFORE_1970; } /** * Return the date corresponding to the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1. * @param ordinal representing the days since 01/01/01 * @return Date converted from the ordinal */ public static Date ordinalToDate(int ordinal) { return new Date((new BigDate(ordinal - DAYS_BEFORE_1970)).getLocalDate().getTime()); } /** * Indicates whether the specified action can be used as an intent. This method queries the package manager for * installed packages that can respond to an intent with the specified action. If no suitable package is found, this * method returns false. * @param context The application's environment. * @param action The Intent action to check for availability. * @return True if an Intent with the specified action can be sent and responded to, false otherwise. */ public static boolean isIntentAvailable(Context context, String action) { return isIntentAvailable(context, action, null); } public static boolean isIntentAvailable(Context context, String action, ComponentName componentName) { final PackageManager packageManager = context.getPackageManager(); final Intent intent = new Intent(action); intent.setComponent(componentName); List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); return list.size() > 0; } /** * @param mediaDir media directory path on SD card * @return path converted to file URL, properly UTF-8 URL encoded */ public static String getBaseUrl(String mediaDir) { // Use android.net.Uri class to ensure whole path is properly encoded // File.toURL() does not work here, and URLEncoder class is not directly usable // with existing slashes if (mediaDir.length() != 0 && !mediaDir.equalsIgnoreCase("null")) { Uri mediaDirUri = Uri.fromFile(new File(mediaDir)); return mediaDirUri.toString() +"/"; } return ""; } /** * Take an array of Long and return an array of long * * @param array The input with type Long[] * @return The output with type long[] */ public static long[] toPrimitive(Long[] array) { long[] results = new long[array.length]; if (array != null) { for (int i = 0; i < array.length; i++) { results[i] = array[i].longValue(); } } return results; } public static long[] toPrimitive(Collection<Long> array) { long[] results = new long[array.size()]; if (array != null) { int i = 0; for (Long item : array) { results[i++] = item.longValue(); } } return results; } public static void updateProgressBars(View view, int x, int y) { if (view == null) { return; } if (view.getParent() instanceof LinearLayout) { LinearLayout.LayoutParams lparam = new LinearLayout.LayoutParams(0, 0); lparam.height = y; lparam.width = x; view.setLayoutParams(lparam); } else if (view.getParent() instanceof FrameLayout) { FrameLayout.LayoutParams lparam = new FrameLayout.LayoutParams(0, 0); lparam.height = y; lparam.width = x; view.setLayoutParams(lparam); } } /** * Calculate the UTC offset */ public static double utcOffset() { Calendar cal = Calendar.getInstance(); // 4am return 4 * 60 * 60 - (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET)) / 1000; } /** Returns the filename without the extension. */ public static String removeExtension(String filename) { int dotPosition = filename.lastIndexOf('.'); if (dotPosition == -1) { return filename; } return filename.substring(0, dotPosition); } /** Removes any character that are not valid as deck names. */ public static String removeInvalidDeckNameCharacters(String name) { if (name == null) { return null; } // The only characters that we cannot absolutely allow to appear in the filename are the ones reserved in some // file system. Currently these are \, /, and :, in order to cover Linux, OSX, and Windows. return name.replaceAll("[:/\\\\]", ""); } /** Returns a list of files for the installed custom fonts. */ public static List<AnkiFont> getCustomFonts(Context context) { String deckPath = AnkiDroidApp.getCurrentAnkiDroidDirectory(); String fontsPath = deckPath + "/fonts/"; File fontsDir = new File(fontsPath); int fontsCount = 0; File[] fontsList = null; if (fontsDir.exists() && fontsDir.isDirectory()) { fontsCount = fontsDir.listFiles().length; fontsList = fontsDir.listFiles(); } String[] ankiDroidFonts = null; try { ankiDroidFonts = context.getAssets().list("fonts"); } catch (IOException e) { Log.e(AnkiDroidApp.TAG, "Error on retrieving ankidroid fonts: " + e); } List<AnkiFont> fonts = new ArrayList<AnkiFont>(); for (int i = 0; i < fontsCount; i++) { AnkiFont font = AnkiFont.createAnkiFont(context, fontsList[i].getAbsolutePath(), false); if (font != null) { fonts.add(font); } } for (int i = 0; i < ankiDroidFonts.length; i++) { AnkiFont font = AnkiFont.createAnkiFont(context, ankiDroidFonts[i], true); if (font != null) { fonts.add(font); } } return fonts; } /** Returns a list of apkg-files. */ public static List<File> getImportableDecks() { String deckPath = AnkiDroidApp.getCurrentAnkiDroidDirectory(); File dir = new File(deckPath); int deckCount = 0; File[] deckList = null; if (dir.exists() && dir.isDirectory()) { deckList = dir.listFiles(new FileFilter(){ @Override public boolean accept(File pathname) { if (pathname.isFile() && pathname.getName().endsWith(".apkg")) { return true; } return false; } }); deckCount = deckList.length; } List<File> decks = new ArrayList<File>(); for (int i = 0; i < deckCount; i++) { decks.add(deckList[i]); } return decks; } /** Joins the given string values using the delimiter between them. */ public static String join(String delimiter, String... values) { StringBuilder sb = new StringBuilder(); for (String value : values) { if (sb.length() != 0) { sb.append(delimiter); } sb.append(value); } return sb.toString(); } /** * Simply copy a file to another location * @param sourceFile The source file * @param destFile The destination file, doesn't need to exist yet. * @throws IOException */ public static void copyFile(File sourceFile, File destFile) throws IOException { if(!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } }
diff --git a/src/com/oresomecraft/maps/tiot/OresomeTownOffices.java b/src/com/oresomecraft/maps/tiot/OresomeTownOffices.java index 4c4b122..7910ca5 100644 --- a/src/com/oresomecraft/maps/tiot/OresomeTownOffices.java +++ b/src/com/oresomecraft/maps/tiot/OresomeTownOffices.java @@ -1,47 +1,47 @@ package com.oresomecraft.maps.tiot; import com.oresomecraft.OresomeBattles.api.BattlePlayer; import com.oresomecraft.OresomeBattles.api.CuboidRegion; import com.oresomecraft.OresomeBattles.api.Gamemode; import com.oresomecraft.maps.MapConfig; import com.oresomecraft.maps.battles.BattleMap; import com.oresomecraft.maps.battles.IBattleMap; import org.bukkit.Location; import org.bukkit.event.Listener; @MapConfig public class OresomeTownOffices extends BattleMap implements IBattleMap, Listener { public OresomeTownOffices() { super.initiate(this, name, fullName, creators, modes); setAllowBuild(false); } // Map details String name = "oresometownoffices"; String fullName = "OresomeTown Offices"; String creators = "meganlovesmusic, SuperDuckFace, ninsai and psgs"; Gamemode[] modes = {Gamemode.TIOT}; public void readyFFASpawns() { FFASpawns.add(new Location(w, -47, 80, 0, -90, 0)); FFASpawns.add(new Location(w, 48, 80, 0, 90, 0)); FFASpawns.add(new Location(w, 0, 80, 48, 180, 0)); FFASpawns.add(new Location(w, 0, 80, -47)); FFASpawns.add(new Location(w, 16, 70, -17, 47, 0)); FFASpawns.add(new Location(w, -17, 70, 16, -132, 0)); FFASpawns.add(new Location(w, 4, 58, 40, 152, 0)); FFASpawns.add(new Location(w, -3, 58, -50, -23, 0)); - setCriminalTester(new CuboidRegion(new Location(w, 2, 65, 2), new Location(w, -1, 68, -1))); + setCriminalTester(new CuboidRegion(new Location(w, 2, 65, 2), new Location(w, -2, 70, -2))); } public void readyTDMSpawns() { // No TDM spawns } public void applyInventory(final BattlePlayer p) { // No predefined inventory } }
true
true
public void readyFFASpawns() { FFASpawns.add(new Location(w, -47, 80, 0, -90, 0)); FFASpawns.add(new Location(w, 48, 80, 0, 90, 0)); FFASpawns.add(new Location(w, 0, 80, 48, 180, 0)); FFASpawns.add(new Location(w, 0, 80, -47)); FFASpawns.add(new Location(w, 16, 70, -17, 47, 0)); FFASpawns.add(new Location(w, -17, 70, 16, -132, 0)); FFASpawns.add(new Location(w, 4, 58, 40, 152, 0)); FFASpawns.add(new Location(w, -3, 58, -50, -23, 0)); setCriminalTester(new CuboidRegion(new Location(w, 2, 65, 2), new Location(w, -1, 68, -1))); }
public void readyFFASpawns() { FFASpawns.add(new Location(w, -47, 80, 0, -90, 0)); FFASpawns.add(new Location(w, 48, 80, 0, 90, 0)); FFASpawns.add(new Location(w, 0, 80, 48, 180, 0)); FFASpawns.add(new Location(w, 0, 80, -47)); FFASpawns.add(new Location(w, 16, 70, -17, 47, 0)); FFASpawns.add(new Location(w, -17, 70, 16, -132, 0)); FFASpawns.add(new Location(w, 4, 58, 40, 152, 0)); FFASpawns.add(new Location(w, -3, 58, -50, -23, 0)); setCriminalTester(new CuboidRegion(new Location(w, 2, 65, 2), new Location(w, -2, 70, -2))); }
diff --git a/src/autosaveworld/threads/backup/ExcludeManager.java b/src/autosaveworld/threads/backup/ExcludeManager.java index b849f26..00bebb2 100644 --- a/src/autosaveworld/threads/backup/ExcludeManager.java +++ b/src/autosaveworld/threads/backup/ExcludeManager.java @@ -1,68 +1,68 @@ /** * 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ package autosaveworld.threads.backup; import java.io.File; import java.util.List; import org.bukkit.Bukkit; import org.bukkit.World; public class ExcludeManager { public static boolean isFolderExcluded(List<String> excludelist, String folder) { - //ignore configured fodlers + //ignore configured folders for (String ef : excludelist) { if (ef.contains("*") && ef.indexOf("*") == ef.length()-1) { //resolve wildcard //check parents folders equality if (new File(folder).getAbsoluteFile().getParentFile().equals(new File(ef).getAbsoluteFile().getParentFile())) { //check name equality String efname = new File(ef).getName(); if (new File(folder).getName().contains(efname.substring(0,efname.indexOf("*")))) { return true; } } } else { //plain folders equality check if (new File(folder).getAbsoluteFile().equals(new File(ef).getAbsoluteFile())) { return true; } } } //ignore others worlds folders (for mcpc+) for (World w : Bukkit.getWorlds()) { if (new File(folder).isDirectory() && new File(folder).getName().equals(w.getWorldFolder().getName())) { return true; } } return false; } }
true
true
public static boolean isFolderExcluded(List<String> excludelist, String folder) { //ignore configured fodlers for (String ef : excludelist) { if (ef.contains("*") && ef.indexOf("*") == ef.length()-1) { //resolve wildcard //check parents folders equality if (new File(folder).getAbsoluteFile().getParentFile().equals(new File(ef).getAbsoluteFile().getParentFile())) { //check name equality String efname = new File(ef).getName(); if (new File(folder).getName().contains(efname.substring(0,efname.indexOf("*")))) { return true; } } } else { //plain folders equality check if (new File(folder).getAbsoluteFile().equals(new File(ef).getAbsoluteFile())) { return true; } } } //ignore others worlds folders (for mcpc+) for (World w : Bukkit.getWorlds()) { if (new File(folder).isDirectory() && new File(folder).getName().equals(w.getWorldFolder().getName())) { return true; } } return false; }
public static boolean isFolderExcluded(List<String> excludelist, String folder) { //ignore configured folders for (String ef : excludelist) { if (ef.contains("*") && ef.indexOf("*") == ef.length()-1) { //resolve wildcard //check parents folders equality if (new File(folder).getAbsoluteFile().getParentFile().equals(new File(ef).getAbsoluteFile().getParentFile())) { //check name equality String efname = new File(ef).getName(); if (new File(folder).getName().contains(efname.substring(0,efname.indexOf("*")))) { return true; } } } else { //plain folders equality check if (new File(folder).getAbsoluteFile().equals(new File(ef).getAbsoluteFile())) { return true; } } } //ignore others worlds folders (for mcpc+) for (World w : Bukkit.getWorlds()) { if (new File(folder).isDirectory() && new File(folder).getName().equals(w.getWorldFolder().getName())) { return true; } } return false; }
diff --git a/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/blocks/LeftCurlyCheck.java b/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/blocks/LeftCurlyCheck.java index 042ef717..82103a67 100644 --- a/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/blocks/LeftCurlyCheck.java +++ b/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/blocks/LeftCurlyCheck.java @@ -1,240 +1,240 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2005 Oliver Burn // // This library 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 2.1 of the License, or (at your option) any later version. // // This library 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 library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.blocks; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.api.Utils; import com.puppycrawl.tools.checkstyle.checks.AbstractOptionCheck; /** * <p> * Checks the placement of left curly braces on types, methods and * other blocks: * {@link TokenTypes#LITERAL_CATCH LITERAL_CATCH}, {@link * TokenTypes#LITERAL_DO LITERAL_DO}, {@link TokenTypes#LITERAL_ELSE * LITERAL_ELSE}, {@link TokenTypes#LITERAL_FINALLY LITERAL_FINALLY}, {@link * TokenTypes#LITERAL_FOR LITERAL_FOR}, {@link TokenTypes#LITERAL_IF * LITERAL_IF}, {@link TokenTypes#LITERAL_SWITCH LITERAL_SWITCH}, {@link * TokenTypes#LITERAL_SYNCHRONIZED LITERAL_SYNCHRONIZED}, {@link * TokenTypes#LITERAL_TRY LITERAL_TRY}, {@link TokenTypes#LITERAL_WHILE * LITERAL_WHILE}. * </p> * * <p> * The policy to verify is specified using the {@link LeftCurlyOption} class and * defaults to {@link LeftCurlyOption#EOL}. Policies {@link LeftCurlyOption#EOL} * and {@link LeftCurlyOption#NLOW} take into account property maxLineLength. * The default value for maxLineLength is 80. * </p> * <p> * An example of how to configure the check is: * </p> * <pre> * &lt;module name="LeftCurly"/&gt; * </pre> * <p> * An example of how to configure the check with policy * {@link LeftCurlyOption#NLOW} and maxLineLength 120 is: * </p> * <pre> * &lt;module name="LeftCurly"&gt; * &lt;property name="option" * value="nlow"/&gt; &lt;property name="maxLineLength" value="120"/&gt; &lt; * /module&gt; * </pre> * * @author Oliver Burn * @author lkuehne * @version 1.0 */ public class LeftCurlyCheck extends AbstractOptionCheck { /** default maximum line length */ private static final int DEFAULT_MAX_LINE_LENGTH = 80; /** TODO: replace this ugly hack **/ private int mMaxLineLength = DEFAULT_MAX_LINE_LENGTH; /** * Creates a default instance and sets the policy to EOL. */ public LeftCurlyCheck() { super(LeftCurlyOption.EOL); } /** * Sets the maximum line length used in calculating the placement of the * left curly brace. * @param aMaxLineLength the max allowed line length */ public void setMaxLineLength(int aMaxLineLength) { mMaxLineLength = aMaxLineLength; } /** @see com.puppycrawl.tools.checkstyle.api.Check */ public int[] getDefaultTokens() { return new int[] { TokenTypes.INTERFACE_DEF, TokenTypes.CLASS_DEF, TokenTypes.ANNOTATION_DEF, TokenTypes.ENUM_DEF, TokenTypes.CTOR_DEF, TokenTypes.METHOD_DEF, TokenTypes.ENUM_CONSTANT_DEF, TokenTypes.LITERAL_WHILE, TokenTypes.LITERAL_TRY, TokenTypes.LITERAL_CATCH, TokenTypes.LITERAL_FINALLY, TokenTypes.LITERAL_SYNCHRONIZED, TokenTypes.LITERAL_SWITCH, TokenTypes.LITERAL_DO, TokenTypes.LITERAL_IF, TokenTypes.LITERAL_ELSE, TokenTypes.LITERAL_FOR, // TODO: need to handle.... //TokenTypes.STATIC_INIT, }; } /** @see com.puppycrawl.tools.checkstyle.api.Check */ public void visitToken(DetailAST aAST) { final DetailAST startToken; final DetailAST brace; switch (aAST.getType()) { case TokenTypes.CTOR_DEF : case TokenTypes.METHOD_DEF : startToken = aAST; brace = aAST.findFirstToken(TokenTypes.SLIST); break; case TokenTypes.INTERFACE_DEF : case TokenTypes.CLASS_DEF : case TokenTypes.ANNOTATION_DEF : case TokenTypes.ENUM_DEF : case TokenTypes.ENUM_CONSTANT_DEF : startToken = (DetailAST) aAST.getFirstChild(); final DetailAST objBlock = aAST.findFirstToken(TokenTypes.OBJBLOCK); brace = (objBlock == null) - ? null + ? null : (DetailAST) objBlock.getFirstChild(); break; case TokenTypes.LITERAL_WHILE: case TokenTypes.LITERAL_CATCH: case TokenTypes.LITERAL_SYNCHRONIZED: case TokenTypes.LITERAL_FOR: case TokenTypes.LITERAL_TRY: case TokenTypes.LITERAL_FINALLY: case TokenTypes.LITERAL_DO: case TokenTypes.LITERAL_IF : startToken = aAST; brace = aAST.findFirstToken(TokenTypes.SLIST); break; case TokenTypes.LITERAL_ELSE : startToken = aAST; final DetailAST candidate = (DetailAST) aAST.getFirstChild(); brace = (candidate.getType() == TokenTypes.SLIST) ? candidate : null; // silently ignore break; case TokenTypes.LITERAL_SWITCH : startToken = aAST; brace = aAST.findFirstToken(TokenTypes.LCURLY); break; default : startToken = null; brace = null; } if ((brace != null) && (startToken != null)) { verifyBrace(brace, startToken); } } /** * Verifies that a specified left curly brace is placed correctly * according to policy. * @param aBrace token for left curly brace * @param aStartToken token for start of expression */ private void verifyBrace(final DetailAST aBrace, final DetailAST aStartToken) { final String braceLine = getLines()[aBrace.getLineNo() - 1]; // calculate the previous line length without trailing whitespace. Need // to handle the case where there is no previous line, cause the line // being check is the first line in the file. final int prevLineLen = (aBrace.getLineNo() == 1) ? mMaxLineLength : Utils.lengthMinusTrailingWhitespace( getLines()[aBrace.getLineNo() - 2]); // Check for being told to ignore, or have '{}' which is a special case if ((braceLine.length() > (aBrace.getColumnNo() + 1)) && (braceLine.charAt(aBrace.getColumnNo() + 1) == '}')) { ; // ignore } else if (getAbstractOption() == LeftCurlyOption.NL) { if (!Utils.whitespaceBefore(aBrace.getColumnNo(), braceLine)) { log(aBrace.getLineNo(), aBrace.getColumnNo(), "line.new", "{"); } } else if (getAbstractOption() == LeftCurlyOption.EOL) { if (Utils.whitespaceBefore(aBrace.getColumnNo(), braceLine) && ((prevLineLen + 2) <= mMaxLineLength)) { log(aBrace.getLineNo(), aBrace.getColumnNo(), "line.previous", "{"); } } else if (getAbstractOption() == LeftCurlyOption.NLOW) { if (aStartToken.getLineNo() == aBrace.getLineNo()) { ; // all ok as on the same line } else if ((aStartToken.getLineNo() + 1) == aBrace.getLineNo()) { if (!Utils.whitespaceBefore(aBrace.getColumnNo(), braceLine)) { log(aBrace.getLineNo(), aBrace.getColumnNo(), "line.new", "{"); } else if ((prevLineLen + 2) <= mMaxLineLength) { log(aBrace.getLineNo(), aBrace.getColumnNo(), "line.previous", "{"); } } else if (!Utils.whitespaceBefore(aBrace.getColumnNo(), braceLine)) { log(aBrace.getLineNo(), aBrace.getColumnNo(), "line.new", "{"); } } } }
true
true
public void visitToken(DetailAST aAST) { final DetailAST startToken; final DetailAST brace; switch (aAST.getType()) { case TokenTypes.CTOR_DEF : case TokenTypes.METHOD_DEF : startToken = aAST; brace = aAST.findFirstToken(TokenTypes.SLIST); break; case TokenTypes.INTERFACE_DEF : case TokenTypes.CLASS_DEF : case TokenTypes.ANNOTATION_DEF : case TokenTypes.ENUM_DEF : case TokenTypes.ENUM_CONSTANT_DEF : startToken = (DetailAST) aAST.getFirstChild(); final DetailAST objBlock = aAST.findFirstToken(TokenTypes.OBJBLOCK); brace = (objBlock == null) ? null : (DetailAST) objBlock.getFirstChild(); break; case TokenTypes.LITERAL_WHILE: case TokenTypes.LITERAL_CATCH: case TokenTypes.LITERAL_SYNCHRONIZED: case TokenTypes.LITERAL_FOR: case TokenTypes.LITERAL_TRY: case TokenTypes.LITERAL_FINALLY: case TokenTypes.LITERAL_DO: case TokenTypes.LITERAL_IF : startToken = aAST; brace = aAST.findFirstToken(TokenTypes.SLIST); break; case TokenTypes.LITERAL_ELSE : startToken = aAST; final DetailAST candidate = (DetailAST) aAST.getFirstChild(); brace = (candidate.getType() == TokenTypes.SLIST) ? candidate : null; // silently ignore break; case TokenTypes.LITERAL_SWITCH : startToken = aAST; brace = aAST.findFirstToken(TokenTypes.LCURLY); break; default : startToken = null; brace = null; } if ((brace != null) && (startToken != null)) { verifyBrace(brace, startToken); } }
public void visitToken(DetailAST aAST) { final DetailAST startToken; final DetailAST brace; switch (aAST.getType()) { case TokenTypes.CTOR_DEF : case TokenTypes.METHOD_DEF : startToken = aAST; brace = aAST.findFirstToken(TokenTypes.SLIST); break; case TokenTypes.INTERFACE_DEF : case TokenTypes.CLASS_DEF : case TokenTypes.ANNOTATION_DEF : case TokenTypes.ENUM_DEF : case TokenTypes.ENUM_CONSTANT_DEF : startToken = (DetailAST) aAST.getFirstChild(); final DetailAST objBlock = aAST.findFirstToken(TokenTypes.OBJBLOCK); brace = (objBlock == null) ? null : (DetailAST) objBlock.getFirstChild(); break; case TokenTypes.LITERAL_WHILE: case TokenTypes.LITERAL_CATCH: case TokenTypes.LITERAL_SYNCHRONIZED: case TokenTypes.LITERAL_FOR: case TokenTypes.LITERAL_TRY: case TokenTypes.LITERAL_FINALLY: case TokenTypes.LITERAL_DO: case TokenTypes.LITERAL_IF : startToken = aAST; brace = aAST.findFirstToken(TokenTypes.SLIST); break; case TokenTypes.LITERAL_ELSE : startToken = aAST; final DetailAST candidate = (DetailAST) aAST.getFirstChild(); brace = (candidate.getType() == TokenTypes.SLIST) ? candidate : null; // silently ignore break; case TokenTypes.LITERAL_SWITCH : startToken = aAST; brace = aAST.findFirstToken(TokenTypes.LCURLY); break; default : startToken = null; brace = null; } if ((brace != null) && (startToken != null)) { verifyBrace(brace, startToken); } }
diff --git a/src/com/android/camera/Camera.java b/src/com/android/camera/Camera.java index c60ba9ba..0bbaf48f 100644 --- a/src/com/android/camera/Camera.java +++ b/src/com/android/camera/Camera.java @@ -1,2390 +1,2385 @@ /* * Copyright (C) 2007 The Android Open Source 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. */ package com.android.camera; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.ContentProviderClient; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences.Editor; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.SurfaceTexture; import android.hardware.Camera.CameraInfo; import android.hardware.Camera.Face; import android.hardware.Camera.FaceDetectionListener; import android.hardware.Camera.Parameters; import android.hardware.Camera.PictureCallback; import android.hardware.Camera.Size; import android.location.Location; import android.media.CameraProfile; import android.media.MediaActionSound; import android.net.Uri; import android.os.Bundle; import android.os.ConditionVariable; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.os.MessageQueue; import android.os.SystemClock; import android.provider.MediaStore; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.OrientationEventListener; import android.view.View; import android.view.WindowManager; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.android.camera.ui.CameraPicker; import com.android.camera.ui.FaceView; import com.android.camera.ui.IndicatorControlContainer; import com.android.camera.ui.PopupManager; import com.android.camera.ui.Rotatable; import com.android.camera.ui.RotateImageView; import com.android.camera.ui.RotateLayout; import com.android.camera.ui.RotateTextToast; import com.android.camera.ui.TwoStateImageView; import com.android.camera.ui.ZoomControl; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collections; import java.util.Formatter; import java.util.List; /** The Camera activity which can preview and take pictures. */ public class Camera extends ActivityBase implements FocusManager.Listener, ModePicker.OnModeChangeListener, FaceDetectionListener, CameraPreference.OnPreferenceChangedListener, LocationManager.Listener, PreviewFrameLayout.OnSizeChangedListener, ShutterButton.OnShutterButtonListener { private static final String TAG = "camera"; // We number the request code from 1000 to avoid collision with Gallery. private static final int REQUEST_CROP = 1000; private static final int FIRST_TIME_INIT = 2; private static final int CLEAR_SCREEN_DELAY = 3; private static final int SET_CAMERA_PARAMETERS_WHEN_IDLE = 4; private static final int CHECK_DISPLAY_ROTATION = 5; private static final int SHOW_TAP_TO_FOCUS_TOAST = 6; private static final int UPDATE_THUMBNAIL = 7; private static final int SWITCH_CAMERA = 8; private static final int CAMERA_OPEN_DONE = 9; private static final int START_PREVIEW_DONE = 10; private static final int OPEN_CAMERA_FAIL = 11; private static final int CAMERA_DISABLED = 12; // The subset of parameters we need to update in setCameraParameters(). private static final int UPDATE_PARAM_INITIALIZE = 1; private static final int UPDATE_PARAM_ZOOM = 2; private static final int UPDATE_PARAM_PREFERENCE = 4; private static final int UPDATE_PARAM_ALL = -1; // When setCameraParametersWhenIdle() is called, we accumulate the subsets // needed to be updated in mUpdateSet. private int mUpdateSet; private static final int SCREEN_DELAY = 2 * 60 * 1000; private int mZoomValue; // The current zoom value. private int mZoomMax; private ZoomControl mZoomControl; private Parameters mInitialParams; private boolean mFocusAreaSupported; private boolean mMeteringAreaSupported; private boolean mAeLockSupported; private boolean mAwbLockSupported; private boolean mContinousFocusSupported; private MyOrientationEventListener mOrientationListener; // The degrees of the device rotated clockwise from its natural orientation. private int mOrientation = OrientationEventListener.ORIENTATION_UNKNOWN; // The orientation compensation for icons and thumbnails. Ex: if the value // is 90, the UI components should be rotated 90 degrees counter-clockwise. private int mOrientationCompensation = 0; private ComboPreferences mPreferences; private static final String sTempCropFilename = "crop-temp"; private ContentProviderClient mMediaProviderClient; private ShutterButton mShutterButton; private boolean mFaceDetectionStarted = false; private PreviewFrameLayout mPreviewFrameLayout; private SurfaceTexture mSurfaceTexture; private RotateDialogController mRotateDialog; private ModePicker mModePicker; private FaceView mFaceView; private RotateLayout mFocusAreaIndicator; private Rotatable mReviewCancelButton; private Rotatable mReviewDoneButton; private View mReviewRetakeButton; // mCropValue and mSaveUri are used only if isImageCaptureIntent() is true. private String mCropValue; private Uri mSaveUri; // Small indicators which show the camera settings in the viewfinder. private TextView mExposureIndicator; private ImageView mGpsIndicator; private ImageView mFlashIndicator; private ImageView mSceneIndicator; private ImageView mWhiteBalanceIndicator; private ImageView mFocusIndicator; // A view group that contains all the small indicators. private Rotatable mOnScreenIndicators; // We use a thread in ImageSaver to do the work of saving images and // generating thumbnails. This reduces the shot-to-shot time. private ImageSaver mImageSaver; // Similarly, we use a thread to generate the name of the picture and insert // it into MediaStore while picture taking is still in progress. private ImageNamer mImageNamer; private MediaActionSound mCameraSound; private Runnable mDoSnapRunnable = new Runnable() { @Override public void run() { onShutterButtonClick(); } }; private final StringBuilder mBuilder = new StringBuilder(); private final Formatter mFormatter = new Formatter(mBuilder); private final Object[] mFormatterArgs = new Object[1]; /** * An unpublished intent flag requesting to return as soon as capturing * is completed. * * TODO: consider publishing by moving into MediaStore. */ private static final String EXTRA_QUICK_CAPTURE = "android.intent.extra.quickCapture"; // The display rotation in degrees. This is only valid when mCameraState is // not PREVIEW_STOPPED. private int mDisplayRotation; // The value for android.hardware.Camera.setDisplayOrientation. private int mCameraDisplayOrientation; // The value for UI components like indicators. private int mDisplayOrientation; // The value for android.hardware.Camera.Parameters.setRotation. private int mJpegRotation; private boolean mFirstTimeInitialized; private boolean mIsImageCaptureIntent; private static final int PREVIEW_STOPPED = 0; private static final int IDLE = 1; // preview is active // Focus is in progress. The exact focus state is in Focus.java. private static final int FOCUSING = 2; private static final int SNAPSHOT_IN_PROGRESS = 3; // Switching between cameras. private static final int SWITCHING_CAMERA = 4; private int mCameraState = PREVIEW_STOPPED; private boolean mSnapshotOnIdle = false; private ContentResolver mContentResolver; private boolean mDidRegister = false; private LocationManager mLocationManager; private final ShutterCallback mShutterCallback = new ShutterCallback(); private final PostViewPictureCallback mPostViewPictureCallback = new PostViewPictureCallback(); private final RawPictureCallback mRawPictureCallback = new RawPictureCallback(); private final AutoFocusCallback mAutoFocusCallback = new AutoFocusCallback(); private final AutoFocusMoveCallback mAutoFocusMoveCallback = new AutoFocusMoveCallback(); private final CameraErrorCallback mErrorCallback = new CameraErrorCallback(); private long mFocusStartTime; private long mShutterCallbackTime; private long mPostViewPictureCallbackTime; private long mRawPictureCallbackTime; private long mJpegPictureCallbackTime; private long mOnResumeTime; private long mStorageSpace; private byte[] mJpegImageData; // These latency time are for the CameraLatency test. public long mAutoFocusTime; public long mShutterLag; public long mShutterToPictureDisplayedTime; public long mPictureDisplayedToJpegCallbackTime; public long mJpegCallbackFinishTime; public long mCaptureStartTime; // This handles everything about focus. private FocusManager mFocusManager; private String mSceneMode; private Toast mNotSelectableToast; private final Handler mHandler = new MainHandler(); private IndicatorControlContainer mIndicatorControlContainer; private PreferenceGroup mPreferenceGroup; private boolean mQuickCapture; CameraStartUpThread mCameraStartUpThread; ConditionVariable mStartPreviewPrerequisiteReady = new ConditionVariable(); // The purpose is not to block the main thread in onCreate and onResume. private class CameraStartUpThread extends Thread { private volatile boolean mCancelled; public void cancel() { mCancelled = true; } @Override public void run() { try { // We need to check whether the activity is paused before long // operations to ensure that onPause() can be done ASAP. if (mCancelled) return; mCameraDevice = Util.openCamera(Camera.this, mCameraId); mParameters = mCameraDevice.getParameters(); // Wait until all the initialization needed by startPreview are // done. mStartPreviewPrerequisiteReady.block(); initializeCapabilities(); if (mFocusManager == null) initializeFocusManager(); if (mCancelled) return; setCameraParameters(UPDATE_PARAM_ALL); mHandler.sendEmptyMessage(CAMERA_OPEN_DONE); if (mCancelled) return; startPreview(); mHandler.sendEmptyMessage(START_PREVIEW_DONE); mOnResumeTime = SystemClock.uptimeMillis(); mHandler.sendEmptyMessage(CHECK_DISPLAY_ROTATION); } catch (CameraHardwareException e) { mHandler.sendEmptyMessage(OPEN_CAMERA_FAIL); } catch (CameraDisabledException e) { mHandler.sendEmptyMessage(CAMERA_DISABLED); } } } /** * This Handler is used to post message back onto the main thread of the * application */ private class MainHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { case CLEAR_SCREEN_DELAY: { getWindow().clearFlags( WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); break; } case FIRST_TIME_INIT: { initializeFirstTime(); break; } case SET_CAMERA_PARAMETERS_WHEN_IDLE: { setCameraParametersWhenIdle(0); break; } case CHECK_DISPLAY_ROTATION: { // Set the display orientation if display rotation has changed. // Sometimes this happens when the device is held upside // down and camera app is opened. Rotation animation will // take some time and the rotation value we have got may be // wrong. Framework does not have a callback for this now. if (Util.getDisplayRotation(Camera.this) != mDisplayRotation) { setDisplayOrientation(); } if (SystemClock.uptimeMillis() - mOnResumeTime < 5000) { mHandler.sendEmptyMessageDelayed(CHECK_DISPLAY_ROTATION, 100); } break; } case SHOW_TAP_TO_FOCUS_TOAST: { showTapToFocusToast(); break; } case UPDATE_THUMBNAIL: { mImageSaver.updateThumbnail(); break; } case SWITCH_CAMERA: { switchCamera(); break; } case CAMERA_OPEN_DONE: { initializeAfterCameraOpen(); break; } case START_PREVIEW_DONE: { mCameraStartUpThread = null; setCameraState(IDLE); break; } case OPEN_CAMERA_FAIL: { mCameraStartUpThread = null; mOpenCameraFail = true; Util.showErrorAndFinish(Camera.this, R.string.cannot_connect_camera); break; } case CAMERA_DISABLED: { mCameraStartUpThread = null; mCameraDisabled = true; Util.showErrorAndFinish(Camera.this, R.string.camera_disabled); break; } } } } private void initializeAfterCameraOpen() { // These depend on camera parameters. setPreviewFrameLayoutAspectRatio(); mFocusManager.setPreviewSize(mPreviewFrameLayout.getWidth(), mPreviewFrameLayout.getHeight()); if (mIndicatorControlContainer == null) { initializeIndicatorControl(); } // This should be enabled after preview is started. mIndicatorControlContainer.setEnabled(false); initializeZoom(); updateOnScreenIndicators(); startFaceDetection(); showTapToFocusToastIfNeeded(); } private void resetExposureCompensation() { String value = mPreferences.getString(CameraSettings.KEY_EXPOSURE, CameraSettings.EXPOSURE_DEFAULT_VALUE); if (!CameraSettings.EXPOSURE_DEFAULT_VALUE.equals(value)) { Editor editor = mPreferences.edit(); editor.putString(CameraSettings.KEY_EXPOSURE, "0"); editor.apply(); } } private void keepMediaProviderInstance() { // We want to keep a reference to MediaProvider in camera's lifecycle. // TODO: Utilize mMediaProviderClient instance to replace // ContentResolver calls. if (mMediaProviderClient == null) { mMediaProviderClient = mContentResolver .acquireContentProviderClient(MediaStore.AUTHORITY); } } // Snapshots can only be taken after this is called. It should be called // once only. We could have done these things in onCreate() but we want to // make preview screen appear as soon as possible. private void initializeFirstTime() { if (mFirstTimeInitialized) return; // Create orientation listener. This should be done first because it // takes some time to get first orientation. mOrientationListener = new MyOrientationEventListener(Camera.this); mOrientationListener.enable(); // Initialize location service. boolean recordLocation = RecordLocationPreference.get( mPreferences, mContentResolver); mLocationManager.recordLocation(recordLocation); keepMediaProviderInstance(); checkStorage(); // Initialize shutter button. mShutterButton = (ShutterButton) findViewById(R.id.shutter_button); mShutterButton.setOnShutterButtonListener(this); mShutterButton.setVisibility(View.VISIBLE); mImageSaver = new ImageSaver(); mImageNamer = new ImageNamer(); installIntentFilter(); mFirstTimeInitialized = true; addIdleHandler(); } private void showTapToFocusToastIfNeeded() { // Show the tap to focus toast if this is the first start. if (mFocusAreaSupported && mPreferences.getBoolean(CameraSettings.KEY_CAMERA_FIRST_USE_HINT_SHOWN, true)) { // Delay the toast for one second to wait for orientation. mHandler.sendEmptyMessageDelayed(SHOW_TAP_TO_FOCUS_TOAST, 1000); } } private void addIdleHandler() { MessageQueue queue = Looper.myQueue(); queue.addIdleHandler(new MessageQueue.IdleHandler() { @Override public boolean queueIdle() { Storage.ensureOSXCompatible(); return false; } }); } // If the activity is paused and resumed, this method will be called in // onResume. private void initializeSecondTime() { // Start orientation listener as soon as possible because it takes // some time to get first orientation. mOrientationListener.enable(); // Start location update if needed. boolean recordLocation = RecordLocationPreference.get( mPreferences, mContentResolver); mLocationManager.recordLocation(recordLocation); installIntentFilter(); mImageSaver = new ImageSaver(); mImageNamer = new ImageNamer(); initializeZoom(); keepMediaProviderInstance(); checkStorage(); hidePostCaptureAlert(); if (!mIsImageCaptureIntent) { mModePicker.setCurrentMode(ModePicker.MODE_CAMERA); } if (mIndicatorControlContainer != null) { mIndicatorControlContainer.reloadPreferences(); } } private class ZoomChangeListener implements ZoomControl.OnZoomChangedListener { @Override public void onZoomValueChanged(int index) { // Not useful to change zoom value when the activity is paused. if (mPaused) return; mZoomValue = index; // Set zoom parameters asynchronously mParameters.setZoom(mZoomValue); mCameraDevice.setParametersAsync(mParameters); } } private void initializeZoom() { if (!mParameters.isZoomSupported()) return; mZoomMax = mParameters.getMaxZoom(); // Currently we use immediate zoom for fast zooming to get better UX and // there is no plan to take advantage of the smooth zoom. mZoomControl.setZoomMax(mZoomMax); mZoomControl.setZoomIndex(mParameters.getZoom()); mZoomControl.setOnZoomChangeListener(new ZoomChangeListener()); } @Override public void startFaceDetection() { if (mFaceDetectionStarted || mCameraState != IDLE) return; if (mParameters.getMaxNumDetectedFaces() > 0) { mFaceDetectionStarted = true; mFaceView.clear(); mFaceView.setVisibility(View.VISIBLE); mFaceView.setDisplayOrientation(mDisplayOrientation); CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId]; mFaceView.setMirror(info.facing == CameraInfo.CAMERA_FACING_FRONT); mFaceView.resume(); mFocusManager.setFaceView(mFaceView); mCameraDevice.setFaceDetectionListener(this); mCameraDevice.startFaceDetection(); } } @Override public void stopFaceDetection() { if (!mFaceDetectionStarted) return; if (mParameters.getMaxNumDetectedFaces() > 0) { mFaceDetectionStarted = false; mCameraDevice.setFaceDetectionListener(null); mCameraDevice.stopFaceDetection(); if (mFaceView != null) mFaceView.clear(); } } @Override public boolean dispatchTouchEvent(MotionEvent m) { if (mCameraState == SWITCHING_CAMERA) return true; // Check if the popup window should be dismissed first. if (m.getAction() == MotionEvent.ACTION_DOWN) { float x = m.getX(); float y = m.getY(); // Dismiss the mode selection window if the ACTION_DOWN event is out // of its view area. if ((mModePicker != null) && !Util.pointInView(x, y, mModePicker)) { mModePicker.dismissModeSelection(); } // Check if the popup window is visible. Indicator control can be // null if camera is not opened yet. if (mIndicatorControlContainer != null) { View popup = mIndicatorControlContainer.getActiveSettingPopup(); if (popup != null) { // Let popup window, indicator control or preview frame // handle the event by themselves. Dismiss the popup window // if users touch on other areas. if (!Util.pointInView(x, y, popup) && !Util.pointInView(x, y, mIndicatorControlContainer) && !Util.pointInView(x, y, mPreviewFrameLayout)) { mIndicatorControlContainer.dismissSettingPopup(); } } } } return super.dispatchTouchEvent(m); } private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Log.d(TAG, "Received intent action=" + action); if (action.equals(Intent.ACTION_MEDIA_MOUNTED) || action.equals(Intent.ACTION_MEDIA_UNMOUNTED) || action.equals(Intent.ACTION_MEDIA_CHECKING)) { checkStorage(); } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) { checkStorage(); if (!mIsImageCaptureIntent) { getLastThumbnail(); } } } }; private void initOnScreenIndicator() { mGpsIndicator = (ImageView) findViewById(R.id.onscreen_gps_indicator); mExposureIndicator = (TextView) findViewById(R.id.onscreen_exposure_indicator); mFlashIndicator = (ImageView) findViewById(R.id.onscreen_flash_indicator); mSceneIndicator = (ImageView) findViewById(R.id.onscreen_scene_indicator); mWhiteBalanceIndicator = (ImageView) findViewById(R.id.onscreen_white_balance_indicator); mFocusIndicator = (ImageView) findViewById(R.id.onscreen_focus_indicator); } @Override public void showGpsOnScreenIndicator(boolean hasSignal) { if (mGpsIndicator == null) { return; } if (hasSignal) { mGpsIndicator.setImageResource(R.drawable.ic_viewfinder_gps_on); } else { mGpsIndicator.setImageResource(R.drawable.ic_viewfinder_gps_no_signal); } mGpsIndicator.setVisibility(View.VISIBLE); } @Override public void hideGpsOnScreenIndicator() { if (mGpsIndicator == null) { return; } mGpsIndicator.setVisibility(View.GONE); } private void updateExposureOnScreenIndicator(int value) { if (mExposureIndicator == null) { return; } if (value == 0) { mExposureIndicator.setText(""); mExposureIndicator.setVisibility(View.GONE); } else { float step = mParameters.getExposureCompensationStep(); mFormatterArgs[0] = value * step; mBuilder.delete(0, mBuilder.length()); mFormatter.format("%+1.1f", mFormatterArgs); String exposure = mFormatter.toString(); mExposureIndicator.setText(exposure); mExposureIndicator.setVisibility(View.VISIBLE); } } private void updateFlashOnScreenIndicator(String value) { if (mFlashIndicator == null) { return; } if (value == null || Parameters.FLASH_MODE_OFF.equals(value)) { mFlashIndicator.setVisibility(View.GONE); } else { mFlashIndicator.setVisibility(View.VISIBLE); if (Parameters.FLASH_MODE_AUTO.equals(value)) { mFlashIndicator.setImageResource(R.drawable.ic_indicators_landscape_flash_auto); } else if (Parameters.FLASH_MODE_ON.equals(value)) { mFlashIndicator.setImageResource(R.drawable.ic_indicators_landscape_flash_on); } else { // Should not happen. mFlashIndicator.setVisibility(View.GONE); } } } private void updateSceneOnScreenIndicator(String value) { if (mSceneIndicator == null) { return; } boolean isGone = (value == null) || (Parameters.SCENE_MODE_AUTO.equals(value)); mSceneIndicator.setVisibility(isGone ? View.GONE : View.VISIBLE); } private void updateWhiteBalanceOnScreenIndicator(String value) { if (mWhiteBalanceIndicator == null) { return; } if (value == null || Parameters.WHITE_BALANCE_AUTO.equals(value)) { mWhiteBalanceIndicator.setVisibility(View.GONE); } else { mWhiteBalanceIndicator.setVisibility(View.VISIBLE); if (Parameters.WHITE_BALANCE_FLUORESCENT.equals(value)) { mWhiteBalanceIndicator.setImageResource(R.drawable.ic_indicators_fluorescent); } else if (Parameters.WHITE_BALANCE_INCANDESCENT.equals(value)) { mWhiteBalanceIndicator.setImageResource(R.drawable.ic_indicators_incandescent); } else if (Parameters.WHITE_BALANCE_DAYLIGHT.equals(value)) { mWhiteBalanceIndicator.setImageResource(R.drawable.ic_indicators_sunlight); } else if (Parameters.WHITE_BALANCE_CLOUDY_DAYLIGHT.equals(value)) { mWhiteBalanceIndicator.setImageResource(R.drawable.ic_indicators_cloudy); } else { // Should not happen. mWhiteBalanceIndicator.setVisibility(View.GONE); } } } private void updateFocusOnScreenIndicator(String value) { if (mFocusIndicator == null) { return; } // Do not show the indicator if users cannot choose. if (mPreferenceGroup.findPreference(CameraSettings.KEY_FOCUS_MODE) == null) { mFocusIndicator.setVisibility(View.GONE); } else { mFocusIndicator.setVisibility(View.VISIBLE); if (Parameters.FOCUS_MODE_INFINITY.equals(value)) { mFocusIndicator.setImageResource(R.drawable.ic_indicators_landscape); } else if (Parameters.FOCUS_MODE_MACRO.equals(value)) { mFocusIndicator.setImageResource(R.drawable.ic_indicators_macro); } else { // Should not happen. mFocusIndicator.setVisibility(View.GONE); } } } private void updateOnScreenIndicators() { updateSceneOnScreenIndicator(mParameters.getSceneMode()); updateExposureOnScreenIndicator(CameraSettings.readExposure(mPreferences)); updateFlashOnScreenIndicator(mParameters.getFlashMode()); updateWhiteBalanceOnScreenIndicator(mParameters.getWhiteBalance()); updateFocusOnScreenIndicator(mParameters.getFocusMode()); } private final class ShutterCallback implements android.hardware.Camera.ShutterCallback { @Override public void onShutter() { mShutterCallbackTime = System.currentTimeMillis(); mShutterLag = mShutterCallbackTime - mCaptureStartTime; Log.v(TAG, "mShutterLag = " + mShutterLag + "ms"); } } private final class PostViewPictureCallback implements PictureCallback { @Override public void onPictureTaken( byte [] data, android.hardware.Camera camera) { mPostViewPictureCallbackTime = System.currentTimeMillis(); Log.v(TAG, "mShutterToPostViewCallbackTime = " + (mPostViewPictureCallbackTime - mShutterCallbackTime) + "ms"); } } private final class RawPictureCallback implements PictureCallback { @Override public void onPictureTaken( byte [] rawData, android.hardware.Camera camera) { mRawPictureCallbackTime = System.currentTimeMillis(); Log.v(TAG, "mShutterToRawCallbackTime = " + (mRawPictureCallbackTime - mShutterCallbackTime) + "ms"); } } private final class JpegPictureCallback implements PictureCallback { Location mLocation; public JpegPictureCallback(Location loc) { mLocation = loc; } @Override public void onPictureTaken( final byte [] jpegData, final android.hardware.Camera camera) { if (mPaused) { return; } mJpegPictureCallbackTime = System.currentTimeMillis(); // If postview callback has arrived, the captured image is displayed // in postview callback. If not, the captured image is displayed in // raw picture callback. if (mPostViewPictureCallbackTime != 0) { mShutterToPictureDisplayedTime = mPostViewPictureCallbackTime - mShutterCallbackTime; mPictureDisplayedToJpegCallbackTime = mJpegPictureCallbackTime - mPostViewPictureCallbackTime; } else { mShutterToPictureDisplayedTime = mRawPictureCallbackTime - mShutterCallbackTime; mPictureDisplayedToJpegCallbackTime = mJpegPictureCallbackTime - mRawPictureCallbackTime; } Log.v(TAG, "mPictureDisplayedToJpegCallbackTime = " + mPictureDisplayedToJpegCallbackTime + "ms"); if (!mIsImageCaptureIntent) { startPreview(); setCameraState(IDLE); startFaceDetection(); } if (!mIsImageCaptureIntent) { // Calculate the width and the height of the jpeg. Size s = mParameters.getPictureSize(); int orientation = Exif.getOrientation(jpegData); int width, height; if ((mJpegRotation + orientation) % 180 == 0) { width = s.width; height = s.height; } else { width = s.height; height = s.width; } Uri uri = mImageNamer.getUri(); String title = mImageNamer.getTitle(); mImageSaver.addImage(jpegData, uri, title, mLocation, width, height, mThumbnailViewWidth, orientation); } else { mJpegImageData = jpegData; if (!mQuickCapture) { showPostCaptureAlert(); } else { doAttach(); } } // Check this in advance of each shot so we don't add to shutter // latency. It's true that someone else could write to the SD card in // the mean time and fill it, but that could have happened between the // shutter press and saving the JPEG too. checkStorage(); long now = System.currentTimeMillis(); mJpegCallbackFinishTime = now - mJpegPictureCallbackTime; Log.v(TAG, "mJpegCallbackFinishTime = " + mJpegCallbackFinishTime + "ms"); mJpegPictureCallbackTime = 0; } } private final class AutoFocusCallback implements android.hardware.Camera.AutoFocusCallback { @Override public void onAutoFocus( boolean focused, android.hardware.Camera camera) { if (mPaused) return; mAutoFocusTime = System.currentTimeMillis() - mFocusStartTime; Log.v(TAG, "mAutoFocusTime = " + mAutoFocusTime + "ms"); setCameraState(IDLE); mFocusManager.onAutoFocus(focused); } } private final class AutoFocusMoveCallback implements android.hardware.Camera.AutoFocusMoveCallback { @Override public void onAutoFocusMoving( boolean moving, android.hardware.Camera camera) { mFocusManager.onAutoFocusMoving(moving); } } // Each SaveRequest remembers the data needed to save an image. private static class SaveRequest { byte[] data; Uri uri; String title; Location loc; int width, height; int thumbnailWidth; int orientation; } // We use a queue to store the SaveRequests that have not been completed // yet. The main thread puts the request into the queue. The saver thread // gets it from the queue, does the work, and removes it from the queue. // // The main thread needs to wait for the saver thread to finish all the work // in the queue, when the activity's onPause() is called, we need to finish // all the work, so other programs (like Gallery) can see all the images. // // If the queue becomes too long, adding a new request will block the main // thread until the queue length drops below the threshold (QUEUE_LIMIT). // If we don't do this, we may face several problems: (1) We may OOM // because we are holding all the jpeg data in memory. (2) We may ANR // when we need to wait for saver thread finishing all the work (in // onPause() or gotoGallery()) because the time to finishing a long queue // of work may be too long. private class ImageSaver extends Thread { private static final int QUEUE_LIMIT = 3; private ArrayList<SaveRequest> mQueue; private Thumbnail mPendingThumbnail; private Object mUpdateThumbnailLock = new Object(); private boolean mStop; // Runs in main thread public ImageSaver() { mQueue = new ArrayList<SaveRequest>(); start(); } // Runs in main thread public void addImage(final byte[] data, Uri uri, String title, Location loc, int width, int height, int thumbnailWidth, int orientation) { SaveRequest r = new SaveRequest(); r.data = data; r.uri = uri; r.title = title; r.loc = (loc == null) ? null : new Location(loc); // make a copy r.width = width; r.height = height; r.thumbnailWidth = thumbnailWidth; r.orientation = orientation; synchronized (this) { while (mQueue.size() >= QUEUE_LIMIT) { try { wait(); } catch (InterruptedException ex) { // ignore. } } mQueue.add(r); notifyAll(); // Tell saver thread there is new work to do. } } // Runs in saver thread @Override public void run() { while (true) { SaveRequest r; synchronized (this) { if (mQueue.isEmpty()) { notifyAll(); // notify main thread in waitDone // Note that we can only stop after we saved all images // in the queue. if (mStop) break; try { wait(); } catch (InterruptedException ex) { // ignore. } continue; } r = mQueue.get(0); } storeImage(r.data, r.uri, r.title, r.loc, r.width, r.height, r.thumbnailWidth, r.orientation); synchronized (this) { mQueue.remove(0); notifyAll(); // the main thread may wait in addImage } } } // Runs in main thread public void waitDone() { synchronized (this) { while (!mQueue.isEmpty()) { try { wait(); } catch (InterruptedException ex) { // ignore. } } } updateThumbnail(); } // Runs in main thread public void finish() { waitDone(); synchronized (this) { mStop = true; notifyAll(); } try { join(); } catch (InterruptedException ex) { // ignore. } } // Runs in main thread (because we need to update mThumbnailView in the // main thread) public void updateThumbnail() { Thumbnail t; synchronized (mUpdateThumbnailLock) { mHandler.removeMessages(UPDATE_THUMBNAIL); t = mPendingThumbnail; mPendingThumbnail = null; } if (t != null) { mThumbnail = t; mThumbnailView.setBitmap(mThumbnail.getBitmap()); } } // Runs in saver thread private void storeImage(final byte[] data, Uri uri, String title, Location loc, int width, int height, int thumbnailWidth, int orientation) { boolean ok = Storage.updateImage(mContentResolver, uri, title, loc, orientation, data, width, height); if (ok) { boolean needThumbnail; synchronized (this) { // If the number of requests in the queue (include the // current one) is greater than 1, we don't need to generate // thumbnail for this image. Because we'll soon replace it // with the thumbnail for some image later in the queue. needThumbnail = (mQueue.size() <= 1); } if (needThumbnail) { // Create a thumbnail whose width is equal or bigger than // that of the thumbnail view. int ratio = (int) Math.ceil((double) width / thumbnailWidth); int inSampleSize = Integer.highestOneBit(ratio); Thumbnail t = Thumbnail.createThumbnail( data, orientation, inSampleSize, uri); synchronized (mUpdateThumbnailLock) { // We need to update the thumbnail in the main thread, // so send a message to run updateThumbnail(). mPendingThumbnail = t; mHandler.sendEmptyMessage(UPDATE_THUMBNAIL); } } Util.broadcastNewPicture(Camera.this, uri); } } } private static class ImageNamer extends Thread { private boolean mRequestPending; private ContentResolver mResolver; private long mDateTaken; private int mWidth, mHeight; private boolean mStop; private Uri mUri; private String mTitle; // Runs in main thread public ImageNamer() { start(); } // Runs in main thread public synchronized void prepareUri(ContentResolver resolver, long dateTaken, int width, int height, int rotation) { if (rotation % 180 != 0) { int tmp = width; width = height; height = tmp; } mRequestPending = true; mResolver = resolver; mDateTaken = dateTaken; mWidth = width; mHeight = height; notifyAll(); } // Runs in main thread public synchronized Uri getUri() { // wait until the request is done. while (mRequestPending) { try { wait(); } catch (InterruptedException ex) { // ignore. } } // return the uri generated Uri uri = mUri; mUri = null; return uri; } // Runs in main thread, should be called after getUri(). public synchronized String getTitle() { return mTitle; } // Runs in namer thread @Override public synchronized void run() { while (true) { if (mStop) break; if (!mRequestPending) { try { wait(); } catch (InterruptedException ex) { // ignore. } continue; } cleanOldUri(); generateUri(); mRequestPending = false; notifyAll(); } cleanOldUri(); } // Runs in main thread public synchronized void finish() { mStop = true; notifyAll(); } // Runs in namer thread private void generateUri() { mTitle = Util.createJpegName(mDateTaken); mUri = Storage.newImage(mResolver, mTitle, mDateTaken, mWidth, mHeight); } // Runs in namer thread private void cleanOldUri() { if (mUri == null) return; Storage.deleteImage(mResolver, mUri); mUri = null; } } private void setCameraState(int state) { mCameraState = state; switch (state) { case PREVIEW_STOPPED: case SNAPSHOT_IN_PROGRESS: case FOCUSING: case SWITCHING_CAMERA: enableCameraControls(false); break; case IDLE: enableCameraControls(true); break; } } @Override public boolean capture() { // If we are already in the middle of taking a snapshot then ignore. if (mCameraDevice == null || mCameraState == SNAPSHOT_IN_PROGRESS || mCameraState == SWITCHING_CAMERA) { return false; } mCaptureStartTime = System.currentTimeMillis(); mPostViewPictureCallbackTime = 0; mJpegImageData = null; // Set rotation and gps data. mJpegRotation = Util.getJpegRotation(mCameraId, mOrientation); mParameters.setRotation(mJpegRotation); Location loc = mLocationManager.getCurrentLocation(); Util.setGpsParameters(mParameters, loc); mCameraDevice.setParameters(mParameters); mCameraDevice.takePicture(mShutterCallback, mRawPictureCallback, mPostViewPictureCallback, new JpegPictureCallback(loc)); Size size = mParameters.getPictureSize(); mImageNamer.prepareUri(mContentResolver, mCaptureStartTime, size.width, size.height, mJpegRotation); if (!mIsImageCaptureIntent) { // Start capture animation. mCameraScreenNail.animateCapture(getCameraRotation()); } mFaceDetectionStarted = false; setCameraState(SNAPSHOT_IN_PROGRESS); return true; } private int getCameraRotation() { return (mOrientationCompensation - mDisplayRotation + 360) % 360; } @Override public void setFocusParameters() { setCameraParameters(UPDATE_PARAM_PREFERENCE); } @Override public void playSound(int soundId) { mCameraSound.play(soundId); } private int getPreferredCameraId(ComboPreferences preferences) { int intentCameraId = Util.getCameraFacingIntentExtras(this); if (intentCameraId != -1) { // Testing purpose. Launch a specific camera through the intent // extras. return intentCameraId; } else { return CameraSettings.readPreferredCameraId(preferences); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mPreferences = new ComboPreferences(this); CameraSettings.upgradeGlobalPreferences(mPreferences.getGlobal()); mCameraId = getPreferredCameraId(mPreferences); mContentResolver = getContentResolver(); // To reduce startup time, open the camera and start the preview in // another thread. mCameraStartUpThread = new CameraStartUpThread(); mCameraStartUpThread.start(); setContentView(R.layout.camera); // Surface texture is from camera screen nail and startPreview needs it. // This must be done before startPreview. mIsImageCaptureIntent = isImageCaptureIntent(); createCameraScreenNail(!mIsImageCaptureIntent); mPreferences.setLocalId(this, mCameraId); CameraSettings.upgradeLocalPreferences(mPreferences.getLocal()); mFocusAreaIndicator = (RotateLayout) findViewById( R.id.focus_indicator_rotate_layout); // we need to reset exposure for the preview resetExposureCompensation(); // Starting the preview needs preferences, camera screen nail, and // focus area indicator. mStartPreviewPrerequisiteReady.open(); initializeControlByIntent(); mRotateDialog = new RotateDialogController(this, R.layout.rotate_dialog); mNumberOfCameras = CameraHolder.instance().getNumberOfCameras(); mQuickCapture = getIntent().getBooleanExtra(EXTRA_QUICK_CAPTURE, false); initializeMiscControls(); mLocationManager = new LocationManager(this, this); initOnScreenIndicator(); // Make sure all views are disabled before camera is open. enableCameraControls(false); } private void overrideCameraSettings(final String flashMode, final String whiteBalance, final String focusMode) { if (mIndicatorControlContainer != null) { mIndicatorControlContainer.enableFilter(true); mIndicatorControlContainer.overrideSettings( CameraSettings.KEY_FLASH_MODE, flashMode, CameraSettings.KEY_WHITE_BALANCE, whiteBalance, CameraSettings.KEY_FOCUS_MODE, focusMode); mIndicatorControlContainer.enableFilter(false); } } private void updateSceneModeUI() { // If scene mode is set, we cannot set flash mode, white balance, and // focus mode, instead, we read it from driver if (!Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) { overrideCameraSettings(mParameters.getFlashMode(), mParameters.getWhiteBalance(), mParameters.getFocusMode()); } else { overrideCameraSettings(null, null, null); } } private void loadCameraPreferences() { CameraSettings settings = new CameraSettings(this, mInitialParams, mCameraId, CameraHolder.instance().getCameraInfo()); mPreferenceGroup = settings.getPreferenceGroup(R.xml.camera_preferences); } private void initializeIndicatorControl() { // setting the indicator buttons. mIndicatorControlContainer = (IndicatorControlContainer) findViewById(R.id.indicator_control); loadCameraPreferences(); final String[] SETTING_KEYS = { CameraSettings.KEY_FLASH_MODE, CameraSettings.KEY_WHITE_BALANCE, CameraSettings.KEY_EXPOSURE, CameraSettings.KEY_SCENE_MODE}; final String[] OTHER_SETTING_KEYS = { CameraSettings.KEY_RECORD_LOCATION, CameraSettings.KEY_PICTURE_SIZE, CameraSettings.KEY_FOCUS_MODE}; CameraPicker.setImageResourceId(R.drawable.ic_switch_photo_facing_holo_light); mIndicatorControlContainer.initialize(this, mPreferenceGroup, mParameters.isZoomSupported(), SETTING_KEYS, OTHER_SETTING_KEYS); mCameraPicker = (CameraPicker) mIndicatorControlContainer.findViewById( R.id.camera_picker); updateSceneModeUI(); mIndicatorControlContainer.setListener(this); } private boolean collapseCameraControls() { if ((mIndicatorControlContainer != null) && mIndicatorControlContainer.dismissSettingPopup()) { return true; } if (mModePicker != null && mModePicker.dismissModeSelection()) return true; return false; } private void enableCameraControls(boolean enable) { if (mIndicatorControlContainer != null) { mIndicatorControlContainer.setEnabled(enable); } if (mModePicker != null) mModePicker.setEnabled(enable); if (mZoomControl != null) mZoomControl.setEnabled(enable); if (mThumbnailView != null) mThumbnailView.setEnabled(enable); } private class MyOrientationEventListener extends OrientationEventListener { public MyOrientationEventListener(Context context) { super(context); } @Override public void onOrientationChanged(int orientation) { // We keep the last known orientation. So if the user first orient // the camera then point the camera to floor or sky, we still have // the correct orientation. if (orientation == ORIENTATION_UNKNOWN) return; mOrientation = Util.roundOrientation(orientation, mOrientation); // When the screen is unlocked, display rotation may change. Always // calculate the up-to-date orientationCompensation. int orientationCompensation = (mOrientation + Util.getDisplayRotation(Camera.this)) % 360; if (mOrientationCompensation != orientationCompensation) { mOrientationCompensation = orientationCompensation; setOrientationIndicator(mOrientationCompensation, true); } // Show the toast after getting the first orientation changed. if (mHandler.hasMessages(SHOW_TAP_TO_FOCUS_TOAST)) { mHandler.removeMessages(SHOW_TAP_TO_FOCUS_TOAST); showTapToFocusToast(); } } } private void setOrientationIndicator(int orientation, boolean animation) { Rotatable[] indicators = {mThumbnailView, mModePicker, mIndicatorControlContainer, mZoomControl, mFocusAreaIndicator, mFaceView, mReviewDoneButton, mRotateDialog, mOnScreenIndicators}; for (Rotatable indicator : indicators) { if (indicator != null) indicator.setOrientation(orientation, animation); } // We change the orientation of the review cancel button only for tablet // UI because there's a label along with the X icon. For phone UI, we // don't change the orientation because there's only a symmetrical X // icon. if (mReviewCancelButton instanceof RotateLayout) { mReviewCancelButton.setOrientation(orientation, animation); } } @Override public void onStop() { super.onStop(); if (mMediaProviderClient != null) { mMediaProviderClient.release(); mMediaProviderClient = null; } } private void checkStorage() { mStorageSpace = Storage.getAvailableSpace(); updateStorageHint(mStorageSpace); } @OnClickAttr public void onThumbnailClicked(View v) { if (isCameraIdle() && mThumbnail != null) { if (mImageSaver != null) mImageSaver.waitDone(); gotoGallery(); } } // onClick handler for R.id.btn_retake @OnClickAttr public void onReviewRetakeClicked(View v) { if (mPaused) return; hidePostCaptureAlert(); startPreview(); setCameraState(IDLE); startFaceDetection(); } // onClick handler for R.id.btn_done @OnClickAttr public void onReviewDoneClicked(View v) { doAttach(); } // onClick handler for R.id.btn_cancel @OnClickAttr public void onReviewCancelClicked(View v) { doCancel(); } private void doAttach() { if (mPaused) { return; } byte[] data = mJpegImageData; if (mCropValue == null) { // First handle the no crop case -- just return the value. If the // caller specifies a "save uri" then write the data to its // stream. Otherwise, pass back a scaled down version of the bitmap // directly in the extras. if (mSaveUri != null) { OutputStream outputStream = null; try { outputStream = mContentResolver.openOutputStream(mSaveUri); outputStream.write(data); outputStream.close(); setResultEx(RESULT_OK); finish(); } catch (IOException ex) { // ignore exception } finally { Util.closeSilently(outputStream); } } else { int orientation = Exif.getOrientation(data); Bitmap bitmap = Util.makeBitmap(data, 50 * 1024); bitmap = Util.rotate(bitmap, orientation); setResultEx(RESULT_OK, new Intent("inline-data").putExtra("data", bitmap)); finish(); } } else { // Save the image to a temp file and invoke the cropper Uri tempUri = null; FileOutputStream tempStream = null; try { File path = getFileStreamPath(sTempCropFilename); path.delete(); tempStream = openFileOutput(sTempCropFilename, 0); tempStream.write(data); tempStream.close(); tempUri = Uri.fromFile(path); } catch (FileNotFoundException ex) { setResultEx(Activity.RESULT_CANCELED); finish(); return; } catch (IOException ex) { setResultEx(Activity.RESULT_CANCELED); finish(); return; } finally { Util.closeSilently(tempStream); } Bundle newExtras = new Bundle(); if (mCropValue.equals("circle")) { newExtras.putString("circleCrop", "true"); } if (mSaveUri != null) { newExtras.putParcelable(MediaStore.EXTRA_OUTPUT, mSaveUri); } else { newExtras.putBoolean("return-data", true); } Intent cropIntent = new Intent("com.android.camera.action.CROP"); cropIntent.setData(tempUri); cropIntent.putExtras(newExtras); startActivityForResult(cropIntent, REQUEST_CROP); } } private void doCancel() { setResultEx(RESULT_CANCELED, new Intent()); finish(); } @Override public void onShutterButtonFocus(boolean pressed) { if (mPaused || collapseCameraControls() || (mCameraState == SNAPSHOT_IN_PROGRESS) || (mCameraState == PREVIEW_STOPPED)) return; // Do not do focus if there is not enough storage. if (pressed && !canTakePicture()) return; if (pressed) { mFocusManager.onShutterDown(); } else { mFocusManager.onShutterUp(); } } @Override public void onShutterButtonClick() { if (mPaused || collapseCameraControls() || (mCameraState == SWITCHING_CAMERA) || (mCameraState == PREVIEW_STOPPED)) return; // Do not take the picture if there is not enough storage. if (mStorageSpace <= Storage.LOW_STORAGE_THRESHOLD) { Log.i(TAG, "Not enough space or storage not ready. remaining=" + mStorageSpace); return; } Log.v(TAG, "onShutterButtonClick: mCameraState=" + mCameraState); // If the user wants to do a snapshot while the previous one is still // in progress, remember the fact and do it after we finish the previous // one and re-start the preview. Snapshot in progress also includes the // state that autofocus is focusing and a picture will be taken when // focus callback arrives. if ((mFocusManager.isFocusingSnapOnFinish() || mCameraState == SNAPSHOT_IN_PROGRESS) && !mIsImageCaptureIntent) { mSnapshotOnIdle = true; return; } mSnapshotOnIdle = false; mFocusManager.doSnap(); } private void installIntentFilter() { // install an intent filter to receive SD card related events. IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED); intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED); intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED); intentFilter.addAction(Intent.ACTION_MEDIA_CHECKING); intentFilter.addDataScheme("file"); registerReceiver(mReceiver, intentFilter); mDidRegister = true; } @Override protected void onResume() { mPaused = false; super.onResume(); if (mOpenCameraFail || mCameraDisabled) return; mJpegPictureCallbackTime = 0; mZoomValue = 0; // Start the preview if it is not started. if (mCameraState == PREVIEW_STOPPED && mCameraStartUpThread == null) { resetExposureCompensation(); mCameraStartUpThread = new CameraStartUpThread(); mCameraStartUpThread.start(); } if (!mIsImageCaptureIntent) getLastThumbnail(); // If first time initialization is not finished, put it in the // message queue. if (!mFirstTimeInitialized) { mHandler.sendEmptyMessage(FIRST_TIME_INIT); } else { initializeSecondTime(); } keepScreenOnAwhile(); // Dismiss open menu if exists. PopupManager.getInstance(this).notifyShowPopup(null); if (mCameraSound == null) { mCameraSound = new MediaActionSound(); // Not required, but reduces latency when playback is requested later. mCameraSound.load(MediaActionSound.FOCUS_COMPLETE); } } void waitCameraStartUpThread() { try { if (mCameraStartUpThread != null) { mCameraStartUpThread.cancel(); mCameraStartUpThread.join(); mCameraStartUpThread = null; setCameraState(IDLE); } } catch (InterruptedException e) { // ignore } } @Override protected void onPause() { mPaused = true; super.onPause(); // Wait the camera start up thread to finish. waitCameraStartUpThread(); stopPreview(); // Close the camera now because other activities may need to use it. closeCamera(); if (mSurfaceTexture != null) { mCameraScreenNail.releaseSurfaceTexture(); mSurfaceTexture = null; } if (mCameraSound != null) { mCameraSound.release(); mCameraSound = null; } resetScreenOn(); // Clear UI. collapseCameraControls(); if (mFaceView != null) mFaceView.clear(); if (mFirstTimeInitialized) { mOrientationListener.disable(); if (mImageSaver != null) { mImageSaver.finish(); mImageSaver = null; mImageNamer.finish(); mImageNamer = null; } } if (mDidRegister) { unregisterReceiver(mReceiver); mDidRegister = false; } if (mLocationManager != null) mLocationManager.recordLocation(false); updateExposureOnScreenIndicator(0); // If we are in an image capture intent and has taken // a picture, we just clear it in onPause. mJpegImageData = null; // Remove the messages in the event queue. mHandler.removeMessages(FIRST_TIME_INIT); mHandler.removeMessages(CHECK_DISPLAY_ROTATION); mHandler.removeMessages(SWITCH_CAMERA); mHandler.removeMessages(CAMERA_OPEN_DONE); mHandler.removeMessages(START_PREVIEW_DONE); mHandler.removeMessages(OPEN_CAMERA_FAIL); mHandler.removeMessages(CAMERA_DISABLED); mPendingSwitchCameraId = -1; if (mFocusManager != null) mFocusManager.removeMessages(); } private void initializeControlByIntent() { if (mIsImageCaptureIntent) { // Cannot use RotateImageView for "done" and "cancel" button because // the tablet layout uses RotateLayout, which cannot be cast to // RotateImageView. mReviewDoneButton = (Rotatable) findViewById(R.id.btn_done); mReviewCancelButton = (Rotatable) findViewById(R.id.btn_cancel); mReviewRetakeButton = findViewById(R.id.btn_retake); findViewById(R.id.btn_cancel).setVisibility(View.VISIBLE); // Not grayed out upon disabled, to make the follow-up fade-out // effect look smooth. Note that the review done button in tablet // layout is not a TwoStateImageView. if (mReviewDoneButton instanceof TwoStateImageView) { ((TwoStateImageView) mReviewDoneButton).enableFilter(false); } setupCaptureParams(); } else { mThumbnailView = (RotateImageView) findViewById(R.id.thumbnail); mThumbnailView.enableFilter(false); mThumbnailView.setVisibility(View.VISIBLE); mThumbnailViewWidth = mThumbnailView.getLayoutParams().width; mModePicker = (ModePicker) findViewById(R.id.mode_picker); mModePicker.setVisibility(View.VISIBLE); mModePicker.setOnModeChangeListener(this); mModePicker.setCurrentMode(ModePicker.MODE_CAMERA); } } private void initializeFocusManager() { // Create FocusManager object. startPreview needs it. CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId]; boolean mirror = (info.facing == CameraInfo.CAMERA_FACING_FRONT); String[] defaultFocusModes = getResources().getStringArray( R.array.pref_camera_focusmode_default_array); mFocusManager = new FocusManager(mPreferences, defaultFocusModes, mFocusAreaIndicator, mInitialParams, this, mirror, getMainLooper()); } private void initializeMiscControls() { // startPreview needs this. mPreviewFrameLayout = (PreviewFrameLayout) findViewById(R.id.frame); // Set touch focus listener. setSingleTapUpListener(mPreviewFrameLayout); mZoomControl = (ZoomControl) findViewById(R.id.zoom_control); mOnScreenIndicators = (Rotatable) findViewById(R.id.on_screen_indicators); mFaceView = (FaceView) findViewById(R.id.face_view); mPreviewFrameLayout.addOnLayoutChangeListener(this); mPreviewFrameLayout.setOnSizeChangedListener(this); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); setDisplayOrientation(); // Change layout in response to configuration change LinearLayout appRoot = (LinearLayout) findViewById(R.id.camera_app_root); appRoot.setOrientation( newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE ? LinearLayout.HORIZONTAL : LinearLayout.VERTICAL); appRoot.removeAllViews(); LayoutInflater inflater = getLayoutInflater(); inflater.inflate(R.layout.preview_frame, appRoot); inflater.inflate(R.layout.camera_control, appRoot); // from onCreate() initializeControlByIntent(); initializeFocusManager(); initializeMiscControls(); initializeIndicatorControl(); mFocusAreaIndicator = (RotateLayout) findViewById( R.id.focus_indicator_rotate_layout); mFocusManager.setFocusAreaIndicator(mFocusAreaIndicator); // from onResume() if (!mIsImageCaptureIntent) updateThumbnailView(); // from initializeFirstTime() mShutterButton = (ShutterButton) findViewById(R.id.shutter_button); mShutterButton.setOnShutterButtonListener(this); mShutterButton.setVisibility(View.VISIBLE); initializeZoom(); initOnScreenIndicator(); updateOnScreenIndicators(); mFaceView.clear(); mFaceView.setVisibility(View.VISIBLE); mFaceView.setDisplayOrientation(mDisplayOrientation); CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId]; mFaceView.setMirror(info.facing == CameraInfo.CAMERA_FACING_FRONT); mFaceView.resume(); mFocusManager.setFaceView(mFaceView); } @Override protected void onActivityResult( int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQUEST_CROP: { Intent intent = new Intent(); if (data != null) { Bundle extras = data.getExtras(); if (extras != null) { intent.putExtras(extras); } } setResultEx(resultCode, intent); finish(); File path = getFileStreamPath(sTempCropFilename); path.delete(); break; } } } private boolean canTakePicture() { return isCameraIdle() && (mStorageSpace > Storage.LOW_STORAGE_THRESHOLD); } @Override public void autoFocus() { mFocusStartTime = System.currentTimeMillis(); mCameraDevice.autoFocus(mAutoFocusCallback); setCameraState(FOCUSING); } @Override public void cancelAutoFocus() { mCameraDevice.cancelAutoFocus(); setCameraState(IDLE); setCameraParameters(UPDATE_PARAM_PREFERENCE); } // Preview area is touched. Handle touch focus. @Override protected void onSingleTapUp(View view, int x, int y) { if (mPaused || mCameraDevice == null || !mFirstTimeInitialized || mCameraState == SNAPSHOT_IN_PROGRESS || mCameraState == SWITCHING_CAMERA || mCameraState == PREVIEW_STOPPED) { return; } // Do not trigger touch focus if popup window is opened. if (collapseCameraControls()) return; // Check if metering area or focus area is supported. if (!mFocusAreaSupported && !mMeteringAreaSupported) return; mFocusManager.onSingleTapUp(x, y); } @Override public void onBackPressed() { if (!isCameraIdle()) { // ignore backs while we're taking a picture return; } else if (!collapseCameraControls()) { super.onBackPressed(); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_FOCUS: if (mFirstTimeInitialized && event.getRepeatCount() == 0) { onShutterButtonFocus(true); } return true; case KeyEvent.KEYCODE_CAMERA: if (mFirstTimeInitialized && event.getRepeatCount() == 0) { onShutterButtonClick(); } return true; case KeyEvent.KEYCODE_DPAD_CENTER: // If we get a dpad center event without any focused view, move // the focus to the shutter button and press it. if (mFirstTimeInitialized && event.getRepeatCount() == 0) { // Start auto-focus immediately to reduce shutter lag. After // the shutter button gets the focus, onShutterButtonFocus() // will be called again but it is fine. if (collapseCameraControls()) return true; onShutterButtonFocus(true); if (mShutterButton.isInTouchMode()) { mShutterButton.requestFocusFromTouch(); } else { mShutterButton.requestFocus(); } mShutterButton.setPressed(true); } return true; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_FOCUS: if (mFirstTimeInitialized) { onShutterButtonFocus(false); } return true; } return super.onKeyUp(keyCode, event); } private void closeCamera() { if (mCameraDevice != null) { mCameraDevice.setZoomChangeListener(null); mCameraDevice.setFaceDetectionListener(null); mCameraDevice.setErrorCallback(null); CameraHolder.instance().release(); mFaceDetectionStarted = false; mCameraDevice = null; setCameraState(PREVIEW_STOPPED); mFocusManager.onCameraReleased(); } } private void setDisplayOrientation() { mDisplayRotation = Util.getDisplayRotation(this); mDisplayOrientation = Util.getDisplayOrientation(mDisplayRotation, mCameraId); mCameraDisplayOrientation = Util.getDisplayOrientation(0, mCameraId); if (mFaceView != null) { mFaceView.setDisplayOrientation(mDisplayOrientation); } mFocusManager.setDisplayOrientation(mDisplayOrientation); } private void startPreview() { mFocusManager.resetTouchFocus(); mCameraDevice.setErrorCallback(mErrorCallback); // If we're previewing already, stop the preview first (this will blank // the screen). if (mCameraState != PREVIEW_STOPPED) stopPreview(); setDisplayOrientation(); mCameraDevice.setDisplayOrientation(mCameraDisplayOrientation); if (!mSnapshotOnIdle) { // If the focus mode is continuous autofocus, call cancelAutoFocus to // resume it because it may have been paused by autoFocus call. if (Parameters.FOCUS_MODE_CONTINUOUS_PICTURE.equals(mFocusManager.getFocusMode())) { mCameraDevice.cancelAutoFocus(); } mFocusManager.setAeAwbLock(false); // Unlock AE and AWB. } setCameraParameters(UPDATE_PARAM_ALL); if (mSurfaceTexture == null) { Size size = mParameters.getPreviewSize(); if (mCameraDisplayOrientation % 180 == 0) { mCameraScreenNail.setSize(size.width, size.height); } else { mCameraScreenNail.setSize(size.height, size.width); } notifyScreenNailChanged(); mCameraScreenNail.acquireSurfaceTexture(); mSurfaceTexture = mCameraScreenNail.getSurfaceTexture(); } mCameraDevice.setPreviewTextureAsync(mSurfaceTexture); Log.v(TAG, "startPreview"); mCameraDevice.startPreviewAsync(); mFocusManager.onPreviewStarted(); if (mSnapshotOnIdle) { mHandler.post(mDoSnapRunnable); } } private void stopPreview() { if (mCameraDevice != null && mCameraState != PREVIEW_STOPPED) { Log.v(TAG, "stopPreview"); mCameraDevice.cancelAutoFocus(); // Reset the focus. mCameraDevice.stopPreview(); mFaceDetectionStarted = false; } setCameraState(PREVIEW_STOPPED); if (mFocusManager != null) mFocusManager.onPreviewStopped(); } private static boolean isSupported(String value, List<String> supported) { return supported == null ? false : supported.indexOf(value) >= 0; } @SuppressWarnings("deprecation") private void updateCameraParametersInitialize() { // Reset preview frame rate to the maximum because it may be lowered by // video camera application. List<Integer> frameRates = mParameters.getSupportedPreviewFrameRates(); if (frameRates != null) { Integer max = Collections.max(frameRates); mParameters.setPreviewFrameRate(max); } mParameters.setRecordingHint(false); // Disable video stabilization. Convenience methods not available in API // level <= 14 String vstabSupported = mParameters.get("video-stabilization-supported"); if ("true".equals(vstabSupported)) { mParameters.set("video-stabilization", "false"); } } private void updateCameraParametersZoom() { // Set zoom. if (mParameters.isZoomSupported()) { mParameters.setZoom(mZoomValue); } } private void updateCameraParametersPreference() { if (mAeLockSupported) { mParameters.setAutoExposureLock(mFocusManager.getAeAwbLock()); } if (mAwbLockSupported) { mParameters.setAutoWhiteBalanceLock(mFocusManager.getAeAwbLock()); } if (mFocusAreaSupported) { mParameters.setFocusAreas(mFocusManager.getFocusAreas()); } if (mMeteringAreaSupported) { // Use the same area for focus and metering. mParameters.setMeteringAreas(mFocusManager.getMeteringAreas()); } // Set picture size. String pictureSize = mPreferences.getString( CameraSettings.KEY_PICTURE_SIZE, null); if (pictureSize == null) { CameraSettings.initialCameraPictureSize(this, mParameters); } else { List<Size> supported = mParameters.getSupportedPictureSizes(); CameraSettings.setCameraPictureSize( pictureSize, supported, mParameters); } Size size = mParameters.getPictureSize(); // Set a preview size that is closest to the viewfinder height and has // the right aspect ratio. List<Size> sizes = mParameters.getSupportedPreviewSizes(); Size optimalSize = Util.getOptimalPreviewSize(this, sizes, (double) size.width / size.height); Size original = mParameters.getPreviewSize(); if (!original.equals(optimalSize)) { mParameters.setPreviewSize(optimalSize.width, optimalSize.height); // Zoom related settings will be changed for different preview // sizes, so set and read the parameters to get latest values mCameraDevice.setParameters(mParameters); mParameters = mCameraDevice.getParameters(); } Log.v(TAG, "Preview size is " + optimalSize.width + "x" + optimalSize.height); // Since change scene mode may change supported values, // Set scene mode first, mSceneMode = mPreferences.getString( CameraSettings.KEY_SCENE_MODE, getString(R.string.pref_camera_scenemode_default)); if (isSupported(mSceneMode, mParameters.getSupportedSceneModes())) { if (!mParameters.getSceneMode().equals(mSceneMode)) { mParameters.setSceneMode(mSceneMode); // Setting scene mode will change the settings of flash mode, // white balance, and focus mode. Here we read back the // parameters, so we can know those settings. mCameraDevice.setParameters(mParameters); mParameters = mCameraDevice.getParameters(); } } else { mSceneMode = mParameters.getSceneMode(); if (mSceneMode == null) { mSceneMode = Parameters.SCENE_MODE_AUTO; } } // Set JPEG quality. int jpegQuality = CameraProfile.getJpegEncodingQualityParameter(mCameraId, CameraProfile.QUALITY_HIGH); mParameters.setJpegQuality(jpegQuality); // For the following settings, we need to check if the settings are // still supported by latest driver, if not, ignore the settings. // Set exposure compensation int value = CameraSettings.readExposure(mPreferences); int max = mParameters.getMaxExposureCompensation(); int min = mParameters.getMinExposureCompensation(); if (value >= min && value <= max) { mParameters.setExposureCompensation(value); } else { Log.w(TAG, "invalid exposure range: " + value); } if (Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) { // Set flash mode. String flashMode = mPreferences.getString( CameraSettings.KEY_FLASH_MODE, getString(R.string.pref_camera_flashmode_default)); List<String> supportedFlash = mParameters.getSupportedFlashModes(); if (isSupported(flashMode, supportedFlash)) { mParameters.setFlashMode(flashMode); } else { flashMode = mParameters.getFlashMode(); if (flashMode == null) { flashMode = getString( R.string.pref_camera_flashmode_no_flash); } } // Set white balance parameter. String whiteBalance = mPreferences.getString( CameraSettings.KEY_WHITE_BALANCE, getString(R.string.pref_camera_whitebalance_default)); if (isSupported(whiteBalance, mParameters.getSupportedWhiteBalance())) { mParameters.setWhiteBalance(whiteBalance); } else { whiteBalance = mParameters.getWhiteBalance(); if (whiteBalance == null) { whiteBalance = Parameters.WHITE_BALANCE_AUTO; } } // Set focus mode. mFocusManager.overrideFocusMode(null); mParameters.setFocusMode(mFocusManager.getFocusMode()); } else { mFocusManager.overrideFocusMode(mParameters.getFocusMode()); } if (mContinousFocusSupported) { - try { - if (mParameters.getFocusMode().equals(Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) { - mCameraDevice.setAutoFocusMoveCallback(mAutoFocusMoveCallback); - } else { - mCameraDevice.setAutoFocusMoveCallback(null); - } - } catch (RuntimeException e) { - // Ignore. This can be removed if CTS requires autofocus move - // callback. + if (mParameters.getFocusMode().equals(Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) { + mCameraDevice.setAutoFocusMoveCallback(mAutoFocusMoveCallback); + } else { + mCameraDevice.setAutoFocusMoveCallback(null); } } } // We separate the parameters into several subsets, so we can update only // the subsets actually need updating. The PREFERENCE set needs extra // locking because the preference can be changed from GLThread as well. private void setCameraParameters(int updateSet) { if ((updateSet & UPDATE_PARAM_INITIALIZE) != 0) { updateCameraParametersInitialize(); } if ((updateSet & UPDATE_PARAM_ZOOM) != 0) { updateCameraParametersZoom(); } if ((updateSet & UPDATE_PARAM_PREFERENCE) != 0) { updateCameraParametersPreference(); } mCameraDevice.setParameters(mParameters); } // If the Camera is idle, update the parameters immediately, otherwise // accumulate them in mUpdateSet and update later. private void setCameraParametersWhenIdle(int additionalUpdateSet) { mUpdateSet |= additionalUpdateSet; if (mCameraDevice == null) { // We will update all the parameters when we open the device, so // we don't need to do anything now. mUpdateSet = 0; return; } else if (isCameraIdle()) { setCameraParameters(mUpdateSet); updateSceneModeUI(); mUpdateSet = 0; } else { if (!mHandler.hasMessages(SET_CAMERA_PARAMETERS_WHEN_IDLE)) { mHandler.sendEmptyMessageDelayed( SET_CAMERA_PARAMETERS_WHEN_IDLE, 1000); } } } private boolean isCameraIdle() { return (mCameraState == IDLE) || ((mFocusManager != null) && mFocusManager.isFocusCompleted() && (mCameraState != SWITCHING_CAMERA)); } private boolean isImageCaptureIntent() { String action = getIntent().getAction(); return (MediaStore.ACTION_IMAGE_CAPTURE.equals(action)); } private void setupCaptureParams() { Bundle myExtras = getIntent().getExtras(); if (myExtras != null) { mSaveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT); mCropValue = myExtras.getString("crop"); } } private void showPostCaptureAlert() { if (mIsImageCaptureIntent) { Util.fadeOut(mIndicatorControlContainer); Util.fadeOut(mShutterButton); Util.fadeIn(mReviewRetakeButton); Util.fadeIn((View) mReviewDoneButton); } } private void hidePostCaptureAlert() { if (mIsImageCaptureIntent) { Util.fadeOut(mReviewRetakeButton); Util.fadeOut((View) mReviewDoneButton); Util.fadeIn(mShutterButton); if (mIndicatorControlContainer != null) { Util.fadeIn(mIndicatorControlContainer); } } } private void switchToOtherMode(int mode) { if (isFinishing()) return; if (mImageSaver != null) mImageSaver.waitDone(); if (mThumbnail != null) ThumbnailHolder.keep(mThumbnail); MenuHelper.gotoMode(mode, Camera.this); mHandler.removeMessages(FIRST_TIME_INIT); finish(); } @Override public void onModeChanged(int mode) { if (mode != ModePicker.MODE_CAMERA) switchToOtherMode(mode); } @Override public void onSharedPreferenceChanged() { // ignore the events after "onPause()" if (mPaused) return; boolean recordLocation = RecordLocationPreference.get( mPreferences, mContentResolver); mLocationManager.recordLocation(recordLocation); setCameraParametersWhenIdle(UPDATE_PARAM_PREFERENCE); setPreviewFrameLayoutAspectRatio(); updateOnScreenIndicators(); } @Override public void onCameraPickerClicked(int cameraId) { if (mPaused || mPendingSwitchCameraId != -1) return; Log.v(TAG, "Start to copy texture. cameraId=" + cameraId); // We need to keep a preview frame for the animation before // releasing the camera. This will trigger onPreviewTextureCopied. mCameraScreenNail.copyTexture(); mPendingSwitchCameraId = cameraId; // Disable all camera controls. setCameraState(SWITCHING_CAMERA); } private void switchCamera() { if (mPaused) return; Log.v(TAG, "Start to switch camera. id=" + mPendingSwitchCameraId); mCameraId = mPendingSwitchCameraId; mPendingSwitchCameraId = -1; mCameraPicker.setCameraId(mCameraId); // from onPause closeCamera(); collapseCameraControls(); if (mFaceView != null) mFaceView.clear(); if (mFocusManager != null) mFocusManager.removeMessages(); // Restart the camera and initialize the UI. From onCreate. mPreferences.setLocalId(Camera.this, mCameraId); CameraSettings.upgradeLocalPreferences(mPreferences.getLocal()); CameraOpenThread cameraOpenThread = new CameraOpenThread(); cameraOpenThread.start(); try { cameraOpenThread.join(); } catch (InterruptedException ex) { // ignore } initializeCapabilities(); CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId]; boolean mirror = (info.facing == CameraInfo.CAMERA_FACING_FRONT); mFocusManager.setMirror(mirror); mFocusManager.setParameters(mInitialParams); startPreview(); setCameraState(IDLE); initializeIndicatorControl(); // from onResume setOrientationIndicator(mOrientationCompensation, false); // from initializeFirstTime initializeZoom(); updateOnScreenIndicators(); startFaceDetection(); showTapToFocusToastIfNeeded(); // Start switch camera animation. mCameraDevice.waitForIdle(); // Wait until startPreview finishes. mCameraScreenNail.animateSwitchCamera(); } // Preview texture has been copied. Now camera can be released and the // animation can be started. @Override protected void onPreviewTextureCopied() { mHandler.sendEmptyMessage(SWITCH_CAMERA); } @Override public void onUserInteraction() { super.onUserInteraction(); keepScreenOnAwhile(); } private void resetScreenOn() { mHandler.removeMessages(CLEAR_SCREEN_DELAY); getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } private void keepScreenOnAwhile() { mHandler.removeMessages(CLEAR_SCREEN_DELAY); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY); } @Override public void onRestorePreferencesClicked() { if (mPaused) return; Runnable runnable = new Runnable() { @Override public void run() { restorePreferences(); } }; mRotateDialog.showAlertDialog( null, getString(R.string.confirm_restore_message), getString(android.R.string.ok), runnable, getString(android.R.string.cancel), null); } private void restorePreferences() { // Reset the zoom. Zoom value is not stored in preference. if (mParameters.isZoomSupported()) { mZoomValue = 0; setCameraParametersWhenIdle(UPDATE_PARAM_ZOOM); mZoomControl.setZoomIndex(0); } if (mIndicatorControlContainer != null) { mIndicatorControlContainer.dismissSettingPopup(); CameraSettings.restorePreferences(Camera.this, mPreferences, mParameters); mIndicatorControlContainer.reloadPreferences(); onSharedPreferenceChanged(); } } @Override public void onOverriddenPreferencesClicked() { if (mPaused) return; if (mNotSelectableToast == null) { String str = getResources().getString(R.string.not_selectable_in_scene_mode); mNotSelectableToast = Toast.makeText(Camera.this, str, Toast.LENGTH_SHORT); } mNotSelectableToast.show(); } @Override public void onFaceDetection(Face[] faces, android.hardware.Camera camera) { mFaceView.setFaces(faces); } private void showTapToFocusToast() { new RotateTextToast(this, R.string.tap_to_focus, mOrientationCompensation).show(); // Clear the preference. Editor editor = mPreferences.edit(); editor.putBoolean(CameraSettings.KEY_CAMERA_FIRST_USE_HINT_SHOWN, false); editor.apply(); } private void initializeCapabilities() { mInitialParams = mCameraDevice.getParameters(); mFocusAreaSupported = (mInitialParams.getMaxNumFocusAreas() > 0 && isSupported(Parameters.FOCUS_MODE_AUTO, mInitialParams.getSupportedFocusModes())); mMeteringAreaSupported = (mInitialParams.getMaxNumMeteringAreas() > 0); mAeLockSupported = mInitialParams.isAutoExposureLockSupported(); mAwbLockSupported = mInitialParams.isAutoWhiteBalanceLockSupported(); mContinousFocusSupported = mInitialParams.getSupportedFocusModes().contains( Parameters.FOCUS_MODE_CONTINUOUS_PICTURE); } // PreviewFrameLayout size has changed. @Override public void onSizeChanged(int width, int height) { if (mFocusManager != null) mFocusManager.setPreviewSize(width, height); } void setPreviewFrameLayoutAspectRatio() { // Set the preview frame aspect ratio according to the picture size. Size size = mParameters.getPictureSize(); mPreviewFrameLayout.setAspectRatio((double) size.width / size.height); } }
true
true
private void updateCameraParametersPreference() { if (mAeLockSupported) { mParameters.setAutoExposureLock(mFocusManager.getAeAwbLock()); } if (mAwbLockSupported) { mParameters.setAutoWhiteBalanceLock(mFocusManager.getAeAwbLock()); } if (mFocusAreaSupported) { mParameters.setFocusAreas(mFocusManager.getFocusAreas()); } if (mMeteringAreaSupported) { // Use the same area for focus and metering. mParameters.setMeteringAreas(mFocusManager.getMeteringAreas()); } // Set picture size. String pictureSize = mPreferences.getString( CameraSettings.KEY_PICTURE_SIZE, null); if (pictureSize == null) { CameraSettings.initialCameraPictureSize(this, mParameters); } else { List<Size> supported = mParameters.getSupportedPictureSizes(); CameraSettings.setCameraPictureSize( pictureSize, supported, mParameters); } Size size = mParameters.getPictureSize(); // Set a preview size that is closest to the viewfinder height and has // the right aspect ratio. List<Size> sizes = mParameters.getSupportedPreviewSizes(); Size optimalSize = Util.getOptimalPreviewSize(this, sizes, (double) size.width / size.height); Size original = mParameters.getPreviewSize(); if (!original.equals(optimalSize)) { mParameters.setPreviewSize(optimalSize.width, optimalSize.height); // Zoom related settings will be changed for different preview // sizes, so set and read the parameters to get latest values mCameraDevice.setParameters(mParameters); mParameters = mCameraDevice.getParameters(); } Log.v(TAG, "Preview size is " + optimalSize.width + "x" + optimalSize.height); // Since change scene mode may change supported values, // Set scene mode first, mSceneMode = mPreferences.getString( CameraSettings.KEY_SCENE_MODE, getString(R.string.pref_camera_scenemode_default)); if (isSupported(mSceneMode, mParameters.getSupportedSceneModes())) { if (!mParameters.getSceneMode().equals(mSceneMode)) { mParameters.setSceneMode(mSceneMode); // Setting scene mode will change the settings of flash mode, // white balance, and focus mode. Here we read back the // parameters, so we can know those settings. mCameraDevice.setParameters(mParameters); mParameters = mCameraDevice.getParameters(); } } else { mSceneMode = mParameters.getSceneMode(); if (mSceneMode == null) { mSceneMode = Parameters.SCENE_MODE_AUTO; } } // Set JPEG quality. int jpegQuality = CameraProfile.getJpegEncodingQualityParameter(mCameraId, CameraProfile.QUALITY_HIGH); mParameters.setJpegQuality(jpegQuality); // For the following settings, we need to check if the settings are // still supported by latest driver, if not, ignore the settings. // Set exposure compensation int value = CameraSettings.readExposure(mPreferences); int max = mParameters.getMaxExposureCompensation(); int min = mParameters.getMinExposureCompensation(); if (value >= min && value <= max) { mParameters.setExposureCompensation(value); } else { Log.w(TAG, "invalid exposure range: " + value); } if (Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) { // Set flash mode. String flashMode = mPreferences.getString( CameraSettings.KEY_FLASH_MODE, getString(R.string.pref_camera_flashmode_default)); List<String> supportedFlash = mParameters.getSupportedFlashModes(); if (isSupported(flashMode, supportedFlash)) { mParameters.setFlashMode(flashMode); } else { flashMode = mParameters.getFlashMode(); if (flashMode == null) { flashMode = getString( R.string.pref_camera_flashmode_no_flash); } } // Set white balance parameter. String whiteBalance = mPreferences.getString( CameraSettings.KEY_WHITE_BALANCE, getString(R.string.pref_camera_whitebalance_default)); if (isSupported(whiteBalance, mParameters.getSupportedWhiteBalance())) { mParameters.setWhiteBalance(whiteBalance); } else { whiteBalance = mParameters.getWhiteBalance(); if (whiteBalance == null) { whiteBalance = Parameters.WHITE_BALANCE_AUTO; } } // Set focus mode. mFocusManager.overrideFocusMode(null); mParameters.setFocusMode(mFocusManager.getFocusMode()); } else { mFocusManager.overrideFocusMode(mParameters.getFocusMode()); } if (mContinousFocusSupported) { try { if (mParameters.getFocusMode().equals(Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) { mCameraDevice.setAutoFocusMoveCallback(mAutoFocusMoveCallback); } else { mCameraDevice.setAutoFocusMoveCallback(null); } } catch (RuntimeException e) { // Ignore. This can be removed if CTS requires autofocus move // callback. } } }
private void updateCameraParametersPreference() { if (mAeLockSupported) { mParameters.setAutoExposureLock(mFocusManager.getAeAwbLock()); } if (mAwbLockSupported) { mParameters.setAutoWhiteBalanceLock(mFocusManager.getAeAwbLock()); } if (mFocusAreaSupported) { mParameters.setFocusAreas(mFocusManager.getFocusAreas()); } if (mMeteringAreaSupported) { // Use the same area for focus and metering. mParameters.setMeteringAreas(mFocusManager.getMeteringAreas()); } // Set picture size. String pictureSize = mPreferences.getString( CameraSettings.KEY_PICTURE_SIZE, null); if (pictureSize == null) { CameraSettings.initialCameraPictureSize(this, mParameters); } else { List<Size> supported = mParameters.getSupportedPictureSizes(); CameraSettings.setCameraPictureSize( pictureSize, supported, mParameters); } Size size = mParameters.getPictureSize(); // Set a preview size that is closest to the viewfinder height and has // the right aspect ratio. List<Size> sizes = mParameters.getSupportedPreviewSizes(); Size optimalSize = Util.getOptimalPreviewSize(this, sizes, (double) size.width / size.height); Size original = mParameters.getPreviewSize(); if (!original.equals(optimalSize)) { mParameters.setPreviewSize(optimalSize.width, optimalSize.height); // Zoom related settings will be changed for different preview // sizes, so set and read the parameters to get latest values mCameraDevice.setParameters(mParameters); mParameters = mCameraDevice.getParameters(); } Log.v(TAG, "Preview size is " + optimalSize.width + "x" + optimalSize.height); // Since change scene mode may change supported values, // Set scene mode first, mSceneMode = mPreferences.getString( CameraSettings.KEY_SCENE_MODE, getString(R.string.pref_camera_scenemode_default)); if (isSupported(mSceneMode, mParameters.getSupportedSceneModes())) { if (!mParameters.getSceneMode().equals(mSceneMode)) { mParameters.setSceneMode(mSceneMode); // Setting scene mode will change the settings of flash mode, // white balance, and focus mode. Here we read back the // parameters, so we can know those settings. mCameraDevice.setParameters(mParameters); mParameters = mCameraDevice.getParameters(); } } else { mSceneMode = mParameters.getSceneMode(); if (mSceneMode == null) { mSceneMode = Parameters.SCENE_MODE_AUTO; } } // Set JPEG quality. int jpegQuality = CameraProfile.getJpegEncodingQualityParameter(mCameraId, CameraProfile.QUALITY_HIGH); mParameters.setJpegQuality(jpegQuality); // For the following settings, we need to check if the settings are // still supported by latest driver, if not, ignore the settings. // Set exposure compensation int value = CameraSettings.readExposure(mPreferences); int max = mParameters.getMaxExposureCompensation(); int min = mParameters.getMinExposureCompensation(); if (value >= min && value <= max) { mParameters.setExposureCompensation(value); } else { Log.w(TAG, "invalid exposure range: " + value); } if (Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) { // Set flash mode. String flashMode = mPreferences.getString( CameraSettings.KEY_FLASH_MODE, getString(R.string.pref_camera_flashmode_default)); List<String> supportedFlash = mParameters.getSupportedFlashModes(); if (isSupported(flashMode, supportedFlash)) { mParameters.setFlashMode(flashMode); } else { flashMode = mParameters.getFlashMode(); if (flashMode == null) { flashMode = getString( R.string.pref_camera_flashmode_no_flash); } } // Set white balance parameter. String whiteBalance = mPreferences.getString( CameraSettings.KEY_WHITE_BALANCE, getString(R.string.pref_camera_whitebalance_default)); if (isSupported(whiteBalance, mParameters.getSupportedWhiteBalance())) { mParameters.setWhiteBalance(whiteBalance); } else { whiteBalance = mParameters.getWhiteBalance(); if (whiteBalance == null) { whiteBalance = Parameters.WHITE_BALANCE_AUTO; } } // Set focus mode. mFocusManager.overrideFocusMode(null); mParameters.setFocusMode(mFocusManager.getFocusMode()); } else { mFocusManager.overrideFocusMode(mParameters.getFocusMode()); } if (mContinousFocusSupported) { if (mParameters.getFocusMode().equals(Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) { mCameraDevice.setAutoFocusMoveCallback(mAutoFocusMoveCallback); } else { mCameraDevice.setAutoFocusMoveCallback(null); } } }
diff --git a/src/com/tomclaw/mandarin/core/Handler.java b/src/com/tomclaw/mandarin/core/Handler.java index 95c10e5..f685872 100644 --- a/src/com/tomclaw/mandarin/core/Handler.java +++ b/src/com/tomclaw/mandarin/core/Handler.java @@ -1,1033 +1,1034 @@ package com.tomclaw.mandarin.core; import com.tomclaw.mandarin.main.*; import com.tomclaw.mandarin.molecus.*; import com.tomclaw.tcuilite.*; import com.tomclaw.tcuilite.localization.Localization; import com.tomclaw.utils.LogUtil; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; /** * Solkin Igor Viktorovich, TomClaw Software, 2003-2012 * http://www.tomclaw.com/ * @author Solkin */ public class Handler { /** * Setting up received roster * @param roster */ public static void setRoster( Hashtable params ) { Vector rosterItems = ( Vector ) params.get( "ROSTER" ); /** Inserting services group item into zero index **/ GroupItem servicesGroupItem = ( GroupItem ) params.get( "SERVICES" ); int regServicesCount = servicesGroupItem.getChildsCount(); int allServicesCount = MidletMain.mainFrame.buddyList.servicesGroupItem.getChildsCount(); for ( int c = 0; c < regServicesCount; c++ ) { BuddyItem regServiceItem = ( BuddyItem ) servicesGroupItem.elementAt( c ); LogUtil.outMessage( "regServiceItem [ " + c + " ] = " + regServiceItem.getJid() ); /** Cycling all services **/ for ( int i = 0; i < allServicesCount; i++ ) { ServiceItem allServiceItem = ( ServiceItem ) MidletMain.mainFrame.buddyList.servicesGroupItem.elementAt( i ); if ( regServiceItem.getJid().equals( allServiceItem.getJid() ) ) { /** This is not temp service **/ allServiceItem.setTemp( false ); allServiceItem.setSubscription( regServiceItem.getSubscription() ); /** This is the same service **/ regServiceItem = null; break; } } /** Checking for item existance in all services **/ if ( regServiceItem != null ) { MidletMain.mainFrame.buddyList.servicesGroupItem.addChild( regServiceItem ); } } rosterItems.insertElementAt( MidletMain.mainFrame.buddyList.servicesGroupItem, 0 ); /** Inserting rooms group into second index **/ rosterItems.insertElementAt( MidletMain.mainFrame.buddyList.roomsGroupItem, 1 ); /** Creating and inserting temporary items group **/ MidletMain.mainFrame.buddyList.tempGroupItem = new GroupItem( Localization.getMessage( "TEMPORARY" ) ); MidletMain.mainFrame.buddyList.tempGroupItem.internalGroupId = GroupItem.GROUP_TEMP_ID; MidletMain.mainFrame.buddyList.tempGroupItem.isCollapsed = false; rosterItems.addElement( MidletMain.mainFrame.buddyList.tempGroupItem ); /** Inserting general group to the end **/ MidletMain.mainFrame.buddyList.generalGroupItem = ( GroupItem ) params.get( "GENERAL" ); MidletMain.mainFrame.buddyList.generalGroupItem.isGroupVisible = true; rosterItems.addElement( MidletMain.mainFrame.buddyList.generalGroupItem ); /** Setting up collected roster vector **/ MidletMain.mainFrame.buddyList.setBuddyItems( rosterItems ); /** Sending request to chatframe for update * buddy items and resources for opened tabs **/ MidletMain.chatFrame.updateBuddyItems(); /** Repainting **/ MainFrame.repaintFrame(); ChatFrame.repaintFrame(); } /** * Setting up services * @param services */ public static void setServices( Hashtable services ) { /** Definig services group **/ MidletMain.mainFrame.buddyList.servicesGroupItem = new GroupItem( Localization.getMessage( "SERVICES" ) ); MidletMain.mainFrame.buddyList.servicesGroupItem.internalGroupId = GroupItem.GROUP_SERVICES_ID; /** Cycling elements **/ Vector items = ( Vector ) services.get( "ITEMS" ); if ( items != null ) { for ( int c = 0; c < items.size(); c++ ) { Item item = ( Item ) items.elementAt( c ); ServiceItem serviceItem = new ServiceItem( item.jid, item.name ); serviceItem.updateUi(); if ( serviceItem.isServiceSupported() ) { MidletMain.mainFrame.buddyList.servicesGroupItem.addChild( serviceItem ); } } } } /** * Setting up bookmarks * @param services */ public static void setBookmarks( Vector items ) { /** Checking for items existance **/ if ( items != null ) { MidletMain.mainFrame.buddyList.roomsGroupItem.setChilds( items ); } } /** * Setting up bookmarks * @param services */ public static void setBookmarks( Hashtable params ) { /** Definig rooms group **/ MidletMain.mainFrame.buddyList.roomsGroupItem = new GroupItem( Localization.getMessage( "ROOMS" ) ); MidletMain.mainFrame.buddyList.roomsGroupItem.internalGroupId = GroupItem.GROUP_ROOMS_ID; /** Obtain elements **/ Vector items = ( Vector ) params.get( "BOOKMARKS" ); /** Setting up items **/ setBookmarks( items ); } /** * Showing buddy presence * @param from * @param show * @param priority * @param status */ public static void setPresence( String from, String show, int priority, String status, String caps, String ver, boolean isInvalidBuddy, Hashtable params ) { String clearJid = BuddyList.getClearJid( from ); String resource = BuddyList.getJidResource( from ); LogUtil.outMessage( "Presence: " + from ); /** If this is self presence, changing status in AccountRoot **/ if ( from.equals( AccountRoot.getFullJid() ) ) { AccountRoot.setStatusIndex( StatusUtil.getStatusIndex( show ) ); } else { /** Searching for buddy in roster **/ BuddyItem buddyItem = MidletMain.mainFrame.buddyList.getBuddyItem( clearJid ); /** Checking for buddy item existing in roster **/ if ( buddyItem == null ) { /** Buddy not exist, according to the * RFC 3921 presence must be ignored **/ LogUtil.outMessage( "BuddyItem not exists, according to the RFC 3921, " + "presence must be ignored" ); return; } else { /** Buddy exists **/ LogUtil.outMessage( "Buddy exists" ); Resource t_resource = buddyItem.getResource( resource ); t_resource.setStatusIndex( StatusUtil.getStatusIndex( show ) ); t_resource.setStatusText( status ); t_resource.setCaps( caps ); t_resource.setVer( ver ); buddyItem.setBuddyInvalid( isInvalidBuddy ); /** Updating buddyItem status **/ buddyItem.getStatusIndex(); /** Checking for setting, status and resource usage **/ if ( Settings.isRemoveOfflineResources && ( StatusUtil.getStatusIndex( show ) == StatusUtil.offlineIndex ) && !MidletMain.chatFrame.getBuddyResourceUsed( clearJid, resource ) ) { /** Resource is offline, settings is to * remove offline resource and resource is not used **/ LogUtil.outMessage( "Removing resource: ".concat( resource ) ); buddyItem.removeResource( resource ); } /** Checking for MUC presence information **/ if ( !params.isEmpty() && buddyItem.getInternalType() == BuddyItem.TYPE_ROOM_ITEM ) { /** Creating room instance from buddy item **/ RoomItem roomItem = ( RoomItem ) buddyItem; /** Checking for error code **/ if ( params.containsKey( "ERROR_CAUSE" ) ) { String error_cause = ( String ) params.get( "ERROR_CAUSE" ); Handler.showError( "MUC_".concat( error_cause ) ); } else { /** Obtain affiliation, JID, role and nick **/ String muc_affiliation = null; String muc_jid = null; String muc_role = null; String muc_nick = null; if ( params.containsKey( "AFFILIATION" ) ) { /** Affiliation in MUC **/ muc_affiliation = ( String ) params.get( "AFFILIATION" ); t_resource.setAffiliation( RoomUtil.getAffiliationIndex( muc_affiliation ) ); } if ( params.containsKey( "JID" ) ) { /** JID in MUC **/ muc_jid = ( String ) params.get( "JID" ); t_resource.setJid( muc_jid ); } if ( params.containsKey( "ROLE" ) ) { /** Role in MUC **/ muc_role = ( String ) params.get( "ROLE" ); t_resource.setRole( RoomUtil.getRoleIndex( muc_role ) ); } if ( params.containsKey( "NICK" ) ) { /** Nick in MUC **/ muc_nick = ( String ) params.get( "NICK" ); } if ( params.containsKey( "STATUS_110" ) || ( muc_jid != null && muc_jid.equals( AccountRoot.getFullJid() ) ) ) { /** Inform user that presence refers to itself **/ if ( muc_affiliation != null ) { /** Applying self-affiliation **/ roomItem.setAffiliation( RoomUtil.getAffiliationIndex( muc_affiliation ) ); } /** Checking for role **/ if ( muc_role != null ) { /** Applying self-role **/ roomItem.setRole( RoomUtil.getRoleIndex( muc_role ) ); } } /** Status codes **/ if ( params.containsKey( "STATUS_100" ) ) { /** Inform user that any occupant is * allowed to see the user’s full JID **/ roomItem.setNonAnonimous( true ); } else { /** Room is anonymous **/ roomItem.setNonAnonimous( false ); } if ( params.containsKey( "STATUS_101" ) ) { /** Inform user that his or her affiliation * changed while not in the room **/ showDialog( "INFO", "AFFL_WAS_CHANGED" ); } if ( params.containsKey( "STATUS_102" ) ) { /** Inform occupants that room now shows unavailable members **/ } if ( params.containsKey( "STATUS_103" ) ) { /** Inform occupants that room now does * not show unavailable members **/ } if ( params.containsKey( "STATUS_104" ) ) { /** Inform occupants that a non-privacy-related room, * configuration change has occurred **/ } - if ( ( params.containsKey( "STATUS_110" ) - || ( muc_jid != null - && muc_jid.equals( AccountRoot.getFullJid() ) ) ) - && !params.containsKey( "STATUS_303" ) - && !roomItem.getRoomActive() ) { + if ( ( params.containsKey( "STATUS_110" ) ) + && !params.containsKey( "STATUS_303" ) ) { /** Setting up room active or inactive * if it is not already active **/ + boolean isRoomActive = roomItem.getRoomActive(); if ( roomItem.setRoomActive( t_resource.statusIndex != StatusUtil.offlineIndex ) ) { - /** Handling room entering is complete **/ - Handler.roomEnteringComplete( roomItem, - params.containsKey( "STATUS_201" ), true ); + /** Checking for room became active **/ + if ( !isRoomActive && roomItem.getRoomActive() ) { + /** Handling room entering is complete **/ + Handler.roomEnteringComplete( roomItem, + params.containsKey( "STATUS_201" ), true ); + } } else { /** Hiding wait screen **/ MidletMain.screen.setWaitScreenState( false ); } } if ( params.containsKey( "STATUS_170" ) ) { /** Room logging is enabled **/ } if ( params.containsKey( "STATUS_171" ) ) { /** Room logging is disabled **/ } if ( params.containsKey( "STATUS_172" ) ) { /** Room is now non-anonymous **/ roomItem.setNonAnonimous( true ); } if ( params.containsKey( "STATUS_173" ) ) { /** Room is now semi-anonymous **/ roomItem.setNonAnonimous( false ); } if ( params.containsKey( "STATUS_201" ) ) { /** Room is created **/ } if ( params.containsKey( "STATUS_210" ) ) { /** Inform user that service has assigned or modified, * occupant's room nick **/ } if ( params.containsKey( "STATUS_301" ) ) { /** User is banned **/ roomItem.setResourcesOffline(); /** In this case, user banned, but * status updated for whole room **/ resource = ""; /** Showing error **/ showError( "ROOM_VISITOR_BANNED" ); } if ( params.containsKey( "STATUS_303" ) ) { /** Inform all occupants of new room nickname **/ LogUtil.outMessage( "Inform all occupants of new room nickname" ); LogUtil.outMessage( "room nick: " + roomItem.getRoomNick() ); LogUtil.outMessage( "resource : " + t_resource.resource ); /** Checking for this is our new nick **/ if ( muc_nick.equals( roomItem.getRoomNick() ) ) { /** This is our nick - update bookmark **/ - RoomItem item = new RoomItem( roomItem.getJid(), - roomItem.getNickName(), roomItem.getMinimize(), + RoomItem item = new RoomItem( roomItem.getJid(), + roomItem.getNickName(), roomItem.getMinimize(), roomItem.getAutoJoin() ); /** Updating parameters **/ item.setRoomNick( muc_nick ); item.setRoomPassword( roomItem.getRoomPassword() ); /** Mechanism invocation **/ - Mechanism.sendBookmarksOperation( Mechanism.OPERATION_EDIT, + Mechanism.sendBookmarksOperation( Mechanism.OPERATION_EDIT, roomItem, item, false, true ); } /** Checking for chat tab **/ - ChatTab chatTab = MidletMain.chatFrame.getChatTab( clearJid, + ChatTab chatTab = MidletMain.chatFrame.getChatTab( clearJid, "", false ); if ( chatTab != null ) { /** Check and prepare message **/ - String message = "[p][i][b][c=purple]".concat(resource). + String message = "[p][i][b][c=purple]".concat( resource ). concat( "[/c][/b][/i] " ).concat( Localization.getMessage( "CHANGED_NICK" ) ). concat( " [i][b][c=purple]" ).concat( muc_nick ). concat( "[/c][/b][/i][/p]" ); /** Showing message in chat tab **/ - boolean isTabActive = MidletMain.chatFrame.addChatItem( + boolean isTabActive = MidletMain.chatFrame.addChatItem( chatTab, AccountRoot.generateCookie(), ChatItem.TYPE_PLAIN_MSG, true, resource, message ); if ( !( isTabActive && MidletMain.screen.activeWindow. equals( MidletMain.chatFrame ) ) ) { /** Chat tab is not active or ChatFrame * is not on the screen **/ chatTab.resource.unreadCount++; /** Check for first unread message **/ if ( chatTab.resource.unreadCount == 1 ) { /** Buddy item UI update **/ chatTab.buddyItem.updateUi(); /** Chat tab UI update **/ chatTab.updateUi(); } } } } if ( params.containsKey( "STATUS_307" ) ) { /** User is kicked **/ roomItem.setResourcesOffline(); /** In this case, user banned, but * status updated for whole room **/ resource = ""; /** Showing error **/ showError( "ROOM_VISITOR_KICKED" ); } if ( params.containsKey( "STATUS_321" ) ) { /** Room is members-only and user affiliation changed **/ roomItem.setResourcesOffline(); /** In this case, user banned, but * status updated for whole room **/ resource = ""; /** Showing error **/ showError( "ROOM_MEMBERS_ONLY_AFFL_CHG" ); } if ( params.containsKey( "STATUS_322" ) ) { /** User is non-member in members-only room and kicked out **/ roomItem.setResourcesOffline(); /** In this case, user banned, but * status updated for whole room **/ resource = ""; /** Showing error **/ showError( "ROOM_BECAME_MEMBERS_ONLY" ); } if ( params.containsKey( "STATUS_332" ) ) { /** Inform user that he or she is being removed from the room, * because the MUC service is being shut down **/ roomItem.setResourcesOffline(); /** In this case, user banned, but * status updated for whole room **/ resource = ""; /** Showing error **/ showError( "SYSTEM_SHUTDOWN" ); } } } buddyItem.updateUi(); /** Updating opened chat tab **/ MidletMain.chatFrame.updateTab( clearJid, resource ); } } /** Repainting **/ MainFrame.repaintFrame(); ChatFrame.repaintFrame(); LogUtil.outMessage( "Buddy presence OK" ); } /** * Shows message in chat frame * @param from * @param type * @param id * @param message */ public static void setMessage( String from, String type, String id, String message, String subject ) { String jid = BuddyList.getClearJid( from ); String nickName; String resource; /** Checking for message type to detect resource **/ if ( type.equals( "groupchat" ) ) { resource = ""; } else { resource = BuddyList.getJidResource( from ); } /** Checking for chat tab **/ ChatTab chatTab = MidletMain.chatFrame.getChatTab( jid, resource, false ); if ( chatTab == null ) { /** Searching for buddy **/ BuddyItem buddyItem = MidletMain.mainFrame.buddyList.getBuddyItem( jid ); if ( buddyItem == null ) { LogUtil.outMessage( "No such buddy in roster. " ); /** Creating buddy item **/ buddyItem = MidletMain.mainFrame.buddyList.createTempBuddyItem( jid ); } Resource resourceObject = buddyItem.getResource( resource ); /** There is no opened chat tab, checking for default resource chat **/ ChatTab tempTab = MidletMain.chatFrame.getStandAloneOnlineResourceTab( jid ); if ( tempTab != null && tempTab.resource.resource.equals( "" ) && !tempTab.isMucTab() ) { /** Default empty resource chat found This chat tab must be replaced for incoming resource, because, maybe, it really one alive now? **/ LogUtil.outMessage( "Reassign chat tab from empty to named: ".concat( resource ) ); tempTab.resource = resourceObject; chatTab = tempTab; /** Chat tab UI update **/ chatTab.updateUi(); } else { /** Crating chat tab **/ chatTab = new ChatTab( buddyItem, resourceObject ); MidletMain.chatFrame.addChatTab( chatTab, false ); } } /** Defining nick name and applying subject **/ if ( chatTab.isMucTab() ) { nickName = BuddyList.getJidResource( from ); /** Checking for message is topic **/ if ( subject != null && ( message == null || nickName.length() == 0 ) ) { ( ( RoomItem ) chatTab.buddyItem ).setRoomTopic( subject ); } } else { nickName = chatTab.buddyItem.getNickName(); } /** Check and prepare message **/ message = ChatFrame.checkMessage( nickName, message, subject, chatTab.isMucTab() ); /** Showing message in chat tab **/ boolean isTabActive = MidletMain.chatFrame.addChatItem( chatTab, id, ChatItem.TYPE_PLAIN_MSG, true, nickName, message ); if ( !( isTabActive && MidletMain.screen.activeWindow.equals( MidletMain.chatFrame ) ) ) { /** Chat tab is not active or ChatFrame is not on the screen **/ chatTab.resource.unreadCount++; /** Check for first unread message **/ if ( chatTab.resource.unreadCount == 1 ) { /** Buddy item UI update **/ chatTab.buddyItem.updateUi(); /** Chat tab UI update **/ chatTab.updateUi(); } } /** Repainting **/ MidletMain.screen.repaint(); } /** * Updating nick name for specified JID * @param fullJid * @param nick */ public static void setNickName( String fullJId, String nick ) { String jid = BuddyList.getClearJid( fullJId ); /** Searching for buddy **/ BuddyItem buddyItem = MidletMain.mainFrame.buddyList.getBuddyItem( jid ); if ( buddyItem == null ) { LogUtil.outMessage( "No such buddy in roster: ".concat( jid ) ); } else { /** Setting up nick name **/ buddyItem.setNickName( nick ); buddyItem.updateUi(); /** Repainting **/ MainFrame.repaintFrame(); ChatFrame.repaintFrame(); } } /** User-side connection established event **/ public static void connectedEvent() { /** Changing user theme **/ LogUtil.outMessage( "Connected event" ); Theme.startThemeChange( Settings.themeOfflineResPath, Settings.themeOnlineResPath ); } /** User-side disconnect showing **/ public static void disconnectEvent() { if ( AccountRoot.getStatusIndex() != StatusUtil.offlineIndex ) { LogUtil.outMessage( "Disconnected event" ); /** Updating account status **/ AccountRoot.setStatusIndex( StatusUtil.offlineIndex ); /** Changing roster items status **/ MidletMain.mainFrame.buddyList.setRosterOffline(); MidletMain.chatFrame.updateTabs(); /** Repainting **/ MainFrame.repaintFrame(); ChatFrame.repaintFrame(); /** Changing user theme **/ Theme.startThemeChange( Settings.themeOnlineResPath, Settings.themeOfflineResPath ); } } /** Configures and appends defined register item to the specified popup **/ public static void appendRegisterEvent( PopupItem popupItem, ServiceItem serviceItem ) { serviceItem.getRegisterPopup().name = serviceItem.getJid(); /** Checking for service connected **/ if ( serviceItem.isConnected() || serviceItem.isBuddyInvalid() ) { popupItem.addSubItem( serviceItem.getUnRegisterPopup() ); } else { popupItem.addSubItem( serviceItem.getRegisterPopup() ); } } /** Appends command items to specified popup item **/ public static void appendCommands( final PopupItem parentPopup, Hashtable params ) { /** Defining node name **/ String node = ( String ) params.get( "NODE" ); if ( node != null ) { parentPopup.name = ( String ) node; } /** Cycling items **/ Vector items = ( Vector ) params.get( "ITEMS" ); if ( items != null ) { for ( int c = 0; c < items.size(); c++ ) { final Item item = ( Item ) items.elementAt( c ); PopupItem popupItem = new PopupItem( item.name ) { public void actionPerformed() { /** Showing wait screen **/ MidletMain.screen.setWaitScreenState( true ); LogUtil.outMessage( "Command execute: " + item.node + " for: " + item.jid ); Mechanism.executeCommand( item ); } }; popupItem.name = item.node; parentPopup.addSubItem( popupItem ); } } } /** * Updates rooms frame items * @param roomsBrowseFrame * @param params */ public static void updateRoomsFrame( final RoomsFrame roomsFrame, Hashtable params ) { /** Cycling items **/ Vector items = ( Vector ) params.get( "ITEMS" ); /** Creating new swap vector **/ Vector listItems = new Vector(); /** Create room list item **/ ListItem listItem = new ListItem( Localization.getMessage( "CREATE_ROOM" ) ); listItems.addElement( listItem ); /** Checking for items in not null-type **/ if ( items != null ) { /** Adding all items to listItems **/ for ( int c = 0; c < items.size(); c++ ) { Item item = ( Item ) items.elementAt( c ); listItems.addElement( new DiscoItem( item.name, item.jid ) ); } } /** Applying collected swap **/ roomsFrame.getList().items = listItems; roomsFrame.updateTime = System.currentTimeMillis(); } /** * Creates new temporary room * @param roomIndex * @return RoomItem */ public static RoomItem createTempRoomItem( int roomIndex ) { /** Creating new room item **/ RoomItem roomItem = new RoomItem( String.valueOf( roomIndex ).concat( "@" ).concat( AccountRoot.getRoomHost() ), String.valueOf( roomIndex ), false, false ); roomItem.setRoomNick( AccountRoot.getNickName() ); roomItem.setTemp( true ); roomItem.updateUi(); /** Adding room item to roster **/ MidletMain.mainFrame.buddyList.roomsGroupItem.addChild( roomItem ); return roomItem; } /** * Method for caching rooms frame cause it's weight * @return RoomsFrame */ public static RoomsFrame getRoomsFrame() { /** Checking for rooms frame unexistance **/ if ( MidletMain.roomsFrame == null ) { /** Creating rooms frame instance **/ MidletMain.roomsFrame = new RoomsFrame(); } if ( System.currentTimeMillis() - MidletMain.roomsFrame.updateTime > Settings.roomsUpdateDelay ) { /** Mechanism invocation **/ Mechanism.sendRoomsItemsDiscoveryRequest(); } return MidletMain.roomsFrame; } public static void resetRoomsCache() { /** Checking for rooms frame is initialized **/ if ( MidletMain.roomsFrame != null ) { MidletMain.roomsFrame.resetRoomsCache(); } } /** * Showing rooms frame */ public static void showRoomsFrame() { /** Checking for frame not active now **/ if ( !MidletMain.screen.activeWindow.equals( getRoomsFrame() ) ) { /** Showing rooms frame **/ MidletMain.screen.setActiveWindow( getRoomsFrame() ); } } /** * Creating instace, configurating and showing room more frame * @param params */ public static void showRoomMoreFrame( DiscoItem discoItem, Hashtable params ) { /** Creating frame instance **/ RoomMoreFrame roomMoreFrame = new RoomMoreFrame( discoItem ); /** Checcking for form exist **/ if ( params.containsKey( "FORM" ) ) { /** Setting up main objects **/ roomMoreFrame.setMainObjects( ( ( Form ) params.get( "FORM" ) ).objects ); } else { roomMoreFrame.setMainObjects( new Vector() ); } /** Obtain keys enumeration **/ Enumeration keys = params.keys(); /** Variables **/ String key; /** Cycling all keys **/ while ( keys.hasMoreElements() ) { key = ( String ) keys.nextElement(); /** Checking for form key **/ if ( key.equals( "FORM" ) ) { /** Form exist **/ } else if ( key.equals( "IDENT_CATG" ) ) { LogUtil.outMessage( key.concat( " = " ).concat( ( String ) params.get( key ) ) ); } else if ( key.equals( "IDENT_TYPE" ) ) { LogUtil.outMessage( key.concat( " = " ).concat( ( String ) params.get( key ) ) ); } else if ( key.equals( "IDENT_NAME" ) ) { LogUtil.outMessage( key.concat( " = " ).concat( ( String ) params.get( key ) ) ); roomMoreFrame.setHeader( ( String ) params.get( key ) ); } else { LogUtil.outMessage( "feature: ".concat( key ) ); roomMoreFrame.addFeatureItem( key ); } } /** Showing frame **/ MidletMain.screen.setActiveWindow( roomMoreFrame ); } /** * Room entering is complete event * @param roomItem * @param isCreated * @param isCleanChat */ public static void roomEnteringComplete( RoomItem roomItem, boolean isCreated, boolean isCleanChat ) { /** Checking for room item temp status **/ if ( isCreated ) { /** Loading room configuration frame */ Mechanism.configureRoomRequest( roomItem, true ); } else { /** Opening room in chat frame **/ MidletMain.mainFrame.openDialog( roomItem, roomItem.getResource( "" ), isCleanChat ); /** Hiding wait screen **/ MidletMain.screen.setWaitScreenState( false ); } } public static void showRoomVisitorsListEditFrame( RoomItem roomItem, String affiliation, Vector items ) { /** Creating frame instance **/ RoomVisitorsEditFrame roomVisitorsEditFrame = new RoomVisitorsEditFrame( roomItem, affiliation, items ); /** Disabling wait screen **/ MidletMain.screen.setWaitScreenState( false ); /** Setting up frame as current **/ MidletMain.screen.setActiveWindow( roomVisitorsEditFrame ); } /** * Closing all opened chat tabs of this jid * and removing buddy item if it temporary * Returns boolean flag - true if buddy permanent, false - if not * @param jid * @return boolean */ public static boolean closeOpenedTabs( BuddyItem buddyItem ) { /** Removing tabs **/ MidletMain.chatFrame.removeChatTabs( buddyItem.getJid() ); /** Checking for item is temporary **/ if ( buddyItem.getTemp() ) { /** Removing buddy from groups **/ MidletMain.mainFrame.buddyList.removeBuddyFromGroups( buddyItem ); return false; } return true; } /** * Checks for bookmark existance and adds if not exist * @param discoItem */ public static RoomItem getBookmark( DiscoItem discoItem ) { /** Checking for bookmarks existance **/ if ( getBuddyList().roomsGroupItem.getChildsCount() > 0 ) { /** Obtain rooms **/ Vector items = getBuddyList().roomsGroupItem.getChilds(); /** Cycling all rooms **/ for ( int c = 0; c < items.size(); c++ ) { RoomItem roomItem = ( RoomItem ) items.elementAt( c ); /** Checking for jid equals **/ if ( roomItem.getJid().equals( discoItem.getJid() ) ) { return roomItem; } } } /** No such room item **/ return null; } /** * Returns buddy list * @return BuddyList */ public static BuddyList getBuddyList() { return MidletMain.mainFrame.buddyList; } /** * Returns buddy items JID in array by items specified host * @param serviceHost * @return String[] */ public static String[] getServiceItems( String serviceHost ) { return MidletMain.mainFrame.buddyList.getServiceItems( serviceHost ); } /** * Sends pong to ping initiator * @param xmlWriter * @param from * @param id */ public static void sendPong( Session session, String from, String id ) { /** Sending pong via mechanism **/ Mechanism.sendPong( session, from, id ); } /** * Shows main frame popup item on right soft * @param popupItem */ public static void showMainFrameElementPopup( PopupItem popupItem ) { /** Showing right soft **/ MidletMain.mainFrame.soft.rightSoft = popupItem; MidletMain.mainFrame.soft.setRightSoftPressed( true ); /** Hiding wait screen state **/ MidletMain.screen.setWaitScreenState( false ); } /** * Shows command frame for specified item and form * @param item * @param form */ public static void showCommandFrame( Item item, Form form, PopupItem rightSoft ) { if ( form.objects == null || ( form.status != null && form.status.equals( "completed" ) && form.objects.isEmpty() ) || form.objects.isEmpty() ) { MidletMain.screen.setActiveWindow( MidletMain.mainFrame ); } else { CommandFrame commandFrame = new CommandFrame( item, rightSoft ); commandFrame.setFormData( form ); MidletMain.screen.setActiveWindow( commandFrame ); } /** Hiding wait notify **/ MidletMain.screen.setWaitScreenState( false ); } /** * Showing buddy add frame by specified host, description and prompt * @param serviceHost * @param desc * @param prompt */ public static void showBuddyAddFrame( String serviceHost, String desc, String prompt ) { /** Showing buddy add frame **/ MidletMain.screen.setActiveWindow( new BuddyAddFrame( serviceHost, desc, prompt ) ); /** Hiding wait notify **/ MidletMain.screen.setWaitScreenState( false ); } /** * Checking for active window, showing main * frame and disabling wait screen state */ public static void showMainFrame() { /** Switching to main frame window **/ showNextFrame( MidletMain.mainFrame ); } /** * Checking for active window, showing specified * frame and disabling wait screen state */ public static void showNextFrame( Window nextFrame ) { /** Checking for active window **/ if ( !MidletMain.screen.activeWindow.equals( nextFrame ) ) { /** Showing main frame **/ MidletMain.screen.setActiveWindow( nextFrame ); } /** Hiding wait screen state **/ MidletMain.screen.setWaitScreenState( false ); /** Repaint main frame **/ MidletMain.screen.repaint(); } /** * Checking for online active connection to server * @return boolean */ public static boolean sureIsOnline() { /** Checking for online status **/ if ( AccountRoot.isOffline() ) { Handler.showError( "ONLINE_REQUIRED" ); return false; } return true; } /** * Checking for main frame is active * window and sending repaint request */ public static void repaintMainFrame() { /** Checking for main frame opened **/ if ( MidletMain.screen.activeWindow.equals( MidletMain.mainFrame ) ) { /** Repainting main frame **/ MidletMain.screen.repaint(); } } /** * All-in-one subscription mechanisms, followed specified policy * @param jid * @param actionType */ public static void showSubscriptionAction( final String jid, final String actionType ) { /** Checking for service type of JID **/ if ( jid.indexOf( '@' ) == -1 ) { /** Checking for subscription action type **/ if ( actionType.equals( "SUBSCRIBE" ) ) { /** Automatically approve request **/ Mechanism.sendSubscriptionApprove( jid ); /** Automatically generating subscription request **/ Mechanism.sendSubscriptionRequest( jid ); } return; } /** Searching for buddy **/ if ( MidletMain.mainFrame.buddyList.getBuddyItem( jid ) == null ) { LogUtil.outMessage( "No such buddy in roster. " ); /** Creating buddy item **/ MidletMain.mainFrame.buddyList.createTempBuddyItem( jid ); } /** Checking for subscription action type **/ if ( actionType.equals( "SUBSCRIBED" ) ) { /** Checking for ignore subscription approve messages **/ if ( Settings.isHideSubscriptionApproveMessage ) { /** Nothing to do in this case **/ return; } } else if ( actionType.equals( "SUBSCRIBE" ) ) { /** Checking for automatic subscription requests approve **/ if ( Settings.isAutomatedSubscriptionApprove ) { LogUtil.outMessage( "Sending subscription approve to buddy: ".concat( jid ) ); /** Sending subscription approve **/ Mechanism.sendSubscriptionApprove( jid ); /** Checking subscription status **/ BuddyItem buddyItem = MidletMain.mainFrame.buddyList.getBuddyItem( jid ); /** Checking for buddy item existance and subscription type **/ if ( buddyItem == null || buddyItem.getSubscription().equals( "none" ) || buddyItem.getSubscription().equals( "from" ) ) { /** Sending subscription request **/ LogUtil.outMessage( "Sending subscription request to: ".concat( jid ) ); Mechanism.sendSubscriptionRequest( jid ); } return; } } /** Obtain window **/ final Window window = MidletMain.screen.activeWindow; /** Creating soft and dialog **/ final Soft dialogSoft = new Soft( MidletMain.screen ); /** Left action soft **/ dialogSoft.leftSoft = new PopupItem( Localization.getMessage( "CLOSE" ) ) { public void actionPerformed() { window.closeDialog(); } }; /** Right action soft **/ dialogSoft.rightSoft = new PopupItem( Localization.getMessage( actionType.concat( "_ACTION" ) ) ) { public void actionPerformed() { /** Checking for action type **/ if ( actionType.equals( "SUBSCRIBE" ) ) { Mechanism.sendSubscriptionApprove( jid ); } else if ( actionType.equals( "UNSUBSCRIBED" ) ) { Mechanism.sendSubscriptionReject( jid ); } else { /** Nothing to do in this case **/ return; } /** Closing dialog after action **/ dialogSoft.leftSoft.actionPerformed(); } }; /** Setting up messages **/ String title = actionType.concat( "_TITILE" ); String message = Localization.getMessage( actionType.concat( "_MESSAGE" ) ).concat( ": " ).concat( jid ). concat( "\n" ). concat( Localization.getMessage( actionType.concat( "_COMMENT" ) ) ); /** Showing dialog **/ showDialog( window, dialogSoft, title, message ); } /** * Checking for buddy used in chat * frame and storing it into temp group * @param buddyItem */ public static void checkBuddyUsage( BuddyItem buddyItem ) { /** Checking for opened dialogs **/ if ( MidletMain.chatFrame.getBuddyResourceUsed( buddyItem.getJid(), null ) ) { /** Setting up "temp" flag **/ buddyItem.setTemp( true ); /** Carry this buddy in temporary group **/ MidletMain.mainFrame.buddyList.tempGroupItem.addChild( buddyItem ); } } /** * Sending roster push result * @param iqId */ public static void sendPushResult( String iqId ) { Mechanism.sendIqResult( iqId ); } public static void sendDiscoInfo( String cookie, String jid ) { /** Sending disco info by mechanism **/ Mechanism.sendDiscoInfo( cookie, jid ); } public static void sendLastActivity( String cookie, String jid ) { /** Sending last activity by mechanism **/ Mechanism.sendLastActivity( cookie, jid ); } public static void sendEntityTime( String cookie, String jid ) { /** Sending entity time by mechanism **/ Mechanism.sendEntityTime( cookie, jid ); } public static void sendVersion( String cookie, String jid ) { /** Sending version by mechanism **/ Mechanism.sendVersion( cookie, jid ); } public static void sendTime() { } public static void showError( String errorCause ) { /** Checking error **/ if ( errorCause.equals( "" ) ) { /** Cause unknown **/ LogUtil.outMessage( "Cause unknown" ); errorCause = "CAUSE_UNKNOWN"; } /** Showing dialog **/ showDialog( "ERROR", errorCause ); } /** * Shows error in active window * @param errorCause * @param window */ public static void showDialog( String title, String message ) { /** Obtain window **/ final Window window = MidletMain.screen.activeWindow; /** Hiding wait screen state **/ MidletMain.screen.setWaitScreenState( false ); /** Creating soft and dialog **/ Soft dialogSoft = new Soft( MidletMain.screen ); dialogSoft.leftSoft = new PopupItem( Localization.getMessage( "CLOSE" ) ) { public void actionPerformed() { window.closeDialog(); } }; /** Showing dialog **/ showDialog( window, dialogSoft, title, Localization.getMessage( message ) ); } /** * Showing frame dialog for specified window, soft, * title (not localized) and message (localized) * @param window * @param dialogSoft * @param title * @param message */ public static void showDialog( Window window, Soft dialogSoft, String title, String message ) { /** Hiding wait screen state **/ MidletMain.screen.setWaitScreenState( false ); /** Creating soft and dialog **/ Dialog resultDialog = new Dialog( MidletMain.screen, dialogSoft, Localization.getMessage( title ), message ); /** Showing new dialog **/ window.showDialog( resultDialog ); } }
false
true
public static void setPresence( String from, String show, int priority, String status, String caps, String ver, boolean isInvalidBuddy, Hashtable params ) { String clearJid = BuddyList.getClearJid( from ); String resource = BuddyList.getJidResource( from ); LogUtil.outMessage( "Presence: " + from ); /** If this is self presence, changing status in AccountRoot **/ if ( from.equals( AccountRoot.getFullJid() ) ) { AccountRoot.setStatusIndex( StatusUtil.getStatusIndex( show ) ); } else { /** Searching for buddy in roster **/ BuddyItem buddyItem = MidletMain.mainFrame.buddyList.getBuddyItem( clearJid ); /** Checking for buddy item existing in roster **/ if ( buddyItem == null ) { /** Buddy not exist, according to the * RFC 3921 presence must be ignored **/ LogUtil.outMessage( "BuddyItem not exists, according to the RFC 3921, " + "presence must be ignored" ); return; } else { /** Buddy exists **/ LogUtil.outMessage( "Buddy exists" ); Resource t_resource = buddyItem.getResource( resource ); t_resource.setStatusIndex( StatusUtil.getStatusIndex( show ) ); t_resource.setStatusText( status ); t_resource.setCaps( caps ); t_resource.setVer( ver ); buddyItem.setBuddyInvalid( isInvalidBuddy ); /** Updating buddyItem status **/ buddyItem.getStatusIndex(); /** Checking for setting, status and resource usage **/ if ( Settings.isRemoveOfflineResources && ( StatusUtil.getStatusIndex( show ) == StatusUtil.offlineIndex ) && !MidletMain.chatFrame.getBuddyResourceUsed( clearJid, resource ) ) { /** Resource is offline, settings is to * remove offline resource and resource is not used **/ LogUtil.outMessage( "Removing resource: ".concat( resource ) ); buddyItem.removeResource( resource ); } /** Checking for MUC presence information **/ if ( !params.isEmpty() && buddyItem.getInternalType() == BuddyItem.TYPE_ROOM_ITEM ) { /** Creating room instance from buddy item **/ RoomItem roomItem = ( RoomItem ) buddyItem; /** Checking for error code **/ if ( params.containsKey( "ERROR_CAUSE" ) ) { String error_cause = ( String ) params.get( "ERROR_CAUSE" ); Handler.showError( "MUC_".concat( error_cause ) ); } else { /** Obtain affiliation, JID, role and nick **/ String muc_affiliation = null; String muc_jid = null; String muc_role = null; String muc_nick = null; if ( params.containsKey( "AFFILIATION" ) ) { /** Affiliation in MUC **/ muc_affiliation = ( String ) params.get( "AFFILIATION" ); t_resource.setAffiliation( RoomUtil.getAffiliationIndex( muc_affiliation ) ); } if ( params.containsKey( "JID" ) ) { /** JID in MUC **/ muc_jid = ( String ) params.get( "JID" ); t_resource.setJid( muc_jid ); } if ( params.containsKey( "ROLE" ) ) { /** Role in MUC **/ muc_role = ( String ) params.get( "ROLE" ); t_resource.setRole( RoomUtil.getRoleIndex( muc_role ) ); } if ( params.containsKey( "NICK" ) ) { /** Nick in MUC **/ muc_nick = ( String ) params.get( "NICK" ); } if ( params.containsKey( "STATUS_110" ) || ( muc_jid != null && muc_jid.equals( AccountRoot.getFullJid() ) ) ) { /** Inform user that presence refers to itself **/ if ( muc_affiliation != null ) { /** Applying self-affiliation **/ roomItem.setAffiliation( RoomUtil.getAffiliationIndex( muc_affiliation ) ); } /** Checking for role **/ if ( muc_role != null ) { /** Applying self-role **/ roomItem.setRole( RoomUtil.getRoleIndex( muc_role ) ); } } /** Status codes **/ if ( params.containsKey( "STATUS_100" ) ) { /** Inform user that any occupant is * allowed to see the user’s full JID **/ roomItem.setNonAnonimous( true ); } else { /** Room is anonymous **/ roomItem.setNonAnonimous( false ); } if ( params.containsKey( "STATUS_101" ) ) { /** Inform user that his or her affiliation * changed while not in the room **/ showDialog( "INFO", "AFFL_WAS_CHANGED" ); } if ( params.containsKey( "STATUS_102" ) ) { /** Inform occupants that room now shows unavailable members **/ } if ( params.containsKey( "STATUS_103" ) ) { /** Inform occupants that room now does * not show unavailable members **/ } if ( params.containsKey( "STATUS_104" ) ) { /** Inform occupants that a non-privacy-related room, * configuration change has occurred **/ } if ( ( params.containsKey( "STATUS_110" ) || ( muc_jid != null && muc_jid.equals( AccountRoot.getFullJid() ) ) ) && !params.containsKey( "STATUS_303" ) && !roomItem.getRoomActive() ) { /** Setting up room active or inactive * if it is not already active **/ if ( roomItem.setRoomActive( t_resource.statusIndex != StatusUtil.offlineIndex ) ) { /** Handling room entering is complete **/ Handler.roomEnteringComplete( roomItem, params.containsKey( "STATUS_201" ), true ); } else { /** Hiding wait screen **/ MidletMain.screen.setWaitScreenState( false ); } } if ( params.containsKey( "STATUS_170" ) ) { /** Room logging is enabled **/ } if ( params.containsKey( "STATUS_171" ) ) { /** Room logging is disabled **/ } if ( params.containsKey( "STATUS_172" ) ) { /** Room is now non-anonymous **/ roomItem.setNonAnonimous( true ); } if ( params.containsKey( "STATUS_173" ) ) { /** Room is now semi-anonymous **/ roomItem.setNonAnonimous( false ); } if ( params.containsKey( "STATUS_201" ) ) { /** Room is created **/ } if ( params.containsKey( "STATUS_210" ) ) { /** Inform user that service has assigned or modified, * occupant's room nick **/ } if ( params.containsKey( "STATUS_301" ) ) { /** User is banned **/ roomItem.setResourcesOffline(); /** In this case, user banned, but * status updated for whole room **/ resource = ""; /** Showing error **/ showError( "ROOM_VISITOR_BANNED" ); } if ( params.containsKey( "STATUS_303" ) ) { /** Inform all occupants of new room nickname **/ LogUtil.outMessage( "Inform all occupants of new room nickname" ); LogUtil.outMessage( "room nick: " + roomItem.getRoomNick() ); LogUtil.outMessage( "resource : " + t_resource.resource ); /** Checking for this is our new nick **/ if ( muc_nick.equals( roomItem.getRoomNick() ) ) { /** This is our nick - update bookmark **/ RoomItem item = new RoomItem( roomItem.getJid(), roomItem.getNickName(), roomItem.getMinimize(), roomItem.getAutoJoin() ); /** Updating parameters **/ item.setRoomNick( muc_nick ); item.setRoomPassword( roomItem.getRoomPassword() ); /** Mechanism invocation **/ Mechanism.sendBookmarksOperation( Mechanism.OPERATION_EDIT, roomItem, item, false, true ); } /** Checking for chat tab **/ ChatTab chatTab = MidletMain.chatFrame.getChatTab( clearJid, "", false ); if ( chatTab != null ) { /** Check and prepare message **/ String message = "[p][i][b][c=purple]".concat(resource). concat( "[/c][/b][/i] " ).concat( Localization.getMessage( "CHANGED_NICK" ) ). concat( " [i][b][c=purple]" ).concat( muc_nick ). concat( "[/c][/b][/i][/p]" ); /** Showing message in chat tab **/ boolean isTabActive = MidletMain.chatFrame.addChatItem( chatTab, AccountRoot.generateCookie(), ChatItem.TYPE_PLAIN_MSG, true, resource, message ); if ( !( isTabActive && MidletMain.screen.activeWindow. equals( MidletMain.chatFrame ) ) ) { /** Chat tab is not active or ChatFrame * is not on the screen **/ chatTab.resource.unreadCount++; /** Check for first unread message **/ if ( chatTab.resource.unreadCount == 1 ) { /** Buddy item UI update **/ chatTab.buddyItem.updateUi(); /** Chat tab UI update **/ chatTab.updateUi(); } } } } if ( params.containsKey( "STATUS_307" ) ) { /** User is kicked **/ roomItem.setResourcesOffline(); /** In this case, user banned, but * status updated for whole room **/ resource = ""; /** Showing error **/ showError( "ROOM_VISITOR_KICKED" ); } if ( params.containsKey( "STATUS_321" ) ) { /** Room is members-only and user affiliation changed **/ roomItem.setResourcesOffline(); /** In this case, user banned, but * status updated for whole room **/ resource = ""; /** Showing error **/ showError( "ROOM_MEMBERS_ONLY_AFFL_CHG" ); } if ( params.containsKey( "STATUS_322" ) ) { /** User is non-member in members-only room and kicked out **/ roomItem.setResourcesOffline(); /** In this case, user banned, but * status updated for whole room **/ resource = ""; /** Showing error **/ showError( "ROOM_BECAME_MEMBERS_ONLY" ); } if ( params.containsKey( "STATUS_332" ) ) { /** Inform user that he or she is being removed from the room, * because the MUC service is being shut down **/ roomItem.setResourcesOffline(); /** In this case, user banned, but * status updated for whole room **/ resource = ""; /** Showing error **/ showError( "SYSTEM_SHUTDOWN" ); } } } buddyItem.updateUi(); /** Updating opened chat tab **/ MidletMain.chatFrame.updateTab( clearJid, resource ); } } /** Repainting **/ MainFrame.repaintFrame(); ChatFrame.repaintFrame(); LogUtil.outMessage( "Buddy presence OK" ); }
public static void setPresence( String from, String show, int priority, String status, String caps, String ver, boolean isInvalidBuddy, Hashtable params ) { String clearJid = BuddyList.getClearJid( from ); String resource = BuddyList.getJidResource( from ); LogUtil.outMessage( "Presence: " + from ); /** If this is self presence, changing status in AccountRoot **/ if ( from.equals( AccountRoot.getFullJid() ) ) { AccountRoot.setStatusIndex( StatusUtil.getStatusIndex( show ) ); } else { /** Searching for buddy in roster **/ BuddyItem buddyItem = MidletMain.mainFrame.buddyList.getBuddyItem( clearJid ); /** Checking for buddy item existing in roster **/ if ( buddyItem == null ) { /** Buddy not exist, according to the * RFC 3921 presence must be ignored **/ LogUtil.outMessage( "BuddyItem not exists, according to the RFC 3921, " + "presence must be ignored" ); return; } else { /** Buddy exists **/ LogUtil.outMessage( "Buddy exists" ); Resource t_resource = buddyItem.getResource( resource ); t_resource.setStatusIndex( StatusUtil.getStatusIndex( show ) ); t_resource.setStatusText( status ); t_resource.setCaps( caps ); t_resource.setVer( ver ); buddyItem.setBuddyInvalid( isInvalidBuddy ); /** Updating buddyItem status **/ buddyItem.getStatusIndex(); /** Checking for setting, status and resource usage **/ if ( Settings.isRemoveOfflineResources && ( StatusUtil.getStatusIndex( show ) == StatusUtil.offlineIndex ) && !MidletMain.chatFrame.getBuddyResourceUsed( clearJid, resource ) ) { /** Resource is offline, settings is to * remove offline resource and resource is not used **/ LogUtil.outMessage( "Removing resource: ".concat( resource ) ); buddyItem.removeResource( resource ); } /** Checking for MUC presence information **/ if ( !params.isEmpty() && buddyItem.getInternalType() == BuddyItem.TYPE_ROOM_ITEM ) { /** Creating room instance from buddy item **/ RoomItem roomItem = ( RoomItem ) buddyItem; /** Checking for error code **/ if ( params.containsKey( "ERROR_CAUSE" ) ) { String error_cause = ( String ) params.get( "ERROR_CAUSE" ); Handler.showError( "MUC_".concat( error_cause ) ); } else { /** Obtain affiliation, JID, role and nick **/ String muc_affiliation = null; String muc_jid = null; String muc_role = null; String muc_nick = null; if ( params.containsKey( "AFFILIATION" ) ) { /** Affiliation in MUC **/ muc_affiliation = ( String ) params.get( "AFFILIATION" ); t_resource.setAffiliation( RoomUtil.getAffiliationIndex( muc_affiliation ) ); } if ( params.containsKey( "JID" ) ) { /** JID in MUC **/ muc_jid = ( String ) params.get( "JID" ); t_resource.setJid( muc_jid ); } if ( params.containsKey( "ROLE" ) ) { /** Role in MUC **/ muc_role = ( String ) params.get( "ROLE" ); t_resource.setRole( RoomUtil.getRoleIndex( muc_role ) ); } if ( params.containsKey( "NICK" ) ) { /** Nick in MUC **/ muc_nick = ( String ) params.get( "NICK" ); } if ( params.containsKey( "STATUS_110" ) || ( muc_jid != null && muc_jid.equals( AccountRoot.getFullJid() ) ) ) { /** Inform user that presence refers to itself **/ if ( muc_affiliation != null ) { /** Applying self-affiliation **/ roomItem.setAffiliation( RoomUtil.getAffiliationIndex( muc_affiliation ) ); } /** Checking for role **/ if ( muc_role != null ) { /** Applying self-role **/ roomItem.setRole( RoomUtil.getRoleIndex( muc_role ) ); } } /** Status codes **/ if ( params.containsKey( "STATUS_100" ) ) { /** Inform user that any occupant is * allowed to see the user’s full JID **/ roomItem.setNonAnonimous( true ); } else { /** Room is anonymous **/ roomItem.setNonAnonimous( false ); } if ( params.containsKey( "STATUS_101" ) ) { /** Inform user that his or her affiliation * changed while not in the room **/ showDialog( "INFO", "AFFL_WAS_CHANGED" ); } if ( params.containsKey( "STATUS_102" ) ) { /** Inform occupants that room now shows unavailable members **/ } if ( params.containsKey( "STATUS_103" ) ) { /** Inform occupants that room now does * not show unavailable members **/ } if ( params.containsKey( "STATUS_104" ) ) { /** Inform occupants that a non-privacy-related room, * configuration change has occurred **/ } if ( ( params.containsKey( "STATUS_110" ) ) && !params.containsKey( "STATUS_303" ) ) { /** Setting up room active or inactive * if it is not already active **/ boolean isRoomActive = roomItem.getRoomActive(); if ( roomItem.setRoomActive( t_resource.statusIndex != StatusUtil.offlineIndex ) ) { /** Checking for room became active **/ if ( !isRoomActive && roomItem.getRoomActive() ) { /** Handling room entering is complete **/ Handler.roomEnteringComplete( roomItem, params.containsKey( "STATUS_201" ), true ); } } else { /** Hiding wait screen **/ MidletMain.screen.setWaitScreenState( false ); } } if ( params.containsKey( "STATUS_170" ) ) { /** Room logging is enabled **/ } if ( params.containsKey( "STATUS_171" ) ) { /** Room logging is disabled **/ } if ( params.containsKey( "STATUS_172" ) ) { /** Room is now non-anonymous **/ roomItem.setNonAnonimous( true ); } if ( params.containsKey( "STATUS_173" ) ) { /** Room is now semi-anonymous **/ roomItem.setNonAnonimous( false ); } if ( params.containsKey( "STATUS_201" ) ) { /** Room is created **/ } if ( params.containsKey( "STATUS_210" ) ) { /** Inform user that service has assigned or modified, * occupant's room nick **/ } if ( params.containsKey( "STATUS_301" ) ) { /** User is banned **/ roomItem.setResourcesOffline(); /** In this case, user banned, but * status updated for whole room **/ resource = ""; /** Showing error **/ showError( "ROOM_VISITOR_BANNED" ); } if ( params.containsKey( "STATUS_303" ) ) { /** Inform all occupants of new room nickname **/ LogUtil.outMessage( "Inform all occupants of new room nickname" ); LogUtil.outMessage( "room nick: " + roomItem.getRoomNick() ); LogUtil.outMessage( "resource : " + t_resource.resource ); /** Checking for this is our new nick **/ if ( muc_nick.equals( roomItem.getRoomNick() ) ) { /** This is our nick - update bookmark **/ RoomItem item = new RoomItem( roomItem.getJid(), roomItem.getNickName(), roomItem.getMinimize(), roomItem.getAutoJoin() ); /** Updating parameters **/ item.setRoomNick( muc_nick ); item.setRoomPassword( roomItem.getRoomPassword() ); /** Mechanism invocation **/ Mechanism.sendBookmarksOperation( Mechanism.OPERATION_EDIT, roomItem, item, false, true ); } /** Checking for chat tab **/ ChatTab chatTab = MidletMain.chatFrame.getChatTab( clearJid, "", false ); if ( chatTab != null ) { /** Check and prepare message **/ String message = "[p][i][b][c=purple]".concat( resource ). concat( "[/c][/b][/i] " ).concat( Localization.getMessage( "CHANGED_NICK" ) ). concat( " [i][b][c=purple]" ).concat( muc_nick ). concat( "[/c][/b][/i][/p]" ); /** Showing message in chat tab **/ boolean isTabActive = MidletMain.chatFrame.addChatItem( chatTab, AccountRoot.generateCookie(), ChatItem.TYPE_PLAIN_MSG, true, resource, message ); if ( !( isTabActive && MidletMain.screen.activeWindow. equals( MidletMain.chatFrame ) ) ) { /** Chat tab is not active or ChatFrame * is not on the screen **/ chatTab.resource.unreadCount++; /** Check for first unread message **/ if ( chatTab.resource.unreadCount == 1 ) { /** Buddy item UI update **/ chatTab.buddyItem.updateUi(); /** Chat tab UI update **/ chatTab.updateUi(); } } } } if ( params.containsKey( "STATUS_307" ) ) { /** User is kicked **/ roomItem.setResourcesOffline(); /** In this case, user banned, but * status updated for whole room **/ resource = ""; /** Showing error **/ showError( "ROOM_VISITOR_KICKED" ); } if ( params.containsKey( "STATUS_321" ) ) { /** Room is members-only and user affiliation changed **/ roomItem.setResourcesOffline(); /** In this case, user banned, but * status updated for whole room **/ resource = ""; /** Showing error **/ showError( "ROOM_MEMBERS_ONLY_AFFL_CHG" ); } if ( params.containsKey( "STATUS_322" ) ) { /** User is non-member in members-only room and kicked out **/ roomItem.setResourcesOffline(); /** In this case, user banned, but * status updated for whole room **/ resource = ""; /** Showing error **/ showError( "ROOM_BECAME_MEMBERS_ONLY" ); } if ( params.containsKey( "STATUS_332" ) ) { /** Inform user that he or she is being removed from the room, * because the MUC service is being shut down **/ roomItem.setResourcesOffline(); /** In this case, user banned, but * status updated for whole room **/ resource = ""; /** Showing error **/ showError( "SYSTEM_SHUTDOWN" ); } } } buddyItem.updateUi(); /** Updating opened chat tab **/ MidletMain.chatFrame.updateTab( clearJid, resource ); } } /** Repainting **/ MainFrame.repaintFrame(); ChatFrame.repaintFrame(); LogUtil.outMessage( "Buddy presence OK" ); }
diff --git a/src_new/org/argouml/uml/ui/ActionActivityDiagram.java b/src_new/org/argouml/uml/ui/ActionActivityDiagram.java index 0380984..1ea7933 100644 --- a/src_new/org/argouml/uml/ui/ActionActivityDiagram.java +++ b/src_new/org/argouml/uml/ui/ActionActivityDiagram.java @@ -1,95 +1,96 @@ // Copyright (c) 1996-01 The Regents of the University of California. All // Rights Reserved. Permission to use, copy, modify, and distribute this // software and its documentation without fee, and without a written // agreement is hereby granted, provided that the above copyright notice // and this paragraph appear in all copies. This software program and // documentation are copyrighted by The Regents of the University of // California. The software program and documentation are supplied "AS // IS", without any accompanying services from The Regents. The Regents // does not warrant that the operation of the program will be // uninterrupted or error-free. The end-user understands that the program // was developed for research purposes and is advised not to rely // exclusively on the program for any reason. IN NO EVENT SHALL THE // UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, // SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, // ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF // THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE // PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF // CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, // UPDATES, ENHANCEMENTS, OR MODIFICATIONS. package org.argouml.uml.ui; import org.argouml.kernel.*; import org.argouml.ui.*; import org.argouml.uml.*; import org.argouml.uml.diagram.activity.ui.*; import ru.novosoft.uml.foundation.core.*; import ru.novosoft.uml.behavior.use_cases.*; import ru.novosoft.uml.behavior.state_machines.*; import ru.novosoft.uml.behavior.activity_graphs.*; import java.awt.event.*; import java.beans.*; import javax.swing.JOptionPane; public class ActionActivityDiagram extends UMLChangeAction { //////////////////////////////////////////////////////////////// // static variables public static ActionActivityDiagram SINGLETON = new ActionActivityDiagram(); //////////////////////////////////////////////////////////////// // constructors public ActionActivityDiagram() { super("ActivityDiagram"); } //////////////////////////////////////////////////////////////// // main methods public void actionPerformed(ActionEvent ae) { ProjectBrowser pb = ProjectBrowser.TheInstance; Project p = pb.getProject(); try { - MNamespace ns=(MNamespace)pb.getDetailsTarget(); - if (!((ns instanceof MUseCase) || (ns instanceof MClass))) { + MModelElement me = (MModelElement)pb.getDetailsTarget(); + if (!((me instanceof MNamespace) && ((me instanceof MUseCase) || (me instanceof MClass)))) { JOptionPane.showMessageDialog(null, "You need to have a class or use case as your target in order to\nspecify for what you want to define a behaviour for.", "Warning", JOptionPane.WARNING_MESSAGE); return; }; + MNamespace ns=(MNamespace)me; String contextNameStr = ns.getName(); if (contextNameStr == null) contextNameStr = "untitled"; MActivityGraph am = new MActivityGraphImpl(); am.setUUID(UUIDManager.SINGLETON.getNewUUID()); am.setName(contextNameStr + "ActivityGraph"); MCompositeState cs = new MCompositeStateImpl(); cs.setName("activities_top"); //cs.setNamespace(ns); am.setNamespace(ns); am.setTop(cs); ns.addBehavior(am); UMLActivityDiagram d = new UMLActivityDiagram(ns, am); p.addMember(d); ProjectBrowser.TheInstance.getNavPane().addToHistory(d); pb.setTarget(d); } catch (PropertyVetoException pve) { System.out.println("PropertyVetoException in ActionActivityDiagram"); } super.actionPerformed(ae); } public boolean shouldBeEnabled() { return true; // ProjectBrowser pb = ProjectBrowser.TheInstance; // Project p = pb.getProject(); // Object target = pb.getDetailsTarget(); // return super.shouldBeEnabled() && p != null && // ((target instanceof MUseCase)||(target instanceof MClass)); // or MOperation } } /* end class ActionActivityDiagram */
false
true
public void actionPerformed(ActionEvent ae) { ProjectBrowser pb = ProjectBrowser.TheInstance; Project p = pb.getProject(); try { MNamespace ns=(MNamespace)pb.getDetailsTarget(); if (!((ns instanceof MUseCase) || (ns instanceof MClass))) { JOptionPane.showMessageDialog(null, "You need to have a class or use case as your target in order to\nspecify for what you want to define a behaviour for.", "Warning", JOptionPane.WARNING_MESSAGE); return; }; String contextNameStr = ns.getName(); if (contextNameStr == null) contextNameStr = "untitled"; MActivityGraph am = new MActivityGraphImpl(); am.setUUID(UUIDManager.SINGLETON.getNewUUID()); am.setName(contextNameStr + "ActivityGraph"); MCompositeState cs = new MCompositeStateImpl(); cs.setName("activities_top"); //cs.setNamespace(ns); am.setNamespace(ns); am.setTop(cs); ns.addBehavior(am); UMLActivityDiagram d = new UMLActivityDiagram(ns, am); p.addMember(d); ProjectBrowser.TheInstance.getNavPane().addToHistory(d); pb.setTarget(d); } catch (PropertyVetoException pve) { System.out.println("PropertyVetoException in ActionActivityDiagram"); } super.actionPerformed(ae); }
public void actionPerformed(ActionEvent ae) { ProjectBrowser pb = ProjectBrowser.TheInstance; Project p = pb.getProject(); try { MModelElement me = (MModelElement)pb.getDetailsTarget(); if (!((me instanceof MNamespace) && ((me instanceof MUseCase) || (me instanceof MClass)))) { JOptionPane.showMessageDialog(null, "You need to have a class or use case as your target in order to\nspecify for what you want to define a behaviour for.", "Warning", JOptionPane.WARNING_MESSAGE); return; }; MNamespace ns=(MNamespace)me; String contextNameStr = ns.getName(); if (contextNameStr == null) contextNameStr = "untitled"; MActivityGraph am = new MActivityGraphImpl(); am.setUUID(UUIDManager.SINGLETON.getNewUUID()); am.setName(contextNameStr + "ActivityGraph"); MCompositeState cs = new MCompositeStateImpl(); cs.setName("activities_top"); //cs.setNamespace(ns); am.setNamespace(ns); am.setTop(cs); ns.addBehavior(am); UMLActivityDiagram d = new UMLActivityDiagram(ns, am); p.addMember(d); ProjectBrowser.TheInstance.getNavPane().addToHistory(d); pb.setTarget(d); } catch (PropertyVetoException pve) { System.out.println("PropertyVetoException in ActionActivityDiagram"); } super.actionPerformed(ae); }
diff --git a/src/com/google/inject/internal/Errors.java b/src/com/google/inject/internal/Errors.java index e3689b73..b21b8860 100644 --- a/src/com/google/inject/internal/Errors.java +++ b/src/com/google/inject/internal/Errors.java @@ -1,511 +1,512 @@ /** * Copyright (C) 2006 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.google.inject.internal; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.inject.CreationException; import com.google.inject.Key; import com.google.inject.Provider; import com.google.inject.Scope; import com.google.inject.TypeLiteral; import com.google.inject.spi.Dependency; import com.google.inject.spi.InjectionPoint; import com.google.inject.spi.Message; import java.io.Serializable; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Formatter; import java.util.Iterator; import java.util.List; /** * A collection of error messages. If this type is passed as a method parameter, the method is * considered to have executed succesfully only if new errors were not added to this collection. * * @author [email protected] (Jesse Wilson) */ public final class Errors implements Serializable { // TODO(kevinb): gee, ya think we might want to remove this? private static final boolean allowNullsBadBadBad = "I'm a bad hack".equals(System.getProperty("guice.allow.nulls.bad.bad.bad")); private List<Message> errors; private final List<Object> sources; public Errors() { sources = Lists.newArrayList(); errors = Lists.newArrayList(); } public Errors(Object source) { sources = Lists.newArrayList(source); errors = Lists.newArrayList(); } private Errors(Errors parent, Object source) { errors = parent.errors; sources = Lists.newArrayList(parent.sources); sources.add(source); } /** * Returns an instance that uses {@code source} as a reference point for newly added errors. */ public Errors withSource(Object source) { return source == SourceProvider.UNKNOWN_SOURCE ? this : new Errors(this, source); } public void pushSource(Object source) { sources.add(source); } public void popSource(Object source) { Object popped = sources.remove(sources.size() - 1); checkArgument(source == popped); } /** * We use a fairly generic error message here. The motivation is to share the * same message for both bind time errors: * <pre><code>Guice.createInjector(new AbstractModule() { * public void configure() { * bind(Runnable.class); * } * }</code></pre> * ...and at provide-time errors: * <pre><code>Guice.createInjector().getInstance(Runnable.class);</code></pre> * Otherwise we need to know who's calling when resolving a just-in-time * binding, which makes things unnecessarily complex. */ public Errors missingImplementation(Object keyOrType) { return addMessage("No implementation for %s was bound.", keyOrType); } public Errors converterReturnedNull(String stringValue, Object source, TypeLiteral<?> type, MatcherAndConverter matchingConverter) { return addMessage("Received null converting '%s' (bound at %s) to %s%n" + " using %s.", stringValue, sourceToString(source), type, matchingConverter); } public Errors conversionTypeError(String stringValue, Object source, TypeLiteral<?> type, MatcherAndConverter matchingConverter, Object converted) { return addMessage("Type mismatch converting '%s' (bound at %s) to %s%n" + " using %s.%n" + " Converter returned %s.", stringValue, sourceToString(source), type, matchingConverter, converted); } public Errors conversionError(String stringValue, Object source, TypeLiteral<?> type, MatcherAndConverter matchingConverter, Exception cause) { return addMessage(cause, "Error converting '%s' (bound at %s) to %s%n" + " using %s.%n" + " Reason: %s", stringValue, sourceToString(source), type, matchingConverter, cause); } public Errors ambiguousTypeConversion(String stringValue, Object source, TypeLiteral<?> type, MatcherAndConverter a, MatcherAndConverter b) { return addMessage("Multiple converters can convert '%s' (bound at %s) to %s:%n" + " %s and%n" + " %s.%n" + " Please adjust your type converter configuration to avoid overlapping matches.", stringValue, sourceToString(source), type, a, b); } public Errors bindingToProvider() { return addMessage("Binding to Provider is not allowed."); } public Errors subtypeNotProvided(Class<? extends Provider<?>> providerType, Class<?> type) { return addMessage("%s doesn't provide instances of %s.", providerType, type); } public Errors notASubtype(Class<?> implementationType, Class<?> type) { return addMessage("%s doesn't extend %s.", implementationType, type); } public Errors recursiveImplementationType() { return addMessage("@ImplementedBy points to the same class it annotates."); } public Errors recursiveProviderType() { return addMessage("@ProvidedBy points to the same class it annotates."); } public Errors missingRuntimeRetention(Object source) { return addMessage("Please annotate with @Retention(RUNTIME).%n" + " Bound at %s.", sourceToString(source)); } public Errors missingScopeAnnotation() { return addMessage("Please annotate with @ScopeAnnotation."); } public Errors optionalConstructor(Constructor constructor) { return addMessage("%s is annotated @Inject(optional=true), " + "but constructors cannot be optional.", constructor); } public Errors cannotBindToGuiceType(String simpleName) { return addMessage("Binding to core guice framework type is not allowed: %s.", simpleName); } public Errors scopeNotFound(Class<? extends Annotation> scopeAnnotation) { return addMessage("No scope is bound to %s.", scopeAnnotation); } public Errors scopeAnnotationOnAbstractType( Class<? extends Annotation> scopeAnnotation, Class<?> type, Object source) { return addMessage("%s is annotated with %s, but scope annotations are not supported " + "for abstract types.%n Bound at %s.", type, scopeAnnotation, sourceToString(source)); } public Errors misplacedBindingAnnotation(Member member, Annotation bindingAnnotation) { return addMessage("%s is annotated with %s, but binding annotations should be applied " + "to its parameters instead.", member, bindingAnnotation); } private static final String CONSTRUCTOR_RULES = "Classes must have either one (and only one) constructor " + "annotated with @Inject or a zero-argument constructor that is not private."; public Errors missingConstructor(Class<?> implementation) { return addMessage("Could not find a suitable constructor in %s. " + CONSTRUCTOR_RULES, implementation); } public Errors tooManyConstructors(Class<?> implementation) { return addMessage("%s has more than one constructor annotated with @Inject. " + CONSTRUCTOR_RULES, implementation); } public Errors duplicateScopes(Scope existing, Class<? extends Annotation> annotationType, Scope scope) { return addMessage("Scope %s is already bound to %s. Cannot bind %s.", existing, annotationType, scope); } public Errors missingConstantValues() { return addMessage("Missing constant value. Please call to(...)."); } public Errors cannotInjectInnerClass(Class<?> type) { return addMessage("Injecting into inner classes is not supported. " + "Please use a 'static' class (top-level or nested) instead of %s.", type); } public Errors duplicateBindingAnnotations(Member member, Class<? extends Annotation> a, Class<? extends Annotation> b) { return addMessage("%s has more than one annotation annotated with @BindingAnnotation: " + "%s and %s", member, a, b); } public Errors duplicateScopeAnnotations( Class<? extends Annotation> a, Class<? extends Annotation> b) { return addMessage("More than one scope annotation was found: %s and %s", a, b); } public Errors recursiveBinding() { return addMessage("Binding points to itself."); } public Errors bindingAlreadySet(Key<?> key, Object source) { return addMessage("A binding to %s was already configured at %s.", key, sourceToString(source)); } public Errors childBindingAlreadySet(Key<?> key) { return addMessage("A binding to %s already exists on a child injector.", key); } public Errors errorInjectingMethod(Throwable cause) { return addMessage(cause, "Error injecting method, %s", cause); } public Errors errorInjectingConstructor(Throwable cause) { return addMessage(cause, "Error injecting constructor, %s", cause); } public Errors errorInProvider(RuntimeException runtimeException, Errors errorsFromException) { if (errorsFromException != null) { return merge(errorsFromException); } else { return addMessage(runtimeException, "Error in custom provider, %s", runtimeException); } } public Errors cannotInjectRawProvider() { return addMessage("Cannot inject a Provider that has no type parameter"); } public Errors cannotSatisfyCircularDependency(Class<?> expectedType) { return addMessage( "Tried proxying %s to support a circular dependency, but it is not an interface.", expectedType); } public Errors makeImmutable() { errors = ImmutableList.copyOf(errors); return this; } public void throwCreationExceptionIfErrorsExist() { if (!hasErrors()) { return; } makeImmutable(); throw new CreationException(getMessages()); } private Message merge(Message message) { List<Object> sources = Lists.newArrayList(); sources.addAll(this.sources); sources.addAll(message.getSources()); return new Message(stripDuplicates(sources), message.getMessage(), message.getCause()); } public Errors merge(Collection<Message> messages) { if (messages != this.errors) { for (Message message : messages) { errors.add(merge(message)); } } return this; } public Errors merge(Errors moreErrors) { merge(moreErrors.errors); return this; } public void throwIfNecessary() throws ErrorsException { if (!hasErrors()) { return; } throw toException(); } public ErrorsException toException() { return new ErrorsException(this); } public boolean hasErrors() { return !errors.isEmpty(); } private Errors addMessage(String messageFormat, Object... arguments) { return addMessage(null, messageFormat, arguments); } private Errors addMessage(Throwable cause, String messageFormat, Object... arguments) { String message = format(messageFormat, arguments); addMessage(new Message(stripDuplicates(sources), message, cause)); return this; } public Errors addMessage(Message message) { errors.add(message); return this; } private String format(String messageFormat, Object... arguments) { for (int i = 0; i < arguments.length; i++) { arguments[i] = Errors.convert(arguments[i]); } return String.format(messageFormat, arguments); } public List<Message> getMessages() { List<Message> result = Lists.newArrayList(errors); Collections.sort(result, new Comparator<Message>() { public int compare(Message a, Message b) { return a.getSource().compareTo(b.getSource()); } }); return result; } public static String format(String heading, Collection<? extends Message> errorMessages) { Formatter fmt = new Formatter().format(heading).format(":%n%n"); int index = 1; for (Message errorMessage : errorMessages) { fmt.format("%s) %s%n", index++, errorMessage.getMessage()); List<Object> dependencies = errorMessage.getSources(); for (int i = dependencies.size() - 1; i >= 0; i--) { Object source = dependencies.get(i); if (source instanceof Dependency) { Dependency<?> dependency = (Dependency<?>) source; InjectionPoint injectionPoint = dependency.getInjectionPoint(); if (injectionPoint != null) { Member member = injectionPoint.getMember(); Class<? extends Member> memberType = MoreTypes.memberType(member); if (memberType == Field.class) { fmt.format(" for field at %s%n", StackTraceElements.forMember(member)); } else if (memberType == Method.class || memberType == Constructor.class) { fmt.format(" for parameter %s at %s%n", dependency.getParameterIndex(), StackTraceElements.forMember(member)); } else { throw new AssertionError(); } + } else { + fmt.format(" while locating %s%n", convert(dependency.getKey())); } - continue; } fmt.format(" at %s%n", sourceToString(source)); } fmt.format("%n"); } return fmt.format("%s error[s]", errorMessages.size()).toString(); } /** * Returns {@code value} if it is non-null allowed to be null. Otherwise a message is added and * an {@code ErrorsException} is thrown. */ public <T> T checkForNull(T value, Object source, Dependency<?> dependency) throws ErrorsException { if (value != null || dependency.isNullable() || allowNullsBadBadBad) { return value; } int parameterIndex = dependency.getParameterIndex(); String parameterName = (parameterIndex != -1) ? "parameter " + parameterIndex + " of " : ""; addMessage("null returned by binding at %s%n but %s%s is not @Nullable", source, parameterName, dependency.getInjectionPoint().getMember()); throw toException(); } private static abstract class Converter<T> { final Class<T> type; Converter(Class<T> type) { this.type = type; } boolean appliesTo(Object o) { return type.isAssignableFrom(o.getClass()); } String convert(Object o) { return toString(type.cast(o)); } abstract String toString(T t); } private static final Collection<Converter<?>> converters = ImmutableList.of( new Converter<MatcherAndConverter>(MatcherAndConverter.class) { public String toString(MatcherAndConverter m) { return m.toString(); } }, new Converter<Class>(Class.class) { public String toString(Class c) { return c.getName(); } }, new Converter<Member>(Member.class) { public String toString(Member member) { return MoreTypes.toString(member); } }, new Converter<Key>(Key.class) { public String toString(Key k) { StringBuilder result = new StringBuilder(); result.append(k.getTypeLiteral()); if (k.getAnnotationType() != null) { result.append(" annotated with "); result.append(k.getAnnotation() != null ? k.getAnnotation() : k.getAnnotationType()); } return result.toString(); } }); public static Object convert(Object o) { for (Converter<?> converter : converters) { if (converter.appliesTo(o)) { return converter.convert(o); } } return o; } /** * This method returns a String that indicates an element source. We do a * best effort to include a line number in this String. */ public static String sourceToString(Object source) { checkNotNull(source, "source"); if (source instanceof InjectionPoint) { return sourceToString(((InjectionPoint) source).getMember()); } else if (source instanceof Member) { return StackTraceElements.forMember((Member) source).toString(); } else if (source instanceof Class) { return StackTraceElements.forType(((Class<?>) source)).toString(); } else { return convert(source).toString(); } } /** * Removes consecutive duplicates, so that [A B B C D A] becomes [A B C D A]. */ private <T> List<T> stripDuplicates(List<T> list) { list = Lists.newArrayList(list); Iterator i = list.iterator(); if (i.hasNext()) { for (Object last = i.next(), current; i.hasNext(); last = current) { current = i.next(); if (last.equals(current)) { i.remove(); } } } return ImmutableList.copyOf(list); } }
false
true
public static String format(String heading, Collection<? extends Message> errorMessages) { Formatter fmt = new Formatter().format(heading).format(":%n%n"); int index = 1; for (Message errorMessage : errorMessages) { fmt.format("%s) %s%n", index++, errorMessage.getMessage()); List<Object> dependencies = errorMessage.getSources(); for (int i = dependencies.size() - 1; i >= 0; i--) { Object source = dependencies.get(i); if (source instanceof Dependency) { Dependency<?> dependency = (Dependency<?>) source; InjectionPoint injectionPoint = dependency.getInjectionPoint(); if (injectionPoint != null) { Member member = injectionPoint.getMember(); Class<? extends Member> memberType = MoreTypes.memberType(member); if (memberType == Field.class) { fmt.format(" for field at %s%n", StackTraceElements.forMember(member)); } else if (memberType == Method.class || memberType == Constructor.class) { fmt.format(" for parameter %s at %s%n", dependency.getParameterIndex(), StackTraceElements.forMember(member)); } else { throw new AssertionError(); } } continue; } fmt.format(" at %s%n", sourceToString(source)); } fmt.format("%n"); } return fmt.format("%s error[s]", errorMessages.size()).toString(); }
public static String format(String heading, Collection<? extends Message> errorMessages) { Formatter fmt = new Formatter().format(heading).format(":%n%n"); int index = 1; for (Message errorMessage : errorMessages) { fmt.format("%s) %s%n", index++, errorMessage.getMessage()); List<Object> dependencies = errorMessage.getSources(); for (int i = dependencies.size() - 1; i >= 0; i--) { Object source = dependencies.get(i); if (source instanceof Dependency) { Dependency<?> dependency = (Dependency<?>) source; InjectionPoint injectionPoint = dependency.getInjectionPoint(); if (injectionPoint != null) { Member member = injectionPoint.getMember(); Class<? extends Member> memberType = MoreTypes.memberType(member); if (memberType == Field.class) { fmt.format(" for field at %s%n", StackTraceElements.forMember(member)); } else if (memberType == Method.class || memberType == Constructor.class) { fmt.format(" for parameter %s at %s%n", dependency.getParameterIndex(), StackTraceElements.forMember(member)); } else { throw new AssertionError(); } } else { fmt.format(" while locating %s%n", convert(dependency.getKey())); } } fmt.format(" at %s%n", sourceToString(source)); } fmt.format("%n"); } return fmt.format("%s error[s]", errorMessages.size()).toString(); }
diff --git a/src/musician101/itembank/commands/ibcommand/HelpCommand.java b/src/musician101/itembank/commands/ibcommand/HelpCommand.java index fe53644..7d88eac 100644 --- a/src/musician101/itembank/commands/ibcommand/HelpCommand.java +++ b/src/musician101/itembank/commands/ibcommand/HelpCommand.java @@ -1,37 +1,37 @@ package musician101.itembank.commands.ibcommand; import musician101.itembank.ItemBank; import musician101.itembank.lib.Constants; import org.bukkit.command.CommandSender; /** * The code used when the Help argument is used in the ItemBank command. * * @author Musician101 */ public class HelpCommand { public static boolean execute(ItemBank plugin, CommandSender sender, String[] args) { if (args.length == 1) sender.sendMessage(Constants.HELP_LIST); else { String cmd = args[1].toLowerCase(); - if (cmd == Constants.ACCOUNT_CMD) + if (cmd.equals(Constants.ACCOUNT_CMD)) sender.sendMessage(Constants.ACCOUNT_HELP); - else if (cmd == Constants.DEPOSIT_CMD) + else if (cmd.equals(Constants.DEPOSIT_CMD)) sender.sendMessage(Constants.DEPOSIT_HELP); - else if (cmd == Constants.IA_CMD) + else if (cmd.equals(Constants.IA_CMD)) sender.sendMessage(Constants.IA_HELP); - else if (cmd == Constants.PURGE_CMD) + else if (cmd.equals(Constants.PURGE_CMD)) sender.sendMessage(Constants.PURGE_HELP); - else if (cmd == Constants.WITHDRAW_CMD) + else if (cmd.equals(Constants.WITHDRAW_CMD)) sender.sendMessage(Constants.WITHDRAW_HELP); else sender.sendMessage(Constants.PREFIX + "Error: Command not recognized."); } return true; } }
false
true
public static boolean execute(ItemBank plugin, CommandSender sender, String[] args) { if (args.length == 1) sender.sendMessage(Constants.HELP_LIST); else { String cmd = args[1].toLowerCase(); if (cmd == Constants.ACCOUNT_CMD) sender.sendMessage(Constants.ACCOUNT_HELP); else if (cmd == Constants.DEPOSIT_CMD) sender.sendMessage(Constants.DEPOSIT_HELP); else if (cmd == Constants.IA_CMD) sender.sendMessage(Constants.IA_HELP); else if (cmd == Constants.PURGE_CMD) sender.sendMessage(Constants.PURGE_HELP); else if (cmd == Constants.WITHDRAW_CMD) sender.sendMessage(Constants.WITHDRAW_HELP); else sender.sendMessage(Constants.PREFIX + "Error: Command not recognized."); } return true; }
public static boolean execute(ItemBank plugin, CommandSender sender, String[] args) { if (args.length == 1) sender.sendMessage(Constants.HELP_LIST); else { String cmd = args[1].toLowerCase(); if (cmd.equals(Constants.ACCOUNT_CMD)) sender.sendMessage(Constants.ACCOUNT_HELP); else if (cmd.equals(Constants.DEPOSIT_CMD)) sender.sendMessage(Constants.DEPOSIT_HELP); else if (cmd.equals(Constants.IA_CMD)) sender.sendMessage(Constants.IA_HELP); else if (cmd.equals(Constants.PURGE_CMD)) sender.sendMessage(Constants.PURGE_HELP); else if (cmd.equals(Constants.WITHDRAW_CMD)) sender.sendMessage(Constants.WITHDRAW_HELP); else sender.sendMessage(Constants.PREFIX + "Error: Command not recognized."); } return true; }
diff --git a/src/Criterion_MaxGain.java b/src/Criterion_MaxGain.java index 89e6a97..0604a49 100644 --- a/src/Criterion_MaxGain.java +++ b/src/Criterion_MaxGain.java @@ -1,34 +1,36 @@ import java.util.ArrayList; public class Criterion_MaxGain implements Criterion { private static double LOG2 = Math.log(2); private double calculateEntropy(ArrayList<Entry> entries) { int countZero = 0; int countOne = 0; for (Entry e : entries) { if (e.label == 0) ++countZero; else ++countOne; } double p0 = (double)(countZero)/((double)entries.size()); double p1 = (double)(countOne)/((double)entries.size()); + double res0 = (p0 == 0)?0:p0*Math.log(p0); + double res1 = (p1 == 0)?0:p1*Math.log(p1); - return (p0*Math.log(p0)+p1*Math.log(p1))/LOG2; + return (res0+res1)/LOG2; } @Override public double calculateSplitPerf(ArrayList<Entry> lchild, ArrayList<Entry> rchild, ArrayList<Entry> all) { double entropyBefore = calculateEntropy(all); double entropyAfter = calculateEntropy(lchild) + calculateEntropy(rchild); return entropyBefore - entropyAfter; } }
false
true
private double calculateEntropy(ArrayList<Entry> entries) { int countZero = 0; int countOne = 0; for (Entry e : entries) { if (e.label == 0) ++countZero; else ++countOne; } double p0 = (double)(countZero)/((double)entries.size()); double p1 = (double)(countOne)/((double)entries.size()); return (p0*Math.log(p0)+p1*Math.log(p1))/LOG2; }
private double calculateEntropy(ArrayList<Entry> entries) { int countZero = 0; int countOne = 0; for (Entry e : entries) { if (e.label == 0) ++countZero; else ++countOne; } double p0 = (double)(countZero)/((double)entries.size()); double p1 = (double)(countOne)/((double)entries.size()); double res0 = (p0 == 0)?0:p0*Math.log(p0); double res1 = (p1 == 0)?0:p1*Math.log(p1); return (res0+res1)/LOG2; }
diff --git a/src/edu/stanford/bmir/protege/web/server/logging/DefaultLogger.java b/src/edu/stanford/bmir/protege/web/server/logging/DefaultLogger.java index 2b2086fe1..b04418a3a 100644 --- a/src/edu/stanford/bmir/protege/web/server/logging/DefaultLogger.java +++ b/src/edu/stanford/bmir/protege/web/server/logging/DefaultLogger.java @@ -1,157 +1,165 @@ package edu.stanford.bmir.protege.web.server.logging; import com.google.common.base.Optional; import edu.stanford.bmir.protege.web.server.MetaProjectManager; import edu.stanford.bmir.protege.web.server.app.App; import edu.stanford.bmir.protege.web.server.app.WebProtegeProperties; import edu.stanford.bmir.protege.web.server.owlapi.HierarchyProviderKey; import edu.stanford.bmir.protege.web.shared.user.UserId; import edu.stanford.smi.protege.server.metaproject.Group; import edu.stanford.smi.protege.server.metaproject.User; import javax.servlet.http.HttpServletRequest; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Date; import java.util.Enumeration; import java.util.IllegalFormatException; import java.util.logging.Level; import java.util.logging.Logger; /** * Author: Matthew Horridge<br> * Stanford University<br> * Bio-Medical Informatics Research Group<br> * Date: 04/03/2013 */ public class DefaultLogger implements WebProtegeLogger { private static final String SUBJECT = "Unexpected Exception in webprotege"; private Logger logger; public DefaultLogger(Class<?> cls) { this.logger = Logger.getLogger(cls.getName()); } @Override public void severe(Throwable t, UserId userId) { String message = formatMessage(t, Optional.of(userId), Optional.<HttpServletRequest>absent()); logSevereMessage(message); } @Override public void severe(Throwable t, UserId userId, HttpServletRequest servletRequest) { String message = formatMessage(t, Optional.of(userId), Optional.of(servletRequest)); logSevereMessage(message); } @Override public void severe(Throwable t) { String message = formatMessage(t, Optional.<UserId>absent(), Optional.<HttpServletRequest>absent()); logSevereMessage(message); } private void logSevereMessage(String message) { emailMessage(message); writeToLog(message, Level.SEVERE); } private String formatMessage(Throwable t, Optional<UserId> userId, Optional<HttpServletRequest> request) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.println("An unexpected exception was thrown on the server"); pw.println(); pw.print("Date and time: "); pw.println(new Date()); if (userId.isPresent()) { pw.println(); pw.print("User: "); pw.println(userId.get().getUserName()); final UserId id = userId.get(); if(!id.isGuest()) { User user = MetaProjectManager.getManager().getMetaProject().getUser(id.getUserName()); pw.println("email: " + user.getEmail()); pw.println("groups: "); for(Group group : user.getGroups()) { pw.println(" " + group.getName()); } } } if(request.isPresent()) { HttpServletRequest req = request.get(); pw.println("Request URI: " + req.getRequestURI()); + String remoteAddr = req.getRemoteAddr(); + if (remoteAddr != null) { + pw.println("Remote address: " + remoteAddr); + } + String remoteHost = req.getRemoteHost(); + if (remoteHost != null) { + pw.println("Remote host: " + remoteHost); + } pw.println(); pw.println("Headers: "); Enumeration headerNames = req.getHeaderNames(); while(headerNames.hasMoreElements()) { Object headerName = headerNames.nextElement(); String header = req.getHeader(headerName.toString()); pw.print(headerName); pw.print(": "); pw.println(header); } } pw.println(); pw.println(); pw.print("Message: "); pw.println(t.getMessage()); pw.println(); pw.println("Stack trace:"); pw.println(); t.printStackTrace(pw); return sw.toString(); } @Override public void info(String message) { writeToLog(message, Level.INFO); } @Override public void info(String message, Object... args) { if(!logger.isLoggable(Level.INFO)) { return; } String formattedMessage = formatMessage(message, args); writeToLog(formattedMessage, Level.INFO); } private String formatMessage(String message, Object[] args) { String formattedMessage; try { formattedMessage = String.format(message, args); } catch (IllegalFormatException e) { formattedMessage = "Illegally formatted log message: " + message; } return formattedMessage; } private void emailMessage(String message) { try { Optional<String> adminEmail = WebProtegeProperties.get().getAdministratorEmail(); if (adminEmail.isPresent()) { App.get().getMailManager().sendMail(adminEmail.get(), SUBJECT, message); } } catch (Throwable e) { info("Problem sending mail %s", e.getMessage()); } } private void writeToLog(String message, Level level) { if (logger.isLoggable(level)) { logger.log(level, message); } } public static void main(String[] args) { DefaultLogger l = new DefaultLogger(HierarchyProviderKey.class); l.severe(new RuntimeException("Test throwing")); } }
true
true
private String formatMessage(Throwable t, Optional<UserId> userId, Optional<HttpServletRequest> request) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.println("An unexpected exception was thrown on the server"); pw.println(); pw.print("Date and time: "); pw.println(new Date()); if (userId.isPresent()) { pw.println(); pw.print("User: "); pw.println(userId.get().getUserName()); final UserId id = userId.get(); if(!id.isGuest()) { User user = MetaProjectManager.getManager().getMetaProject().getUser(id.getUserName()); pw.println("email: " + user.getEmail()); pw.println("groups: "); for(Group group : user.getGroups()) { pw.println(" " + group.getName()); } } } if(request.isPresent()) { HttpServletRequest req = request.get(); pw.println("Request URI: " + req.getRequestURI()); pw.println(); pw.println("Headers: "); Enumeration headerNames = req.getHeaderNames(); while(headerNames.hasMoreElements()) { Object headerName = headerNames.nextElement(); String header = req.getHeader(headerName.toString()); pw.print(headerName); pw.print(": "); pw.println(header); } } pw.println(); pw.println(); pw.print("Message: "); pw.println(t.getMessage()); pw.println(); pw.println("Stack trace:"); pw.println(); t.printStackTrace(pw); return sw.toString(); }
private String formatMessage(Throwable t, Optional<UserId> userId, Optional<HttpServletRequest> request) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.println("An unexpected exception was thrown on the server"); pw.println(); pw.print("Date and time: "); pw.println(new Date()); if (userId.isPresent()) { pw.println(); pw.print("User: "); pw.println(userId.get().getUserName()); final UserId id = userId.get(); if(!id.isGuest()) { User user = MetaProjectManager.getManager().getMetaProject().getUser(id.getUserName()); pw.println("email: " + user.getEmail()); pw.println("groups: "); for(Group group : user.getGroups()) { pw.println(" " + group.getName()); } } } if(request.isPresent()) { HttpServletRequest req = request.get(); pw.println("Request URI: " + req.getRequestURI()); String remoteAddr = req.getRemoteAddr(); if (remoteAddr != null) { pw.println("Remote address: " + remoteAddr); } String remoteHost = req.getRemoteHost(); if (remoteHost != null) { pw.println("Remote host: " + remoteHost); } pw.println(); pw.println("Headers: "); Enumeration headerNames = req.getHeaderNames(); while(headerNames.hasMoreElements()) { Object headerName = headerNames.nextElement(); String header = req.getHeader(headerName.toString()); pw.print(headerName); pw.print(": "); pw.println(header); } } pw.println(); pw.println(); pw.print("Message: "); pw.println(t.getMessage()); pw.println(); pw.println("Stack trace:"); pw.println(); t.printStackTrace(pw); return sw.toString(); }
diff --git a/trunk/org/xbill/DNS/Name.java b/trunk/org/xbill/DNS/Name.java index d7bc3c7..51ff97e 100644 --- a/trunk/org/xbill/DNS/Name.java +++ b/trunk/org/xbill/DNS/Name.java @@ -1,825 +1,825 @@ // Copyright (c) 1999 Brian Wellington ([email protected]) package org.xbill.DNS; import java.io.*; import java.text.*; import org.xbill.DNS.utils.*; /** * A representation of a domain name. It may either be absolute (fully * qualified) or relative. * * @author Brian Wellington */ public class Name implements Comparable { private static final int LABEL_NORMAL = 0; private static final int LABEL_COMPRESSION = 0xC0; private static final int LABEL_MASK = 0xC0; /* The name data */ private byte [] name; /* * Effectively an 8 byte array, where the low order byte stores the number * of labels and the 7 higher order bytes store per-label offsets. */ private long offsets; /* Precomputed hashcode. */ private int hashcode; private static final byte [] emptyLabel = new byte[] {(byte)0}; private static final byte [] wildLabel = new byte[] {(byte)1, (byte)'*'}; /** The root name */ public static final Name root; /** The maximum length of a Name */ private static final int MAXNAME = 255; /** The maximum length of a label a Name */ private static final int MAXLABEL = 63; /** The maximum number of labels in a Name */ private static final int MAXLABELS = 128; /** The maximum number of cached offsets */ private static final int MAXOFFSETS = 7; /* Used for printing non-printable characters */ private static final DecimalFormat byteFormat = new DecimalFormat(); /* Used to efficiently convert bytes to lowercase */ private static final byte lowercase[] = new byte[256]; /* Used in wildcard names. */ private static final Name wild; static { byteFormat.setMinimumIntegerDigits(3); for (int i = 0; i < lowercase.length; i++) { if (i < 'A' || i > 'Z') lowercase[i] = (byte)i; else lowercase[i] = (byte)(i - 'A' + 'a'); } root = new Name(); wild = new Name(); root.appendSafe(emptyLabel, 0, 1); wild.appendSafe(wildLabel, 0, 1); } private Name() { } private final void dump(String prefix) { String s; try { s = toString(); } catch (Exception e) { s = "<unprintable>"; } System.out.println(prefix + ": " + s); byte labels = labels(); for (int i = 0; i < labels; i++) System.out.print(offset(i) + " "); System.out.println(""); for (int i = 0; name != null && i < name.length; i++) System.out.print((name[i] & 0xFF) + " "); System.out.println(""); } private final void setoffset(int n, int offset) { if (n >= MAXOFFSETS) return; int shift = 8 * (7 - n); offsets &= (~(0xFFL << shift)); offsets |= ((long)offset << shift); } private final int offset(int n) { if (n < 0 || n >= getlabels()) throw new IllegalArgumentException("label out of range"); if (n < MAXOFFSETS) { int shift = 8 * (7 - n); return ((int)(offsets >>> shift) & 0xFF); } else { int pos = offset(MAXOFFSETS - 1); for (int i = MAXOFFSETS - 1; i < n; i++) pos += (name[pos] + 1); return (pos); } } private final void setlabels(byte labels) { offsets &= ~(0xFF); offsets |= labels; } private final byte getlabels() { return (byte)(offsets & 0xFF); } private static final void copy(Name src, Name dst) { dst.name = src.name; dst.offsets = src.offsets; } private final void append(byte [] array, int start, int n) throws NameTooLongException { int length = (name == null ? 0 : (name.length - offset(0))); int alength = 0; for (int i = 0, pos = start; i < n; i++) { int len = array[pos]; if (len > MAXLABEL) throw new IllegalStateException("invalid label"); len++; pos += len; alength += len; } int newlength = length + alength; if (newlength > MAXNAME) throw new NameTooLongException(); byte labels = getlabels(); int newlabels = labels + n; if (newlabels > MAXLABELS) throw new IllegalStateException("too many labels"); byte [] newname = new byte[newlength]; if (length != 0) System.arraycopy(name, offset(0), newname, 0, length); System.arraycopy(array, start, newname, length, alength); name = newname; for (int i = 0, pos = length; i < n; i++) { setoffset(labels + i, pos); pos += (newname[pos] + 1); } setlabels((byte) newlabels); } private static TextParseException parseException(String str, String message) { return new TextParseException("'" + str + "': " + message); } private final void appendFromString(String fullName, byte [] array, int start, int n) throws TextParseException { try { append(array, start, n); } catch (NameTooLongException e) { throw parseException(fullName, "Name too long"); } } private final void appendSafe(byte [] array, int start, int n) { try { append(array, start, n); } catch (NameTooLongException e) { } } /** * Create a new name from a string and an origin * @param s The string to be converted * @param origin If the name is not absolute, the origin to be appended * @deprecated As of dnsjava 1.3.0, replaced by <code>Name.fromString</code>. */ public Name(String s, Name origin) { Name n; try { n = Name.fromString(s, origin); } catch (TextParseException e) { StringBuffer sb = new StringBuffer(s); if (origin != null) sb.append("." + origin); sb.append(": "+ e.getMessage()); System.err.println(sb.toString()); return; } if (!n.isAbsolute() && !Options.check("pqdn") && n.getlabels() > 1 && n.getlabels() < MAXLABELS - 1) { /* * This isn't exactly right, but it's close. * Partially qualified names are evil. */ n.appendSafe(emptyLabel, 0, 1); } copy(n, this); } /** * Create a new name from a string * @param s The string to be converted * @deprecated as of dnsjava 1.3.0, replaced by <code>Name.fromString</code>. */ public Name(String s) { this (s, null); } /** * Create a new name from a string and an origin. This does not automatically * make the name absolute; it will be absolute if it has a trailing dot or an * absolute origin is appended. * @param s The string to be converted * @param origin If the name is not absolute, the origin to be appended. * @throws TextParseException The name is invalid. */ public static Name fromString(String s, Name origin) throws TextParseException { Name name = new Name(); if (s.equals("")) throw parseException(s, "empty name"); else if (s.equals("@")) { if (origin == null) return name; return origin; } else if (s.equals(".")) return (root); int labelstart = -1; int pos = 1; byte [] label = new byte[MAXLABEL + 1]; boolean escaped = false; int digits = 0; int intval = 0; boolean absolute = false; for (int i = 0; i < s.length(); i++) { byte b = (byte) s.charAt(i); if (escaped) { if (b >= '0' && b <= '9' && digits < 3) { digits++; intval *= 10; intval += (b - '0'); if (intval > 255) throw parseException(s, "bad escape"); if (digits < 3) continue; b = (byte) intval; } else if (digits > 0 && digits < 3) throw parseException(s, "bad escape"); - if (pos >= MAXLABEL) + if (pos > MAXLABEL) throw parseException(s, "label too long"); labelstart = pos; label[pos++] = b; escaped = false; } else if (b == '\\') { escaped = true; digits = 0; intval = 0; } else if (b == '.') { if (labelstart == -1) throw parseException(s, "invalid empty label"); label[0] = (byte)(pos - 1); name.appendFromString(s, label, 0, 1); labelstart = -1; pos = 1; } else { if (labelstart == -1) labelstart = i; - if (pos >= MAXLABEL) + if (pos > MAXLABEL) throw parseException(s, "label too long"); label[pos++] = b; } } if (digits > 0 && digits < 3) throw parseException(s, "bad escape"); if (labelstart == -1) { name.appendFromString(s, emptyLabel, 0, 1); absolute = true; } else { label[0] = (byte)(pos - 1); name.appendFromString(s, label, 0, 1); } if (origin != null && !absolute) name.appendFromString(s, origin.name, 0, origin.getlabels()); return (name); } /** * Create a new name from a string. This does not automatically make the name * absolute; it will be absolute if it has a trailing dot. * @param s The string to be converted * @throws TextParseException The name is invalid. */ public static Name fromString(String s) throws TextParseException { return fromString(s, null); } /** * Create a new name from a constant string. This should only be used when the name is known to be good - that is, when it is constant. * @param s The string to be converted * @throws IllegalArgumentException The name is invalid. */ public static Name fromConstantString(String s) { try { return fromString(s, null); } catch (TextParseException e) { throw new IllegalArgumentException("Invalid name '" + s + "'"); } } /** * Create a new name from DNS wire format * @param in A stream containing the wire format of the Name. */ Name(DataByteInputStream in) throws IOException { int len, pos, currentpos; Name name2; boolean done = false; byte [] label = new byte[MAXLABEL + 1]; int savedpos = -1; while (!done) { len = in.readUnsignedByte(); switch (len & LABEL_MASK) { case LABEL_NORMAL: if (getlabels() >= MAXLABELS) throw new WireParseException("too many labels"); if (len == 0) { append(emptyLabel, 0, 1); done = true; } else { label[0] = (byte)len; in.readArray(label, 1, len); append(label, 0, 1); } break; case LABEL_COMPRESSION: pos = in.readUnsignedByte(); pos += ((len & ~LABEL_MASK) << 8); if (Options.check("verbosecompression")) System.err.println("currently " + in.getPos() + ", pointer to " + pos); currentpos = in.getPos(); if (pos >= currentpos) throw new WireParseException("bad compression"); if (savedpos == -1) savedpos = currentpos; in.setPos(pos); if (Options.check("verbosecompression")) System.err.println("current name '" + this + "', seeking to " + pos); continue; } } if (savedpos != -1) in.setPos(savedpos); } /** * Create a new name from DNS wire format * @param b A byte array containing the wire format of the name. */ public Name(byte [] b) throws IOException { this(new DataByteInputStream(b)); } /** * Create a new name by removing labels from the beginning of an existing Name * @param src An existing Name * @param n The number of labels to remove from the beginning in the copy */ public Name(Name src, int n) { byte slabels = src.labels(); if (n > slabels) throw new IllegalArgumentException("attempted to remove too " + "many labels"); name = src.name; setlabels((byte)(slabels - n)); for (int i = 0; i < MAXOFFSETS && i < slabels - n; i++) setoffset(i, src.offset(i + n)); } /** * Creates a new name by concatenating two existing names. * @param prefix The prefix name. * @param suffix The suffix name. * @return The concatenated name. * @throws NameTooLongException The name is too long. */ public static Name concatenate(Name prefix, Name suffix) throws NameTooLongException { if (prefix.isAbsolute()) return (prefix); Name newname = new Name(); copy(prefix, newname); newname.append(suffix.name, suffix.offset(0), suffix.getlabels()); return newname; } /** * If this name is a subdomain of origin, return a new name relative to * origin with the same value. Otherwise, return the existing name. * @param origin The origin to remove. * @return The possibly relativized name. */ public Name relativize(Name origin) { if (origin == null || !subdomain(origin)) return this; Name newname = new Name(); copy(this, newname); int length = length() - origin.length(); int labels = newname.labels() - origin.labels(); newname.setlabels((byte)labels); newname.name = new byte[length]; System.arraycopy(name, offset(0), newname.name, 0, length); return newname; } /** * Generates a new Name with the first n labels replaced by a wildcard * @return The wildcard name */ public Name wild(int n) { if (n < 1) throw new IllegalArgumentException("must replace 1 or more " + "labels"); try { Name newname = new Name(); copy(wild, newname); newname.append(name, offset(n), getlabels() - n); return newname; } catch (NameTooLongException e) { throw new IllegalStateException ("Name.wild: concatenate failed"); } } /** * Generates a new Name to be used when following a DNAME. * @param dname The DNAME record to follow. * @return The constructed name. * @throws NameTooLongException The resulting name is too long. */ public Name fromDNAME(DNAMERecord dname) throws NameTooLongException { Name dnameowner = dname.getName(); Name dnametarget = dname.getTarget(); if (!subdomain(dnameowner)) return null; int plabels = labels() - dnameowner.labels(); int plength = length() - dnameowner.length(); int pstart = offset(0); int dlabels = dnametarget.labels(); int dlength = dnametarget.length(); if (plength + dlength > MAXNAME) throw new NameTooLongException(); Name newname = new Name(); newname.setlabels((byte)(plabels + dlabels)); newname.name = new byte[plength + dlength]; System.arraycopy(name, pstart, newname.name, 0, plength); System.arraycopy(dnametarget.name, 0, newname.name, plength, dlength); for (int i = 0, pos = 0; i < MAXOFFSETS && i < plabels + dlabels; i++) { newname.setoffset(i, pos); pos += (newname.name[pos] + 1); } return newname; } /** * Is this name a wildcard? */ public boolean isWild() { if (labels() == 0) return false; return (name[0] == (byte)1 && name[1] == (byte)'*'); } /** * Is this name fully qualified (that is, absolute)? * @deprecated As of dnsjava 1.3.0, replaced by <code>isAbsolute</code>. */ public boolean isQualified() { return (isAbsolute()); } /** * Is this name absolute? */ public boolean isAbsolute() { if (labels() == 0) return false; return (name[name.length - 1] == 0); } /** * The length of the name. */ public short length() { return (short)(name.length - offset(0)); } /** * The number of labels in the name. */ public byte labels() { return getlabels(); } /** * Is the current Name a subdomain of the specified name? */ public boolean subdomain(Name domain) { byte labels = labels(); byte dlabels = domain.labels(); if (dlabels > labels) return false; if (dlabels == labels) return equals(domain); return domain.equals(name, offset(labels - dlabels)); } private String byteString(byte [] array, int pos) { StringBuffer sb = new StringBuffer(); int len = array[pos++]; for (int i = pos; i < pos + len; i++) { short b = (short)(array[i] & 0xFF); if (b <= 0x20 || b >= 0x7f) { sb.append('\\'); sb.append(byteFormat.format(b)); } else if (b == '"' || b == '(' || b == ')' || b == '.' || b == ';' || b == '\\' || b == '@' || b == '$') { sb.append('\\'); sb.append((char)b); } else sb.append((char)b); } return sb.toString(); } /** * Convert Name to a String */ public String toString() { byte labels = labels(); if (labels == 0) return "@"; else if (labels == 1 && name[offset(0)] == 0) return "."; StringBuffer sb = new StringBuffer(); for (int i = 0, pos = offset(0); i < labels; i++) { int len = name[pos]; if (len > MAXLABEL) throw new IllegalStateException("invalid label"); if (len == 0) break; sb.append(byteString(name, pos)); sb.append('.'); pos += (1 + len); } if (!isAbsolute()) sb.deleteCharAt(sb.length() - 1); return sb.toString(); } /** * Convert the nth label in a Name to a String * @param n The label to be converted to a String. The first label is 0. */ public byte [] getLabel(int n) { int pos = offset(n); byte len = (byte)(name[pos] + 1); byte [] label = new byte[len]; System.arraycopy(name, pos, label, 0, len); return label; } /** * Convert the nth label in a Name to a String * @param n The label to be converted to a String. The first label is 0. */ public String getLabelString(int n) { int pos = offset(n); return byteString(name, pos); } /** * Convert Name to DNS wire format * @param out The output stream containing the DNS message. * @param c The compression context, or null of no compression is desired. * @throws IllegalArgumentException The name is not absolute. */ void toWire(DataByteOutputStream out, Compression c) { if (!isAbsolute()) throw new IllegalArgumentException("toWire() called on " + "non-absolute name"); byte labels = labels(); for (int i = 0; i < labels - 1; i++) { Name tname; if (i == 0) tname = this; else tname = new Name(this, i); int pos = -1; if (c != null) pos = c.get(tname); if (pos >= 0) { pos |= (LABEL_MASK << 8); out.writeShort(pos); return; } else { if (c != null) c.add(out.getPos(), tname); out.writeString(name, offset(i)); } } out.writeByte(0); } /** * Convert Name to DNS wire format * @throws IllegalArgumentException The name is not absolute. */ public byte [] toWire() { DataByteOutputStream out = new DataByteOutputStream(); toWire(out, null); return out.toByteArray(); } /** * Convert Name to canonical DNS wire format (all lowercase) * @param out The output stream to which the message is written. */ void toWireCanonical(DataByteOutputStream out) { byte [] b = toWireCanonical(); out.writeArray(b); } /** * Convert Name to canonical DNS wire format (all lowercase) */ public byte [] toWireCanonical() { byte labels = labels(); if (labels == 0) return (new byte[0]); byte [] b = new byte[name.length - offset(0)]; for (int i = 0, pos = offset(0); i < labels; i++) { int len = name[pos]; if (len > MAXLABEL) throw new IllegalStateException("invalid label"); b[pos] = name[pos++]; for (int j = 0; j < len; j++) b[pos] = lowercase[(name[pos++] & 0xFF)]; } return b; } /** * Convert Name to DNS wire format * @param out The output stream containing the DNS message. * @param c The compression context, or null of no compression is desired. * @throws IllegalArgumentException The name is not absolute. */ void toWire(DataByteOutputStream out, Compression c, boolean canonical) { if (canonical) toWireCanonical(out); else toWire(out, c); } private final boolean equals(byte [] b, int bpos) { byte labels = labels(); for (int i = 0, pos = offset(0); i < labels; i++) { if (name[pos] != b[bpos]) return false; int len = name[pos++]; bpos++; if (len > MAXLABEL) throw new IllegalStateException("invalid label"); for (int j = 0; j < len; j++) if (lowercase[(name[pos++] & 0xFF)] != lowercase[(b[bpos++] & 0xFF)]) return false; } return true; } /** * Are these two Names equivalent? */ public boolean equals(Object arg) { if (arg == this) return true; if (arg == null || !(arg instanceof Name)) return false; Name d = (Name) arg; if (d.hashcode == 0) d.hashCode(); if (hashcode == 0) hashCode(); if (d.hashcode != hashcode) return false; if (d.labels() != labels()) return false; return equals(d.name, d.offset(0)); } /** * Computes a hashcode based on the value */ public int hashCode() { if (hashcode != 0) return (hashcode); int code = 0; for (int i = offset(0); i < name.length; i++) code += ((code << 3) + lowercase[(name[i] & 0xFF)]); hashcode = code; return hashcode; } /** * Compares this Name to another Object. * @param o The Object to be compared. * @return The value 0 if the argument is a name equivalent to this name; * a value less than 0 if the argument is less than this name in the canonical * ordering, and a value greater than 0 if the argument is greater than this * name in the canonical ordering. * @throws ClassCastException if the argument is not a Name. */ public int compareTo(Object o) { Name arg = (Name) o; if (this == arg) return (0); byte labels = labels(); byte alabels = arg.labels(); int compares = labels > alabels ? alabels : labels; for (int i = 1; i <= compares; i++) { int start = offset(labels - i); int astart = arg.offset(alabels - i); int length = name[start]; int alength = arg.name[astart]; for (int j = 0; j < length && j < alength; j++) { int n = lowercase[(name[j + start + 1]) & 0xFF] - lowercase[(arg.name[j + astart + 1]) & 0xFF]; if (n != 0) return (n); } if (length != alength) return (length - alength); } return (labels - alabels); } }
false
true
public static Name fromString(String s, Name origin) throws TextParseException { Name name = new Name(); if (s.equals("")) throw parseException(s, "empty name"); else if (s.equals("@")) { if (origin == null) return name; return origin; } else if (s.equals(".")) return (root); int labelstart = -1; int pos = 1; byte [] label = new byte[MAXLABEL + 1]; boolean escaped = false; int digits = 0; int intval = 0; boolean absolute = false; for (int i = 0; i < s.length(); i++) { byte b = (byte) s.charAt(i); if (escaped) { if (b >= '0' && b <= '9' && digits < 3) { digits++; intval *= 10; intval += (b - '0'); if (intval > 255) throw parseException(s, "bad escape"); if (digits < 3) continue; b = (byte) intval; } else if (digits > 0 && digits < 3) throw parseException(s, "bad escape"); if (pos >= MAXLABEL) throw parseException(s, "label too long"); labelstart = pos; label[pos++] = b; escaped = false; } else if (b == '\\') { escaped = true; digits = 0; intval = 0; } else if (b == '.') { if (labelstart == -1) throw parseException(s, "invalid empty label"); label[0] = (byte)(pos - 1); name.appendFromString(s, label, 0, 1); labelstart = -1; pos = 1; } else { if (labelstart == -1) labelstart = i; if (pos >= MAXLABEL) throw parseException(s, "label too long"); label[pos++] = b; } } if (digits > 0 && digits < 3) throw parseException(s, "bad escape"); if (labelstart == -1) { name.appendFromString(s, emptyLabel, 0, 1); absolute = true; } else { label[0] = (byte)(pos - 1); name.appendFromString(s, label, 0, 1); } if (origin != null && !absolute) name.appendFromString(s, origin.name, 0, origin.getlabels()); return (name); }
public static Name fromString(String s, Name origin) throws TextParseException { Name name = new Name(); if (s.equals("")) throw parseException(s, "empty name"); else if (s.equals("@")) { if (origin == null) return name; return origin; } else if (s.equals(".")) return (root); int labelstart = -1; int pos = 1; byte [] label = new byte[MAXLABEL + 1]; boolean escaped = false; int digits = 0; int intval = 0; boolean absolute = false; for (int i = 0; i < s.length(); i++) { byte b = (byte) s.charAt(i); if (escaped) { if (b >= '0' && b <= '9' && digits < 3) { digits++; intval *= 10; intval += (b - '0'); if (intval > 255) throw parseException(s, "bad escape"); if (digits < 3) continue; b = (byte) intval; } else if (digits > 0 && digits < 3) throw parseException(s, "bad escape"); if (pos > MAXLABEL) throw parseException(s, "label too long"); labelstart = pos; label[pos++] = b; escaped = false; } else if (b == '\\') { escaped = true; digits = 0; intval = 0; } else if (b == '.') { if (labelstart == -1) throw parseException(s, "invalid empty label"); label[0] = (byte)(pos - 1); name.appendFromString(s, label, 0, 1); labelstart = -1; pos = 1; } else { if (labelstart == -1) labelstart = i; if (pos > MAXLABEL) throw parseException(s, "label too long"); label[pos++] = b; } } if (digits > 0 && digits < 3) throw parseException(s, "bad escape"); if (labelstart == -1) { name.appendFromString(s, emptyLabel, 0, 1); absolute = true; } else { label[0] = (byte)(pos - 1); name.appendFromString(s, label, 0, 1); } if (origin != null && !absolute) name.appendFromString(s, origin.name, 0, origin.getlabels()); return (name); }
diff --git a/src/uk/me/parabola/mkgmap/main/Main.java b/src/uk/me/parabola/mkgmap/main/Main.java index fc04fee1..53d91486 100644 --- a/src/uk/me/parabola/mkgmap/main/Main.java +++ b/src/uk/me/parabola/mkgmap/main/Main.java @@ -1,372 +1,375 @@ /* * Copyright (C) 2007 Steve Ratcliffe * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * 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. * * * Author: Steve Ratcliffe * Create date: 24-Sep-2007 */ package uk.me.parabola.mkgmap.main; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.ExecutionException; import uk.me.parabola.imgfmt.ExitException; import uk.me.parabola.log.Logger; import uk.me.parabola.mkgmap.ArgumentProcessor; import uk.me.parabola.mkgmap.CommandArgs; import uk.me.parabola.mkgmap.CommandArgsReader; import uk.me.parabola.mkgmap.Version; import uk.me.parabola.mkgmap.combiners.Combiner; import uk.me.parabola.mkgmap.combiners.FileInfo; import uk.me.parabola.mkgmap.combiners.GmapsuppBuilder; import uk.me.parabola.mkgmap.combiners.TdbBuilder; import uk.me.parabola.mkgmap.osmstyle.StyleFileLoader; import uk.me.parabola.mkgmap.osmstyle.StyleImpl; import uk.me.parabola.mkgmap.osmstyle.eval.SyntaxException; import uk.me.parabola.mkgmap.reader.osm.Style; import uk.me.parabola.mkgmap.reader.osm.StyleInfo; import uk.me.parabola.mkgmap.reader.overview.OverviewMapDataSource; /** * The new main program. There can be many filenames to process and there can * be differing outputs determined by options. So the actual work is mostly * done in other classes. This one just works out what is wanted. * * @author Steve Ratcliffe */ public class Main implements ArgumentProcessor { private static final Logger log = Logger.getLogger(Main.class); private final MapProcessor maker = new MapMaker(); // Final .img file combiners. private final List<Combiner> combiners = new ArrayList<Combiner>(); private final Map<String, MapProcessor> processMap = new HashMap<String, MapProcessor>(); private String styleFile = "classpath:styles"; private boolean verbose; private final List<Future<String>> futures = new LinkedList<Future<String>>(); private ExecutorService threadPool; // default number of threads private int maxJobs = 1; /** * The main program to make or combine maps. We now use a two pass process, * first going through the arguments and make any maps and collect names * to be used for creating summary files like the TDB and gmapsupp. * * @param args The command line arguments. */ public static void main(String[] args) { // We need at least one argument. if (args.length < 1) { System.err.println("Usage: mkgmap [options...] <file.osm>"); printHelp(System.err, getLang(), "options"); return; } Main mm = new Main(); try { // Read the command line arguments and process each filename found. CommandArgsReader commandArgs = new CommandArgsReader(mm); commandArgs.readArgs(args); } catch (ExitException e) { System.err.println(e.getMessage()); System.exit(1); } } /** * Grab the options help file and print it. * @param err The output print stream to write to. * @param lang A language hint. The help will be displayed in this * language if it has been translated. * @param file The help file to display. */ private static void printHelp(PrintStream err, String lang, String file) { String path = "/help/" + lang + '/' + file; InputStream stream = Main.class.getResourceAsStream(path); if (stream == null) { err.println("Could not find the help topic: " + file + ", sorry"); return; } BufferedReader r = new BufferedReader(new InputStreamReader(stream)); try { String line; while ((line = r.readLine()) != null) err.println(line); } catch (IOException e) { err.println("Could not read the help topic: " + file + ", sorry"); } } public void startOptions() { MapProcessor saver = new NameSaver(); processMap.put("img", saver); // Todo: instead of the direct saver, modify the file with the correct // family-id etc. processMap.put("typ", saver); // Normal map files. processMap.put("rgn", saver); processMap.put("tre", saver); processMap.put("lbl", saver); processMap.put("net", saver); processMap.put("nod", saver); } /** * Switch out to the appropriate class to process the filename. * * @param args The command arguments. * @param filename The filename to process. */ public void processFilename(final CommandArgs args, final String filename) { final String ext = extractExtension(filename); log.debug("file", filename, ", extension is", ext); final MapProcessor mp = mapMaker(ext); if(threadPool == null) { log.info("Creating thread pool with " + maxJobs + " threads"); threadPool = Executors.newFixedThreadPool(maxJobs); } log.info("Submitting job " + filename); futures.add(threadPool.submit(new Callable<String>() { public String call() { String output = mp.makeMap(args, filename); log.debug("adding output name", output); return output; } })); } private MapProcessor mapMaker(String ext) { MapProcessor mp = processMap.get(ext); if (mp == null) mp = maker; return mp; } public void processOption(String opt, String val) { log.debug("option:", opt, val); if (opt.equals("number-of-files")) { // This option always appears first. We use it to turn on/off // generation of the overview files if there is only one file // to process. int n = Integer.valueOf(val); if (n > 1) addTdbBuilder(); } else if (opt.equals("tdbfile")) { addTdbBuilder(); } else if (opt.equals("gmapsupp")) { addCombiner(new GmapsuppBuilder()); } else if (opt.equals("help")) { printHelp(System.out, getLang(), (val.length() > 0) ? val : "help"); } else if (opt.equals("style-file") || opt.equals("map-features")) { styleFile = val; } else if (opt.equals("verbose")) { verbose = true; } else if (opt.equals("list-styles")) { listStyles(); } else if (opt.equals("max-jobs")) { if(val.length() > 0) maxJobs = Integer.parseInt(val); else maxJobs = Runtime.getRuntime().availableProcessors(); if(maxJobs < 1) { log.warn("max-jobs has to be at least 1"); maxJobs = 1; } } else if (opt.equals("version")) { System.err.println(Version.VERSION); System.exit(0); } } private void addTdbBuilder() { TdbBuilder builder = new TdbBuilder(); builder.setOverviewSource(new OverviewMapDataSource()); addCombiner(builder); } private void listStyles() { String[] names; try { StyleFileLoader loader = StyleFileLoader.createStyleLoader(styleFile, null); names = loader.list(); loader.close(); } catch (FileNotFoundException e) { log.debug("didn't find style file", e); throw new ExitException("Could not list style file " + styleFile); } Arrays.sort(names); System.out.println("The following styles are available:"); for (String name : names) { Style style; try { style = new StyleImpl(styleFile, name); } catch (SyntaxException e) { System.err.println("Error in style: " + e.getMessage()); continue; } catch (FileNotFoundException e) { log.debug("could not find style", name); try { style = new StyleImpl(styleFile, null); } catch (SyntaxException e1) { System.err.println("Error in style: " + e1.getMessage()); continue; } catch (FileNotFoundException e1) { log.debug("could not find style", styleFile); continue; } } StyleInfo info = style.getInfo(); System.out.format("%-15s %6s: %s\n", name,info.getVersion(), info.getSummary()); if (verbose) { for (String s : info.getLongDescription().split("\n")) System.out.printf("\t%s\n", s.trim()); } } } private static String getLang() { return "en"; } private void addCombiner(Combiner combiner) { combiners.add(combiner); } public void endOptions(CommandArgs args) { List<String> filenames = new ArrayList<String>(); if(threadPool != null) { threadPool.shutdown(); while(!futures.isEmpty()) { try { try { // don't call get() until a job has finished if(futures.get(0).isDone()) filenames.add(futures.remove(0).get()); else Thread.sleep(10); - } catch (ExecutionException e) { + } + catch (ExecutionException e) { // Re throw the underlying exception Throwable cause = e.getCause(); if (cause instanceof Exception) - throw (Exception) cause; + throw (Exception)cause; + else if (cause instanceof Error) + throw (Error)cause; else throw e; } } catch (ExitException ee) { throw ee; } catch (Exception e) { e.printStackTrace(System.err); if(!args.getProperties().getProperty("keep-going", false)) { throw new ExitException("Exiting - if you want to carry on regardless, use the --keep-going option"); } } } } if (combiners.isEmpty()) return; log.info("Combining maps"); // Get them all set up. for (Combiner c : combiners) c.init(args); // Tell them about each filename for (String file : filenames) { if (file == null) continue; try { log.info(" " + file); FileInfo mapReader = FileInfo.getFileInfo(file); for (Combiner c : combiners) { c.onMapEnd(mapReader); } } catch (FileNotFoundException e) { log.error("could not open file", e); } } // All done, allow tidy up or file creation to happen for (Combiner c : combiners) { c.onFinish(); } } /** * Get the extension of the filename, ignoring any compression suffix. * * @param filename The original filename. * @return The file extension. */ private String extractExtension(String filename) { String[] parts = filename.toLowerCase(Locale.ENGLISH).split("\\."); List<String> ignore = Arrays.asList("gz", "bz2", "bz"); // We want the last part that is not gz, bz etc (and isn't the first part ;) for (int i = parts.length - 1; i > 0; i--) { String ext = parts[i]; if (!ignore.contains(ext)) return ext; } return ""; } /** * A null implementation that just returns the input name as the output. */ private static class NameSaver implements MapProcessor { public String makeMap(CommandArgs args, String filename) { return filename; } } }
false
true
public void endOptions(CommandArgs args) { List<String> filenames = new ArrayList<String>(); if(threadPool != null) { threadPool.shutdown(); while(!futures.isEmpty()) { try { try { // don't call get() until a job has finished if(futures.get(0).isDone()) filenames.add(futures.remove(0).get()); else Thread.sleep(10); } catch (ExecutionException e) { // Re throw the underlying exception Throwable cause = e.getCause(); if (cause instanceof Exception) throw (Exception) cause; else throw e; } } catch (ExitException ee) { throw ee; } catch (Exception e) { e.printStackTrace(System.err); if(!args.getProperties().getProperty("keep-going", false)) { throw new ExitException("Exiting - if you want to carry on regardless, use the --keep-going option"); } } } } if (combiners.isEmpty()) return; log.info("Combining maps"); // Get them all set up. for (Combiner c : combiners) c.init(args); // Tell them about each filename for (String file : filenames) { if (file == null) continue; try { log.info(" " + file); FileInfo mapReader = FileInfo.getFileInfo(file); for (Combiner c : combiners) { c.onMapEnd(mapReader); } } catch (FileNotFoundException e) { log.error("could not open file", e); } } // All done, allow tidy up or file creation to happen for (Combiner c : combiners) { c.onFinish(); } }
public void endOptions(CommandArgs args) { List<String> filenames = new ArrayList<String>(); if(threadPool != null) { threadPool.shutdown(); while(!futures.isEmpty()) { try { try { // don't call get() until a job has finished if(futures.get(0).isDone()) filenames.add(futures.remove(0).get()); else Thread.sleep(10); } catch (ExecutionException e) { // Re throw the underlying exception Throwable cause = e.getCause(); if (cause instanceof Exception) throw (Exception)cause; else if (cause instanceof Error) throw (Error)cause; else throw e; } } catch (ExitException ee) { throw ee; } catch (Exception e) { e.printStackTrace(System.err); if(!args.getProperties().getProperty("keep-going", false)) { throw new ExitException("Exiting - if you want to carry on regardless, use the --keep-going option"); } } } } if (combiners.isEmpty()) return; log.info("Combining maps"); // Get them all set up. for (Combiner c : combiners) c.init(args); // Tell them about each filename for (String file : filenames) { if (file == null) continue; try { log.info(" " + file); FileInfo mapReader = FileInfo.getFileInfo(file); for (Combiner c : combiners) { c.onMapEnd(mapReader); } } catch (FileNotFoundException e) { log.error("could not open file", e); } } // All done, allow tidy up or file creation to happen for (Combiner c : combiners) { c.onFinish(); } }
diff --git a/src/main/java/com/sonyericsson/jenkins/plugins/bfa/IndicationAnnotatorFactory.java b/src/main/java/com/sonyericsson/jenkins/plugins/bfa/IndicationAnnotatorFactory.java index bc0bf5c..32503ff 100644 --- a/src/main/java/com/sonyericsson/jenkins/plugins/bfa/IndicationAnnotatorFactory.java +++ b/src/main/java/com/sonyericsson/jenkins/plugins/bfa/IndicationAnnotatorFactory.java @@ -1,65 +1,69 @@ /* * The MIT License * * Copyright 2012 Sony Mobile Communications AB. All rights reserved. * * 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.sonyericsson.jenkins.plugins.bfa; import com.sonyericsson.jenkins.plugins.bfa.model.FailureCauseBuildAction; import com.sonyericsson.jenkins.plugins.bfa.model.FoundFailureCause; import hudson.Extension; import hudson.console.ConsoleAnnotator; import hudson.console.ConsoleAnnotatorFactory; import hudson.model.AbstractBuild; import org.kohsuke.stapler.Ancestor; import org.kohsuke.stapler.Stapler; import org.kohsuke.stapler.StaplerRequest; import java.util.List; /** * Factory for creating a new {@link IndicationAnnotator} when the log should be annotated. * * @author Tomas Westling &lt;[email protected]&gt; */ @Extension public class IndicationAnnotatorFactory extends ConsoleAnnotatorFactory { @Override public ConsoleAnnotator newInstance(Object context) { StaplerRequest currentRequest = Stapler.getCurrentRequest(); + if (currentRequest == null) { + //Accessed through some other means than http, so lets assume it is not a human. + return null; + } Ancestor ancestor = currentRequest.findAncestor(AbstractBuild.class); if (ancestor == null) { return null; } Object object = ancestor.getObject(); AbstractBuild build = (AbstractBuild)object; FailureCauseBuildAction action = build.getAction(FailureCauseBuildAction.class); if (action == null) { return null; } List<FoundFailureCause> foundFailureCauses = action.getFoundFailureCauses(); if (foundFailureCauses.size() < 1) { return null; } return new IndicationAnnotator(foundFailureCauses); } }
true
true
public ConsoleAnnotator newInstance(Object context) { StaplerRequest currentRequest = Stapler.getCurrentRequest(); Ancestor ancestor = currentRequest.findAncestor(AbstractBuild.class); if (ancestor == null) { return null; } Object object = ancestor.getObject(); AbstractBuild build = (AbstractBuild)object; FailureCauseBuildAction action = build.getAction(FailureCauseBuildAction.class); if (action == null) { return null; } List<FoundFailureCause> foundFailureCauses = action.getFoundFailureCauses(); if (foundFailureCauses.size() < 1) { return null; } return new IndicationAnnotator(foundFailureCauses); }
public ConsoleAnnotator newInstance(Object context) { StaplerRequest currentRequest = Stapler.getCurrentRequest(); if (currentRequest == null) { //Accessed through some other means than http, so lets assume it is not a human. return null; } Ancestor ancestor = currentRequest.findAncestor(AbstractBuild.class); if (ancestor == null) { return null; } Object object = ancestor.getObject(); AbstractBuild build = (AbstractBuild)object; FailureCauseBuildAction action = build.getAction(FailureCauseBuildAction.class); if (action == null) { return null; } List<FoundFailureCause> foundFailureCauses = action.getFoundFailureCauses(); if (foundFailureCauses.size() < 1) { return null; } return new IndicationAnnotator(foundFailureCauses); }
diff --git a/src/edu/umn/genomics/table/JTableEditor.java b/src/edu/umn/genomics/table/JTableEditor.java index a962f0e..3fb0b43 100644 --- a/src/edu/umn/genomics/table/JTableEditor.java +++ b/src/edu/umn/genomics/table/JTableEditor.java @@ -1,435 +1,436 @@ /* * @(#) $RCSfile: JTableEditor.java,v $ $Revision: 1.1 $ $Date: 2004/08/02 20:23:42 $ $Name: TableView1_3_2 $ * * Center for Computational Genomics and Bioinformatics * Academic Health Center, University of Minnesota * Copyright (c) 2000-2002. The Regents of the University of Minnesota * * 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. * see: http://www.gnu.org/copyleft/gpl.html * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * 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. * */ package edu.umn.genomics.table; import java.awt.*; import java.awt.event.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.*; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.JTableHeader; import javax.swing.table.TableColumnModel; import javax.swing.table.TableModel; /** * * @author J Johnson * @version $Revision: 1.1 $ $Date: 2004/08/02 20:23:42 $ $Name: TableView1_3_2 * $ * @since 1.0 * @see javax.swing.JTable * @see javax.swing.table.TableModel */ public class JTableEditor extends AbstractTableSource { static int createCounter = 0; String[] columnTypes = { "Text", "Integer", "Number", "Date", "Boolean", //"Image", //"Color", }; Class[] columnTypeClass = { java.lang.String.class, java.lang.Integer.class, java.lang.Double.class, java.util.Date.class, java.lang.Boolean.class, // java.awt.Image.class, // java.awt.Color.class, }; /* * DataTypes: Text URL email Number Integer Currency Percent Date Time * Boolean Color Image */ TypedTableModel dtm; JTable table = new JTable(); DefaultListSelectionModel colLSM = new DefaultListSelectionModel(); JScrollPane jsp; JToolBar tb = new JToolBar(); JButton newTblBtn; JButton addColBtn; JButton insColBtn; JButton delColBtn; JButton addRowBtn; JButton insRowBtn; JButton delRowBtn; /** * Generates row numbers for a JList. */ class RowNumListModel extends AbstractListModel { public void setSize(int size) { fireContentsChanged(this, 0, size - 1); } public int getSize() { return dtm != null ? dtm.getRowCount() : 0; } public Object getElementAt(int index) { return new Integer(index + 1); // return new Integer((indexMap != null ? indexMap.getSrc(index) : index) + 1); } } RowNumListModel rowNumLM = new RowNumListModel(); JList rowNums = new JList(rowNumLM); TableModelListener tml = new TableModelListener() { public void tableChanged(TableModelEvent e) { if (e.getSource() != null) { rowNumLM.setSize(((TableModel) e.getSource()).getRowCount()); } } }; MouseAdapter colSelector = new MouseAdapter() { public void mouseClicked(MouseEvent e) { int colIdx = table.getTableHeader().columnAtPoint(e.getPoint()); Rectangle rect = table.getTableHeader().getHeaderRect(colIdx); if (colIdx >= 0) { TableColumnModel columnModel = table.getColumnModel(); int viewColumn = columnModel.getColumnIndexAtX(e.getX()); int column = table.convertColumnIndexToModel(viewColumn); if (e.getClickCount() == 1 && column != -1) { if (e.isControlDown()) { if (colLSM.isSelectedIndex(column)) { colLSM.removeSelectionInterval(column, column); } else { colLSM.addSelectionInterval(column, column); } } else { colLSM.setSelectionInterval(column, column); } } table.getTableHeader().repaint(); return; } } }; /** * Column Header renderer class that has SortArrow icons. */ class ColumnRenderer extends DefaultTableCellRenderer { public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { int ci = table.convertColumnIndexToModel(column); // setHorizontalTextPosition(JLabel.RIGHT); // setHorizontalAlignment(JLabel.LEFT); if (table != null) { JTableHeader header = table.getTableHeader(); if (header != null) { setForeground(header.getForeground()); setBackground(colLSM.isSelectedIndex(column) ? table.getSelectionBackground() : header.getBackground()); setFont(header.getFont()); } } setText((value == null) ? "" : value.toString()); setBorder(UIManager.getBorder("TableHeader.cellBorder")); return this; } }; public JTableEditor() { this(true, true); } public JTableEditor(boolean columnChangesAllowed, boolean rowChangesAllowed) { setLayout(new BorderLayout()); table.getTableHeader().setDefaultRenderer(new ColumnRenderer()); table.getTableHeader().setReorderingAllowed(false); // Set the AbstractTableModel variable tableModel = dtm; Icon newTblIcon = null; Icon addColIcon = null; Icon insColIcon = null; Icon delColIcon = null; Icon addRowIcon = null; Icon insRowIcon = null; Icon delRowIcon = null; try { ClassLoader cl = this.getClass().getClassLoader(); // Java look and feel Graphics Repository: Table Toolbar Button Graphics newTblIcon = new ImageIcon(cl.getResource("edu/umn/genomics/table/Icons/NewTable24.gif")); addColIcon = new ImageIcon(cl.getResource("edu/umn/genomics/table/Icons/ColumnInsertAfter24.gif")); insColIcon = new ImageIcon(cl.getResource("edu/umn/genomics/table/Icons/ColumnInsertBefore24.gif")); delColIcon = new ImageIcon(cl.getResource("edu/umn/genomics/table/Icons/ColumnDelete24.gif")); addRowIcon = new ImageIcon(cl.getResource("edu/umn/genomics/table/Icons/RowInsertAfter24.gif")); insRowIcon = new ImageIcon(cl.getResource("edu/umn/genomics/table/Icons/RowInsertBefore24.gif")); delRowIcon = new ImageIcon(cl.getResource("edu/umn/genomics/table/Icons/RowDelete24.gif")); } catch (Exception ex) { ExceptionHandler.popupException(""+ex); } newTblBtn = newTblIcon != null ? new JButton(newTblIcon) : new JButton("New Table"); addColBtn = addColIcon != null ? new JButton(addColIcon) : new JButton("Add Column"); insColBtn = insColIcon != null ? new JButton(insColIcon) : new JButton("Insert Column"); delColBtn = delColIcon != null ? new JButton(delColIcon) : new JButton("Delete Column"); addRowBtn = addRowIcon != null ? new JButton(addRowIcon) : new JButton("Add Row"); insRowBtn = insRowIcon != null ? new JButton(insRowIcon) : new JButton("Insert Row"); delRowBtn = delRowIcon != null ? new JButton(delRowIcon) : new JButton("Delete Row"); newTblBtn.setToolTipText("Create a New Table."); addColBtn.setToolTipText("Add a new column after the current column."); insColBtn.setToolTipText("Add a new column before the current column."); delColBtn.setToolTipText("Remove the current column."); addRowBtn.setToolTipText("Add a new row after the current row."); insRowBtn.setToolTipText("Add a new row before the current row."); delRowBtn.setToolTipText("Remove the current row."); newTblBtn.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { newTable(); } }); addColBtn.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { int colIndex = colLSM.getMaxSelectionIndex() + 1; newColumn(colIndex > 0 ? colIndex : dtm.getColumnCount()); } }); insColBtn.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { int colIndex = colLSM.getMinSelectionIndex(); newColumn(colIndex >= 0 ? colIndex : 0); } }); delColBtn.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { int min = colLSM.getMinSelectionIndex(); if (min < 0) { } else { int max = colLSM.getMaxSelectionIndex(); int[] colIndex = new int[max - min + 1]; int n = 0; for (int i = min; i <= max; i++) { if (colLSM.isSelectedIndex(i)) { colIndex[n++] = i; } } if (n < colIndex.length) { int[] tmp = colIndex; colIndex = new int[n]; System.arraycopy(tmp, 0, colIndex, 0, n); } dtm.deleteColumns(colIndex); colLSM.clearSelection(); } } }); addRowBtn.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { Object[] rowData = new Object[dtm.getColumnCount()]; dtm.addRow(rowData); } }); insRowBtn.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { int rowIndex = rowNums.getSelectedIndex(); rowIndex = rowIndex >= 0 ? rowIndex : 0; Object[] rowData = new Object[dtm.getColumnCount()]; dtm.insertRow(rowIndex, rowData); } }); delRowBtn.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { int[] indices = rowNums.getSelectedIndices(); for (int i = indices.length - 1; i >= 0; i--) { dtm.removeRow(indices[i]); } + rowNums.clearSelection(); } }); newTable(); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); table.setRowSelectionAllowed(true); table.setCellSelectionEnabled(true); setEditing(columnChangesAllowed, rowChangesAllowed); jsp = new JScrollPane(table); rowNums.setFixedCellHeight(table.getRowHeight()); rowNums.setBackground(table.getTableHeader().getBackground()); jsp.setRowHeaderView(rowNums); JLabel rowNumSortLbl = new JLabel("Row"); rowNumSortLbl.setBackground(table.getTableHeader().getBackground()); jsp.setCorner(JScrollPane.UPPER_LEFT_CORNER, rowNumSortLbl); add(jsp); } public void setEditing(boolean columnChangesAllowed, boolean rowChangesAllowed) { if (columnChangesAllowed || rowChangesAllowed) { tb.removeAll(); tb.add(newTblBtn); if (columnChangesAllowed) { tb.add(addColBtn); tb.add(insColBtn); tb.add(delColBtn); if (rowChangesAllowed) { tb.addSeparator(); } table.getTableHeader().addMouseListener(colSelector); } else { table.getTableHeader().removeMouseListener(colSelector); } if (rowChangesAllowed) { tb.add(addRowBtn); tb.add(insRowBtn); tb.add(delRowBtn); } add(tb, BorderLayout.NORTH); } else { remove(tb); } } public void newTable() { if (dtm != null) { dtm.removeTableModelListener(tml); } dtm = new TypedTableModel(); dtm.addTableModelListener(tml); table.setModel(dtm); // Set the AbstractTableModel variable tableModel = dtm; setTableSource(dtm, "Table " + (++createCounter)); } public void newColumn(int columnIndex) { final int[] colIdx = new int[1]; colIdx[0] = columnIndex; final JTextField columnName = new JTextField(20); final JComboBox columnType = new JComboBox(columnTypes); JPanel colPanel = new JPanel(); colPanel.add(new JLabel("Data Type:")); colPanel.add(columnType); colPanel.add(new JLabel("Column Name:")); colPanel.add(columnName); final Object[] options = {"Add", "Close"}; final JOptionPane optionPane = new JOptionPane( colPanel, JOptionPane.QUESTION_MESSAGE, JOptionPane.DEFAULT_OPTION, null, options, options[0]); Component topLevel = this.getTopLevelAncestor(); final JDialog dialog = topLevel instanceof Dialog ? new JDialog((Dialog) this.getTopLevelAncestor(), "New Column", true) : new JDialog((Frame) this.getTopLevelAncestor(), "New Column", true); dialog.setContentPane(optionPane); dialog.setDefaultCloseOperation( JDialog.DO_NOTHING_ON_CLOSE); dialog.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { // setLabel("Thwarted user attempt to close window."); } }); optionPane.addPropertyChangeListener( new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { String prop = e.getPropertyName(); if (dialog.isVisible() && (e.getSource() == optionPane) && (prop.equals(JOptionPane.VALUE_PROPERTY))) { Object optVal = optionPane.getValue(); if (optVal == options[0]) { String name = columnName.getText(); if (name.length() > 0) { newColumn(colIdx[0], name, columnTypeClass[columnType.getSelectedIndex()]); colLSM.addSelectionInterval(colIdx[0], colIdx[0]); colIdx[0]++; columnName.setText(""); } // reset value so we can enter a new column optionPane.setValue(null); return; } else if (optVal == options[1]) { dialog.setVisible(false); } } } }); dialog.pack(); dialog.setLocationRelativeTo(this); dialog.setVisible(true); } public void newColumn(int columnIndex, String columnName, Class columnClass) { dtm.insertColumn(columnIndex, columnName, columnClass); } public TypedTableModel getTypedTableModel() { return dtm; } public void setPreferredViewableRows(int rowNumber) { Dimension dim = table.getPreferredScrollableViewportSize(); dim.height = rowNumber * table.getRowHeight(); table.setPreferredScrollableViewportSize(dim); } /** * Display a JTableEditor usage: java edu.umn.genomics.table.JTableEditor * * @see FileTableModel */ public static void main(String[] args) { JFrame frame = new JFrame("JTableEditor"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); JTableEditor tableEdit = new JTableEditor(); frame.getContentPane().add(tableEdit); frame.pack(); frame.setVisible(true); } }
true
true
public JTableEditor(boolean columnChangesAllowed, boolean rowChangesAllowed) { setLayout(new BorderLayout()); table.getTableHeader().setDefaultRenderer(new ColumnRenderer()); table.getTableHeader().setReorderingAllowed(false); // Set the AbstractTableModel variable tableModel = dtm; Icon newTblIcon = null; Icon addColIcon = null; Icon insColIcon = null; Icon delColIcon = null; Icon addRowIcon = null; Icon insRowIcon = null; Icon delRowIcon = null; try { ClassLoader cl = this.getClass().getClassLoader(); // Java look and feel Graphics Repository: Table Toolbar Button Graphics newTblIcon = new ImageIcon(cl.getResource("edu/umn/genomics/table/Icons/NewTable24.gif")); addColIcon = new ImageIcon(cl.getResource("edu/umn/genomics/table/Icons/ColumnInsertAfter24.gif")); insColIcon = new ImageIcon(cl.getResource("edu/umn/genomics/table/Icons/ColumnInsertBefore24.gif")); delColIcon = new ImageIcon(cl.getResource("edu/umn/genomics/table/Icons/ColumnDelete24.gif")); addRowIcon = new ImageIcon(cl.getResource("edu/umn/genomics/table/Icons/RowInsertAfter24.gif")); insRowIcon = new ImageIcon(cl.getResource("edu/umn/genomics/table/Icons/RowInsertBefore24.gif")); delRowIcon = new ImageIcon(cl.getResource("edu/umn/genomics/table/Icons/RowDelete24.gif")); } catch (Exception ex) { ExceptionHandler.popupException(""+ex); } newTblBtn = newTblIcon != null ? new JButton(newTblIcon) : new JButton("New Table"); addColBtn = addColIcon != null ? new JButton(addColIcon) : new JButton("Add Column"); insColBtn = insColIcon != null ? new JButton(insColIcon) : new JButton("Insert Column"); delColBtn = delColIcon != null ? new JButton(delColIcon) : new JButton("Delete Column"); addRowBtn = addRowIcon != null ? new JButton(addRowIcon) : new JButton("Add Row"); insRowBtn = insRowIcon != null ? new JButton(insRowIcon) : new JButton("Insert Row"); delRowBtn = delRowIcon != null ? new JButton(delRowIcon) : new JButton("Delete Row"); newTblBtn.setToolTipText("Create a New Table."); addColBtn.setToolTipText("Add a new column after the current column."); insColBtn.setToolTipText("Add a new column before the current column."); delColBtn.setToolTipText("Remove the current column."); addRowBtn.setToolTipText("Add a new row after the current row."); insRowBtn.setToolTipText("Add a new row before the current row."); delRowBtn.setToolTipText("Remove the current row."); newTblBtn.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { newTable(); } }); addColBtn.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { int colIndex = colLSM.getMaxSelectionIndex() + 1; newColumn(colIndex > 0 ? colIndex : dtm.getColumnCount()); } }); insColBtn.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { int colIndex = colLSM.getMinSelectionIndex(); newColumn(colIndex >= 0 ? colIndex : 0); } }); delColBtn.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { int min = colLSM.getMinSelectionIndex(); if (min < 0) { } else { int max = colLSM.getMaxSelectionIndex(); int[] colIndex = new int[max - min + 1]; int n = 0; for (int i = min; i <= max; i++) { if (colLSM.isSelectedIndex(i)) { colIndex[n++] = i; } } if (n < colIndex.length) { int[] tmp = colIndex; colIndex = new int[n]; System.arraycopy(tmp, 0, colIndex, 0, n); } dtm.deleteColumns(colIndex); colLSM.clearSelection(); } } }); addRowBtn.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { Object[] rowData = new Object[dtm.getColumnCount()]; dtm.addRow(rowData); } }); insRowBtn.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { int rowIndex = rowNums.getSelectedIndex(); rowIndex = rowIndex >= 0 ? rowIndex : 0; Object[] rowData = new Object[dtm.getColumnCount()]; dtm.insertRow(rowIndex, rowData); } }); delRowBtn.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { int[] indices = rowNums.getSelectedIndices(); for (int i = indices.length - 1; i >= 0; i--) { dtm.removeRow(indices[i]); } } }); newTable(); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); table.setRowSelectionAllowed(true); table.setCellSelectionEnabled(true); setEditing(columnChangesAllowed, rowChangesAllowed); jsp = new JScrollPane(table); rowNums.setFixedCellHeight(table.getRowHeight()); rowNums.setBackground(table.getTableHeader().getBackground()); jsp.setRowHeaderView(rowNums); JLabel rowNumSortLbl = new JLabel("Row"); rowNumSortLbl.setBackground(table.getTableHeader().getBackground()); jsp.setCorner(JScrollPane.UPPER_LEFT_CORNER, rowNumSortLbl); add(jsp); }
public JTableEditor(boolean columnChangesAllowed, boolean rowChangesAllowed) { setLayout(new BorderLayout()); table.getTableHeader().setDefaultRenderer(new ColumnRenderer()); table.getTableHeader().setReorderingAllowed(false); // Set the AbstractTableModel variable tableModel = dtm; Icon newTblIcon = null; Icon addColIcon = null; Icon insColIcon = null; Icon delColIcon = null; Icon addRowIcon = null; Icon insRowIcon = null; Icon delRowIcon = null; try { ClassLoader cl = this.getClass().getClassLoader(); // Java look and feel Graphics Repository: Table Toolbar Button Graphics newTblIcon = new ImageIcon(cl.getResource("edu/umn/genomics/table/Icons/NewTable24.gif")); addColIcon = new ImageIcon(cl.getResource("edu/umn/genomics/table/Icons/ColumnInsertAfter24.gif")); insColIcon = new ImageIcon(cl.getResource("edu/umn/genomics/table/Icons/ColumnInsertBefore24.gif")); delColIcon = new ImageIcon(cl.getResource("edu/umn/genomics/table/Icons/ColumnDelete24.gif")); addRowIcon = new ImageIcon(cl.getResource("edu/umn/genomics/table/Icons/RowInsertAfter24.gif")); insRowIcon = new ImageIcon(cl.getResource("edu/umn/genomics/table/Icons/RowInsertBefore24.gif")); delRowIcon = new ImageIcon(cl.getResource("edu/umn/genomics/table/Icons/RowDelete24.gif")); } catch (Exception ex) { ExceptionHandler.popupException(""+ex); } newTblBtn = newTblIcon != null ? new JButton(newTblIcon) : new JButton("New Table"); addColBtn = addColIcon != null ? new JButton(addColIcon) : new JButton("Add Column"); insColBtn = insColIcon != null ? new JButton(insColIcon) : new JButton("Insert Column"); delColBtn = delColIcon != null ? new JButton(delColIcon) : new JButton("Delete Column"); addRowBtn = addRowIcon != null ? new JButton(addRowIcon) : new JButton("Add Row"); insRowBtn = insRowIcon != null ? new JButton(insRowIcon) : new JButton("Insert Row"); delRowBtn = delRowIcon != null ? new JButton(delRowIcon) : new JButton("Delete Row"); newTblBtn.setToolTipText("Create a New Table."); addColBtn.setToolTipText("Add a new column after the current column."); insColBtn.setToolTipText("Add a new column before the current column."); delColBtn.setToolTipText("Remove the current column."); addRowBtn.setToolTipText("Add a new row after the current row."); insRowBtn.setToolTipText("Add a new row before the current row."); delRowBtn.setToolTipText("Remove the current row."); newTblBtn.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { newTable(); } }); addColBtn.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { int colIndex = colLSM.getMaxSelectionIndex() + 1; newColumn(colIndex > 0 ? colIndex : dtm.getColumnCount()); } }); insColBtn.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { int colIndex = colLSM.getMinSelectionIndex(); newColumn(colIndex >= 0 ? colIndex : 0); } }); delColBtn.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { int min = colLSM.getMinSelectionIndex(); if (min < 0) { } else { int max = colLSM.getMaxSelectionIndex(); int[] colIndex = new int[max - min + 1]; int n = 0; for (int i = min; i <= max; i++) { if (colLSM.isSelectedIndex(i)) { colIndex[n++] = i; } } if (n < colIndex.length) { int[] tmp = colIndex; colIndex = new int[n]; System.arraycopy(tmp, 0, colIndex, 0, n); } dtm.deleteColumns(colIndex); colLSM.clearSelection(); } } }); addRowBtn.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { Object[] rowData = new Object[dtm.getColumnCount()]; dtm.addRow(rowData); } }); insRowBtn.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { int rowIndex = rowNums.getSelectedIndex(); rowIndex = rowIndex >= 0 ? rowIndex : 0; Object[] rowData = new Object[dtm.getColumnCount()]; dtm.insertRow(rowIndex, rowData); } }); delRowBtn.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { int[] indices = rowNums.getSelectedIndices(); for (int i = indices.length - 1; i >= 0; i--) { dtm.removeRow(indices[i]); } rowNums.clearSelection(); } }); newTable(); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); table.setRowSelectionAllowed(true); table.setCellSelectionEnabled(true); setEditing(columnChangesAllowed, rowChangesAllowed); jsp = new JScrollPane(table); rowNums.setFixedCellHeight(table.getRowHeight()); rowNums.setBackground(table.getTableHeader().getBackground()); jsp.setRowHeaderView(rowNums); JLabel rowNumSortLbl = new JLabel("Row"); rowNumSortLbl.setBackground(table.getTableHeader().getBackground()); jsp.setCorner(JScrollPane.UPPER_LEFT_CORNER, rowNumSortLbl); add(jsp); }
diff --git a/okapi/filters/abstractmarkup/src/main/java/net/sf/okapi/filters/abstractmarkup/AbstractMarkupFilter.java b/okapi/filters/abstractmarkup/src/main/java/net/sf/okapi/filters/abstractmarkup/AbstractMarkupFilter.java index a1f81cafd..fa8f63110 100644 --- a/okapi/filters/abstractmarkup/src/main/java/net/sf/okapi/filters/abstractmarkup/AbstractMarkupFilter.java +++ b/okapi/filters/abstractmarkup/src/main/java/net/sf/okapi/filters/abstractmarkup/AbstractMarkupFilter.java @@ -1,1443 +1,1445 @@ /*=========================================================================== Copyright (C) 2008-2011 by the Okapi Framework contributors ----------------------------------------------------------------------------- This library 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 2.1 of the License, or (at your option) any later version. This library 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 library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA See also the full LGPL text here: http://www.gnu.org/copyleft/lesser.html ===========================================================================*/ package net.sf.okapi.filters.abstractmarkup; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import net.htmlparser.jericho.Attribute; import net.htmlparser.jericho.CharacterEntityReference; import net.htmlparser.jericho.CharacterReference; import net.htmlparser.jericho.Config; import net.htmlparser.jericho.EndTag; import net.htmlparser.jericho.EndTagType; import net.htmlparser.jericho.LoggerProvider; import net.htmlparser.jericho.NumericCharacterReference; import net.htmlparser.jericho.Segment; import net.htmlparser.jericho.Source; import net.htmlparser.jericho.StartTag; import net.htmlparser.jericho.StartTagType; import net.htmlparser.jericho.StreamedSource; import net.htmlparser.jericho.Tag; import net.sf.okapi.common.BOMNewlineEncodingDetector; import net.sf.okapi.common.Event; import net.sf.okapi.common.LocaleId; import net.sf.okapi.common.MimeTypeMapper; import net.sf.okapi.common.Util; import net.sf.okapi.common.exceptions.OkapiBadFilterInputException; import net.sf.okapi.common.exceptions.OkapiIOException; import net.sf.okapi.common.filters.AbstractFilter; import net.sf.okapi.common.filters.EventBuilder; import net.sf.okapi.common.filters.IFilter; import net.sf.okapi.common.filters.PropertyTextUnitPlaceholder; import net.sf.okapi.common.filters.PropertyTextUnitPlaceholder.PlaceholderAccessType; import net.sf.okapi.common.filters.SubFilter; import net.sf.okapi.common.filters.SubFilterEventConverter; import net.sf.okapi.common.resource.Code; import net.sf.okapi.common.resource.DocumentPart; import net.sf.okapi.common.resource.Ending; import net.sf.okapi.common.resource.ITextUnit; import net.sf.okapi.common.resource.RawDocument; import net.sf.okapi.common.resource.StartDocument; import net.sf.okapi.common.resource.TextFragment; import net.sf.okapi.common.resource.TextUnit; import net.sf.okapi.common.skeleton.GenericSkeleton; import net.sf.okapi.common.skeleton.GenericSkeletonPart; import net.sf.okapi.filters.abstractmarkup.ExtractionRuleState.RuleType; import net.sf.okapi.filters.yaml.TaggedFilterConfiguration; import net.sf.okapi.filters.yaml.TaggedFilterConfiguration.RULE_TYPE; /** * Abstract class useful for creating an {@link IFilter} around the Jericho parser. Jericho can parse non-wellformed * HTML, XHTML, XML and various server side scripting languages such as PHP, Mason, Perl (all configurable from * Jericho). AbstractMarkupFilter takes care of the parser initialization and provides default handlers for each token * type returned by the parser. * <p> * Handling of translatable text, inline tags, translatable and read-only attributes are configurable through a user * defined YAML file. See the Okapi HtmlFilter with defaultConfiguration.yml and OpenXml filters for examples. * */ public abstract class AbstractMarkupFilter extends AbstractFilter { private static final Logger LOGGER = Logger.getLogger(AbstractMarkupFilter.class.getName()); private static final String CDATA_START_REGEX = "<\\!\\[CDATA\\["; private static final String CDATA_END_REGEX = "\\]\\]>"; private static final Pattern CDATA_START_PATTERN = Pattern.compile(CDATA_START_REGEX); private static final Pattern CDATA_END_PATTERN = Pattern.compile(CDATA_END_REGEX); private static final int PREVIEW_BYTE_COUNT = 1024; private StringBuilder bufferedWhitespace; private StreamedSource document; private Iterator<Segment> nodeIterator; private boolean hasUtf8Bom; private boolean hasUtf8Encoding; private boolean hasBOM; private EventBuilder eventBuilder; private RawDocument currentRawDocument; private ExtractionRuleState ruleState; @SubFilter() // make this IFilter a subfilter private IFilter cdataSubfilter; @SubFilter() // make this IFilter a subfilter private IFilter pcdataSubfilter; private String currentId; private boolean documentEncoding; private String currentDocName; static { Config.ConvertNonBreakingSpaces = false; Config.NewLine = BOMNewlineEncodingDetector.NewlineType.LF.toString(); Config.LoggerProvider = LoggerProvider.JAVA; //Config.CurrentCompatibilityMode = Config.CompatibilityMode.XHTML; } /** * Default constructor for {@link AbstractMarkupFilter} using default {@link EventBuilder} */ public AbstractMarkupFilter() { this.bufferedWhitespace = new StringBuilder(); this.hasUtf8Bom = false; this.hasUtf8Encoding = false; this.hasBOM = false; this.currentId = null; this.documentEncoding = false; } /** * Default constructor for {@link AbstractMarkupFilter} using default {@link EventBuilder} */ public AbstractMarkupFilter(EventBuilder eventBuilder) { this.eventBuilder = eventBuilder; this.bufferedWhitespace = new StringBuilder(); this.hasUtf8Bom = false; this.hasUtf8Encoding = false; this.hasBOM = false; this.currentId = null; this.documentEncoding = false; } /** * Get the current {@link TaggedFilterConfiguration}. A TaggedFilterConfiguration is the result of reading in a YAML * configuration file and converting it into Java Objects. * * @return a {@link TaggedFilterConfiguration} */ abstract protected TaggedFilterConfiguration getConfig(); /** * Close the filter and all used resources. */ public void close() { super.close(); this.hasUtf8Bom = false; this.hasUtf8Encoding = false; this.currentId = null; if (ruleState != null) { ruleState.reset(!getConfig().isGlobalPreserveWhitespace()); } if (currentRawDocument != null) { currentRawDocument.close(); } try { if (document != null) { document.close(); } } catch (IOException e) { throw new OkapiIOException("Could not close " + getDocumentName(), e); } this.document = null; // help Java GC LOGGER.log(Level.FINE, getDocumentName() + " has been closed"); } /* * Get PREVIEW_BYTE_COUNT bytes so we can sniff out any encoding information in XML or HTML files */ protected Source getParsedHeader(final InputStream inputStream) { try { // Make sure we grab the same buffer for UTF-16/32 // this is to avoid round trip problem when not detecting a declaration // between a non-UTF-16/32 and a UTF-16/32 input int charSize = 1; if ( getEncoding().toLowerCase().startsWith("utf-16") ) charSize = 2; else if ( getEncoding().toLowerCase().startsWith("utf-32") ) charSize = 4; final byte[] bytes = new byte[PREVIEW_BYTE_COUNT * charSize]; int i; for (i = 0; i < bytes.length; i++) { final int nextByte = inputStream.read(); if (nextByte == -1) break; bytes[i] = (byte) nextByte; } Source parsedInput = new Source(new ByteArrayInputStream(bytes, 0, i)); return parsedInput; } catch (IOException e) { throw new OkapiIOException("Could not reset the input stream to it's start position", e); } finally { try { inputStream.reset(); } catch (IOException e) { } } } protected String detectEncoding(RawDocument input) { BOMNewlineEncodingDetector detector = new BOMNewlineEncodingDetector(input.getStream(), input.getEncoding()); detector.detectAndRemoveBom(); setEncoding(detector.getEncoding()); hasUtf8Bom = detector.hasUtf8Bom(); hasUtf8Encoding = detector.hasUtf8Encoding(); hasBOM = detector.hasBom(); setNewlineType(detector.getNewlineType().toString()); Source parsedHeader = getParsedHeader(input.getStream()); String detectedEncoding = parsedHeader.getDocumentSpecifiedEncoding(); documentEncoding = detectedEncoding == null ? false : true; if (detectedEncoding == null && getEncoding() != null) { detectedEncoding = getEncoding(); LOGGER.log(Level.FINE, String.format( "Cannot auto-detect encoding. Using the default encoding (%s)", getEncoding())); } else if (getEncoding() == null) { detectedEncoding = parsedHeader.getEncoding(); // get best guess LOGGER.log( Level.FINE, String.format( "Default encoding and detected encoding not found. Using best guess encoding (%s)", detectedEncoding)); } return detectedEncoding; } /** * Start a new {@link IFilter} using the supplied {@link RawDocument}. * * @param input * - input to the {@link IFilter} (can be a {@link CharSequence}, {@link URI} or {@link InputStream}) */ public void open(RawDocument input) { open(input, true); LOGGER.log(Level.FINE, getName() + " has opened an input document"); } /** * Start a new {@link IFilter} using the supplied {@link RawDocument}. * * @param input * - input to the {@link IFilter} (can be a {@link CharSequence}, {@link URI} or {@link InputStream}) * @param generateSkeleton * - true if the {@link IFilter} should store non-translatble blocks (aka skeleton), false otherwise. * * @throws OkapiBadFilterInputException * @throws OkapiIOException */ public void open(RawDocument input, boolean generateSkeleton) { // close RawDocument from previous run close(); super.open(input, generateSkeleton); currentRawDocument = input; // doc name may be set by sub-classes if (getCurrentDocName() != null) { setDocumentName(getCurrentDocName()); } else if (input.getInputURI() != null) { setDocumentName(input.getInputURI().getPath()); } try { String detectedEncoding = detectEncoding(input); input.setEncoding(detectedEncoding); setOptions(input.getSourceLocale(), input.getTargetLocale(), detectedEncoding, generateSkeleton); document = new StreamedSource(input.getReader()); } catch (IOException e) { throw new OkapiIOException("Filter could not open input stream", e); } currentDocName = null; startFilter(); } public boolean hasNext() { return eventBuilder.hasNext(); } /** * Queue up Jericho tokens until we can build an Okapi {@link Event} and return it. */ public Event next() { while (eventBuilder.hasQueuedEvents()) { return eventBuilder.next(); } while (nodeIterator.hasNext() && !isCanceled()) { Segment segment = nodeIterator.next(); preProcess(segment); if (segment instanceof Tag) { final Tag tag = (Tag) segment; if (tag.getTagType() == StartTagType.NORMAL || tag.getTagType() == StartTagType.UNREGISTERED) { handleStartTag((StartTag) tag); } else if (tag.getTagType() == EndTagType.NORMAL || tag.getTagType() == EndTagType.UNREGISTERED) { handleEndTag((EndTag) tag); } else if (tag.getTagType() == StartTagType.DOCTYPE_DECLARATION) { handleDocTypeDeclaration(tag); } else if (tag.getTagType() == StartTagType.CDATA_SECTION) { handleCdataSection(tag); } else if (tag.getTagType() == StartTagType.COMMENT) { handleComment(tag); } else if (tag.getTagType() == StartTagType.XML_DECLARATION) { handleXmlDeclaration(tag); } else if (tag.getTagType() == StartTagType.XML_PROCESSING_INSTRUCTION) { handleProcessingInstruction(tag); } else if (tag.getTagType() == StartTagType.MARKUP_DECLARATION) { handleMarkupDeclaration(tag); } else if (tag.getTagType() == StartTagType.SERVER_COMMON) { handleServerCommon(tag); } else if (tag.getTagType() == StartTagType.SERVER_COMMON_ESCAPED) { handleServerCommonEscaped(tag); } else { // not classified explicitly by Jericho if (tag instanceof StartTag) { handleStartTag((StartTag) tag); } else if (tag instanceof EndTag) { handleEndTag((EndTag) tag); } else { handleDocumentPart(tag); } } } else if (segment instanceof CharacterEntityReference) { handleCharacterEntity(segment); } else if (segment instanceof NumericCharacterReference) { handleNumericEntity(segment); } else { // last resort is pure text node handleText(segment); } if (eventBuilder.hasQueuedEvents()) { break; } } if (!nodeIterator.hasNext()) { endFilter(); // we are done } // return one of the waiting events return eventBuilder.next(); } /** * Initialize the filter for every input and send the {@link StartDocument} {@link Event} */ protected void startFilter() { // order of execution matters if (eventBuilder == null) { eventBuilder = new AbstractMarkupEventBuilder(getParentId(), isSubFilter()); eventBuilder.setMimeType(getMimeType()); } else { eventBuilder.reset(getParentId(), isSubFilter()); } eventBuilder.addFilterEvent(createStartFilterEvent()); // default is to preserve whitespace boolean preserveWhitespace = true; if (getConfig() != null) { preserveWhitespace = getConfig().isGlobalPreserveWhitespace(); } ruleState = new ExtractionRuleState(preserveWhitespace); setPreserveWhitespace(ruleState.isPreserveWhitespaceState()); // This optimizes memory at the expense of performance nodeIterator = document.iterator(); // initialize cdata sub-filter TaggedFilterConfiguration config = getConfig(); if (config != null && config.getGlobalCDATASubfilter() != null) { cdataSubfilter = getFilterConfigurationMapper().createFilter( getConfig().getGlobalCDATASubfilter(), cdataSubfilter); getEncoderManager().mergeMappings(cdataSubfilter.getEncoderManager()); } // intialize pcdata sub-filter if (config != null && config.getGlobalPCDATASubfilter() != null) { String subfilterName = getConfig().getGlobalPCDATASubfilter(); pcdataSubfilter = getFilterConfigurationMapper().createFilter(subfilterName, pcdataSubfilter); getEncoderManager().mergeMappings(pcdataSubfilter.getEncoderManager()); } } /** * End the current filter processing and send the {@link Ending} {@link Event} */ protected void endFilter() { // clear out all unended temp events eventBuilder.flushRemainingTempEvents(); // make sure we flush out any whitespace at the end of the file if (bufferedWhitespace.length() > 0) { eventBuilder.addDocumentPart(bufferedWhitespace.toString()); bufferedWhitespace.setLength(0); bufferedWhitespace.trimToSize(); } // add the final endDocument event eventBuilder.addFilterEvent(createEndFilterEvent()); } /** * Do any handling needed before the current Segment is processed. Default is to do nothing. * * @param segment */ protected void preProcess(Segment segment) { boolean isInsideTextRun = false; if (segment instanceof Tag) { Tag tag = (Tag)segment; if (getConfig().getElementRuleTypeCandidate(tag.getName()) == RULE_TYPE.INLINE_ELEMENT || getConfig().getElementRuleTypeCandidate(tag.getName()) == RULE_TYPE.INLINE_EXCLUDED_ELEMENT || (getEventBuilder().isInsideTextRun() && (tag .getTagType() == StartTagType.COMMENT || tag .getTagType() == StartTagType.XML_PROCESSING_INSTRUCTION))) { isInsideTextRun = true; } } // add buffered whitespace to the current translatable text if (bufferedWhitespace.length() > 0 && isInsideTextRun) { if (canStartNewTextUnit()) { startTextUnit(bufferedWhitespace.toString()); } else { addToTextUnit(bufferedWhitespace.toString()); } } else if (bufferedWhitespace.length() > 0) { // otherwise add it as non-translatable addToDocumentPart(bufferedWhitespace.toString()); } // reset buffer for next pass bufferedWhitespace.setLength(0); bufferedWhitespace.trimToSize(); } /** * Do any required post-processing on the TextUnit before the {@link Event} leaves the {@link IFilter}. Default * implementation leaves Event unchanged. Override this method if you need to do format specific handing such as * collapsing whitespace. */ protected void postProcessTextUnit (ITextUnit textUnit) { } /** * Handle any recognized escaped server tags. * * @param tag */ protected void handleServerCommonEscaped(Tag tag) { handleDocumentPart(tag); } /** * Handle any recognized server tags (i.e., PHP, Mason etc.) * * @param tag */ protected void handleServerCommon(Tag tag) { handleDocumentPart(tag); } /** * Handle an XML markup declaration. * * @param tag */ protected void handleMarkupDeclaration(Tag tag) { handleDocumentPart(tag); } /** * Handle an XML declaration. * * @param tag */ protected void handleXmlDeclaration(Tag tag) { handleDocumentPart(tag); } /** * Handle the XML doc type declaration (DTD). * * @param tag */ protected void handleDocTypeDeclaration(Tag tag) { handleDocumentPart(tag); } /** * Handle processing instructions. * * @param tag */ protected void handleProcessingInstruction(Tag tag) { if (ruleState.isExludedState()) { addToDocumentPart(tag.toString()); return; } if (isInsideTextRun()) { if (ruleState.isInlineExcludedState()) { eventBuilder.appendCodeData(tag.toString()); eventBuilder.appendCodeOuterData(tag.toString()); return; } else { addCodeToCurrentTextUnit(tag); } } else { handleDocumentPart(tag); } } /** * Handle comments. * * @param tag */ protected void handleComment(Tag tag) { if (ruleState.isExludedState()) { addToDocumentPart(tag.toString()); return; } if (isInsideTextRun()) { if (ruleState.isInlineExcludedState()) { eventBuilder.appendCodeData(tag.toString()); eventBuilder.appendCodeOuterData(tag.toString()); return; } else { addCodeToCurrentTextUnit(tag); } } else { handleDocumentPart(tag); } } /** * Handle CDATA sections. * * @param tag */ protected void handleCdataSection(Tag tag) { // end any skeleton so we can start CDATA section with subfilter if (eventBuilder.hasUnfinishedSkeleton()) { endDocumentPart(); } String cdataWithoutMarkers = CDATA_START_PATTERN.matcher(tag.toString()).replaceFirst(""); cdataWithoutMarkers = CDATA_END_PATTERN.matcher(cdataWithoutMarkers).replaceFirst(""); if ( ruleState.isExludedState() ) { // Excluded content addToDocumentPart(tag.toString()); } else { // Content to extract if (cdataSubfilter != null) { String parentId = eventBuilder.findMostRecentParentId(); cdataSubfilter.close(); parentId = (parentId == null ? getDocumentId().getLastId() : parentId); SubFilterEventConverter converter = new SubFilterEventConverter(parentId, new GenericSkeleton("<![CDATA["), new GenericSkeleton("]]>")); // TODO: only AbstractFilter subclasses can be used as subfilters!!! ((AbstractFilter)cdataSubfilter).setParentId(parentId); cdataSubfilter.open(new RawDocument(cdataWithoutMarkers, getSrcLoc())); int tuChildCount = 0; while (cdataSubfilter.hasNext()) { Event event = converter.convertEvent(cdataSubfilter.next()); eventBuilder.addFilterEvent(event); // subfiltered textunits inherit any name from a parent TU if (event.isTextUnit()) { if (event.getTextUnit().getName() == null) { String parentName = eventBuilder.findMostRecentTextUnitName(); // we need to add a child id so each tu name is unique for this subfiltered content if (parentName != null) { parentName = parentName + "-" + Integer.toString(++tuChildCount); } event.getTextUnit().setName(parentName); } } } cdataSubfilter.close(); } else { // we assume the CDATA is plain text take it as is startTextUnit(new GenericSkeleton("<![CDATA[")); addToTextUnit(cdataWithoutMarkers); setTextUnitType(ITextUnit.TYPE_CDATA); setTextUnitMimeType(MimeTypeMapper.PLAIN_TEXT_MIME_TYPE); endTextUnit(new GenericSkeleton("]]>")); } } } /** * Handle all text (PCDATA). * * @param text */ protected void handleText(Segment text) { // if in excluded state everything is skeleton including text if (ruleState.isExludedState()) { addToDocumentPart(text.toString()); return; } if (ruleState.isInlineExcludedState()) { eventBuilder.appendCodeData(text.toString()); eventBuilder.appendCodeOuterData(text.toString()); return; } // check for ignorable whitespace and add it to the skeleton if (text.isWhiteSpace() && !isInsideTextRun()) { if (bufferedWhitespace.length() <= 0) { // buffer the whitespace until we know that we are not inside // translatable text. bufferedWhitespace.append(text.toString()); } return; } if (canStartNewTextUnit()) { startTextUnit(text.toString()); } else { addToTextUnit(text.toString()); } } /** * Handle all Character entities. Default implementation converts entity to Unicode character. * * @param entity * - the character entity */ protected void handleNumericEntity(Segment entity) { String decodedText = CharacterReference.decode(entity.toString(), false); if (!eventBuilder.isCurrentTextUnit()) { eventBuilder.startTextUnit(); } eventBuilder.addToTextUnit(decodedText); } /** * Handle all numeric entities. Default implementation converts entity to Unicode character. * * @param entity * - the numeric entity */ protected void handleCharacterEntity(Segment entity) { String decodedText = CharacterReference.decode(entity.toString(), false); if (!eventBuilder.isCurrentTextUnit()) { eventBuilder.startTextUnit(); } eventBuilder.addToTextUnit(decodedText); } /** * Handle start tags. * * @param startTag */ protected void handleStartTag(StartTag startTag) { Map<String, String> attributes = new HashMap<String, String>(); attributes = startTag.getAttributes().populateMap(attributes, true); String idValue = null; RULE_TYPE ruleType = getConfig().getConditionalElementRuleType(startTag.getName(), attributes); // reset after each start tag so that we never // set a TextUnit name that id from a far out tag currentId = null; try { // if in excluded state everything is skeleton including text if (ruleState.isExludedState()) { addToDocumentPart(startTag.toString()); if (!startTag.isSyntacticalEmptyElementTag()) { updateStartTagRuleState(startTag.getName(), ruleType, idValue); } return; } List<PropertyTextUnitPlaceholder> propertyTextUnitPlaceholders; propertyTextUnitPlaceholders = createPropertyTextUnitPlaceholders(startTag); if (!startTag.isSyntacticalEmptyElementTag()) { updateStartTagRuleState(startTag.getName(), ruleType, idValue); } switch (ruleType) { case INLINE_EXCLUDED_ELEMENT: // special code like: "<ph translate='no'>some protected text with </ph>" // where the start tag, text and end tag are all one code if (canStartNewTextUnit()) { startTextUnit(); } addCodeToCurrentTextUnit(startTag, false); // addCodeToCurrentTextUnit puts tag in Code.data by default. // Move data to Code.outerData String d = eventBuilder.getCurrentCode().getData(); eventBuilder.getCurrentCode().setData(""); eventBuilder.getCurrentCode().setOuterData(d); break; case INLINE_ELEMENT: // check to see if we are inside a inline run that is excluded if (ruleState.isInlineExcludedState()) { eventBuilder.appendCodeOuterData(startTag.toString()); eventBuilder.appendCodeData(startTag.toString()); break; } if (canStartNewTextUnit()) { startTextUnit(); } addCodeToCurrentTextUnit(startTag); break; case ATTRIBUTES_ONLY: // we assume we have already ended any (non-complex) TextUnit in // the main while loop in AbstractMarkupFilter handleAttributesThatAppearAnywhere(propertyTextUnitPlaceholders, startTag); break; case GROUP_ELEMENT: handleAttributesThatAppearAnywhere(propertyTextUnitPlaceholders, startTag); break; case EXCLUDED_ELEMENT: handleAttributesThatAppearAnywhere(propertyTextUnitPlaceholders, startTag); break; case INCLUDED_ELEMENT: handleAttributesThatAppearAnywhere(propertyTextUnitPlaceholders, startTag); break; case TEXT_UNIT_ELEMENT: handleAttributesThatAppearAnywhere(propertyTextUnitPlaceholders, startTag); setTextUnitType(getConfig().getElementType(startTag)); break; default: handleAttributesThatAppearAnywhere(propertyTextUnitPlaceholders, startTag); } } finally { // A TextUnit may have already been created. Update its preserveWS field if (eventBuilder.isCurrentTextUnit()) { ITextUnit tu = eventBuilder.peekMostRecentTextUnit(); tu.setPreserveWhitespaces(ruleState.isPreserveWhitespaceState()); } } } protected void updateStartTagRuleState(String tag, RULE_TYPE ruleType, String idValue) { RULE_TYPE r = getConfig().getElementRuleTypeCandidate(tag); switch (r) { case INLINE_EXCLUDED_ELEMENT: case INLINE_ELEMENT: ruleState.pushInlineRule(tag, ruleType); break; case ATTRIBUTES_ONLY: // TODO: add a rule state for ATTRIBUTE_ONLY rules break; case GROUP_ELEMENT: ruleState.pushGroupRule(tag, ruleType); break; case EXCLUDED_ELEMENT: ruleState.pushExcludedRule(tag, ruleType); break; case INCLUDED_ELEMENT: ruleState.pushIncludedRule(tag, ruleType); break; case TEXT_UNIT_ELEMENT: ruleState.pushTextUnitRule(tag, ruleType, idValue); break; default: break; } // TODO: add conditional support for PRESERVE_WHITESPACE rules // does this tag have a PRESERVE_WHITESPACE rule? if (getConfig().isRuleType(tag, RULE_TYPE.PRESERVE_WHITESPACE)) { ruleState.pushPreserverWhitespaceRule(tag, true); setPreserveWhitespace(ruleState.isPreserveWhitespaceState()); } } protected RULE_TYPE updateEndTagRuleState(EndTag endTag) { RULE_TYPE ruleType = getConfig().getElementRuleTypeCandidate(endTag.getName()); RuleType currentState = null; switch (ruleType) { case INLINE_EXCLUDED_ELEMENT: case INLINE_ELEMENT: currentState = ruleState.popInlineRule(); ruleType = currentState.ruleType; break; case ATTRIBUTES_ONLY: // TODO: add a rule state for ATTRIBUTE_ONLY rules break; case GROUP_ELEMENT: currentState = ruleState.popGroupRule(); ruleType = currentState.ruleType; break; case EXCLUDED_ELEMENT: currentState = ruleState.popExcludedIncludedRule(); ruleType = currentState.ruleType; break; case INCLUDED_ELEMENT: currentState = ruleState.popExcludedIncludedRule(); ruleType = currentState.ruleType; break; case TEXT_UNIT_ELEMENT: currentState = ruleState.popTextUnitRule(); ruleType = currentState.ruleType; break; default: break; } if (currentState != null) { // if the end tag is not the same as what we found on the stack all bets are off if (!currentState.ruleName.equalsIgnoreCase(endTag.getName())) { String character = Integer.toString(endTag.getBegin()); throw new OkapiBadFilterInputException("End tag " + endTag.getName() + " and start tag " + currentState.ruleName + " do not match at character number " + character); } } return ruleType; } /* * catch tags which are not listed in the config but have attributes that require processing */ private void handleAttributesThatAppearAnywhere( List<PropertyTextUnitPlaceholder> propertyTextUnitPlaceholders, StartTag tag) { HashMap<String, String> attributeMap = new HashMap<String, String>(); switch (getConfig().getConditionalElementRuleType(tag.getName(), tag.getAttributes().populateMap(attributeMap, true))) { case TEXT_UNIT_ELEMENT: if (propertyTextUnitPlaceholders != null && !propertyTextUnitPlaceholders.isEmpty()) { startTextUnit(new GenericSkeleton(tag.toString()), propertyTextUnitPlaceholders); } else { startTextUnit(new GenericSkeleton(tag.toString())); } break; case GROUP_ELEMENT: if (propertyTextUnitPlaceholders != null && !propertyTextUnitPlaceholders.isEmpty()) { startGroup(new GenericSkeleton(tag.toString()), getConfig().getElementType(tag), getSrcLoc(), propertyTextUnitPlaceholders); } else { // no attributes that need processing - just treat as skeleton startGroup(new GenericSkeleton(tag.toString()), getConfig().getElementType(tag)); } break; default: if (propertyTextUnitPlaceholders != null && !propertyTextUnitPlaceholders.isEmpty()) { startDocumentPart(tag.toString(), tag.getName(), propertyTextUnitPlaceholders); endDocumentPart(); } else { // no attributes that need processing - just treat as skeleton addToDocumentPart(tag.toString()); } break; } } /** * Handle end tags, including empty tags. * * @param endTag */ protected void handleEndTag(EndTag endTag) { RULE_TYPE ruleType = RULE_TYPE.RULE_NOT_FOUND; // if in excluded state everything is skeleton including text if (ruleState.isExludedState()) { addToDocumentPart(endTag.toString()); updateEndTagRuleState(endTag); return; } ruleType = updateEndTagRuleState(endTag); switch (ruleType) { case INLINE_EXCLUDED_ELEMENT: eventBuilder.endCode(endTag.toString()); break; case INLINE_ELEMENT: // check to see if we are inside a inline run that is excluded if (ruleState.isInlineExcludedState()) { eventBuilder.appendCodeOuterData(endTag.toString()); eventBuilder.appendCodeData(endTag.toString()); break; } if (canStartNewTextUnit()) { startTextUnit(); } addCodeToCurrentTextUnit(endTag); break; case GROUP_ELEMENT: endGroup(new GenericSkeleton(endTag.toString())); break; case EXCLUDED_ELEMENT: addToDocumentPart(endTag.toString()); break; case INCLUDED_ELEMENT: addToDocumentPart(endTag.toString()); break; case TEXT_UNIT_ELEMENT: // if a pcdata subfilter is configured let it do the processsing if (pcdataSubfilter != null && isInsideTextRun()) { // remove the TextUnit we have accumulated since the start tag ITextUnit pcdata = popTempEvent().getTextUnit(); String parentId = eventBuilder.findMostRecentParentId(); pcdataSubfilter.close(); parentId = (parentId == null ? getDocumentId().getLastId() : parentId); SubFilterEventConverter converter = new SubFilterEventConverter(parentId, // the first GenericSkekeletonPart should be the start tag new GenericSkeleton(((GenericSkeleton)pcdata.getSkeleton()).getFirstPart().toString()), new GenericSkeleton(endTag.toString())); // TODO: only AbstractFilter subclasses can be used as subfilters!!! ((AbstractFilter)pcdataSubfilter).setParentId(parentId); pcdataSubfilter.open(new RawDocument(pcdata.getSource().toString(), getSrcLoc())); int tuChildCount = 0; while (pcdataSubfilter.hasNext()) { Event event = converter.convertEvent(pcdataSubfilter.next()); // we need to escape back to the original format if ("okf_html".equals(getConfig().getGlobalPCDATASubfilter())) { switch(event.getEventType()) { case DOCUMENT_PART: DocumentPart dp = event.getDocumentPart(); dp.setSkeleton(new GenericSkeleton(Util.escapeToXML(dp.getSkeleton().toString(), 0, true, null))); break; case TEXT_UNIT: ITextUnit tu = event.getTextUnit(); // subfiltered textunits can inherit name from a parent TU if (tu.getName() == null) { String parentName = eventBuilder.findMostRecentTextUnitName(); // we need to add a child id so each tu name is unique for this subfiltered content if (parentName != null) { parentName = parentName + "-" + Integer.toString(++tuChildCount); } tu.setName(parentName); } // escape the skeleton parts GenericSkeleton s = (GenericSkeleton)tu.getSkeleton(); - for (GenericSkeletonPart p : s.getParts()) { - if (p.getParent() == null) { - p.setData(Util.escapeToXML(p.getData().toString(), 0, true, null)); - } - } - tu.setSkeleton(s); + if (s != null) { + for (GenericSkeletonPart p : s.getParts()) { + if (p.getParent() == null) { + p.setData(Util.escapeToXML(p.getData().toString(), 0, true, null)); + } + } + tu.setSkeleton(s); + } // now escape all the code content List<Code> codes = tu.getSource().getFirstContent().getCodes(); for (Code c : codes) { c.setData(Util.escapeToXML(c.getData(), 0, true, null)); if (c.hasOuterData()) { c.setOuterData(Util.escapeToXML(c.getOuterData(), 0, true, null)); } } // now escape any remaining text TextFragment f = new TextFragment(Util.escapeToXML(tu.getSource().getFirstContent().getCodedText(), 0, true, null), codes); tu.setSourceContent(f); break; } } eventBuilder.addFilterEvent(event); } pcdataSubfilter.close(); } else { endTextUnit(new GenericSkeleton(endTag.toString())); } break; default: addToDocumentPart(endTag.toString()); break; } // TODO: add conditional support for PRESERVE_WHITESPACE rules // does this tag have a PRESERVE_WHITESPACE rule? if (getConfig().isRuleType(endTag.getName(), RULE_TYPE.PRESERVE_WHITESPACE)) { ruleState.popPreserverWhitespaceRule(); setPreserveWhitespace(ruleState.isPreserveWhitespaceState()); // handle cases such as xml:space where we popped on an element while // processing the attributes } else if (ruleState.peekPreserverWhitespaceRule().ruleName.equalsIgnoreCase(endTag.getName())) { ruleState.popPreserverWhitespaceRule(); setPreserveWhitespace(ruleState.isPreserveWhitespaceState()); } } /** * Handle anything else not classified by Jericho. * * @param tag */ protected void handleDocumentPart(Tag tag) { addToDocumentPart(tag.toString()); } /** * Some attributes names are converted to Okapi standards such as HTML charset to "encoding" and lang to "language" * * @param attrName * - the attribute name * @param attrValue * - the attribute value * @param tag * - the Jericho {@link Tag} that contains the attribute * @return the attribute name after it as passe through the normalization rules */ abstract protected String normalizeAttributeName(String attrName, String attrValue, Tag tag); /** * Add an {@link Code} to the current {@link TextUnit}. Throws an exception if there is no current {@link TextUnit}. * * @param tag * - the Jericho {@link Tag} that is converted to a Okpai {@link Code} */ protected void addCodeToCurrentTextUnit(Tag tag) { addCodeToCurrentTextUnit(tag, true); } /** * Add an {@link Code} to the current {@link TextUnit}. Throws an exception if there is no current {@link TextUnit}. * * @param tag * - the Jericho {@link Tag} that is converted to a Okpai {@link Code} * @param endCodeNow * - do we end the code now or delay so we can add more content to the code? * */ protected void addCodeToCurrentTextUnit(Tag tag, boolean endCodeNow) { List<PropertyTextUnitPlaceholder> propertyTextUnitPlaceholders; String literalTag = tag.toString(); TextFragment.TagType codeType; // start tag or empty tag if (tag.getTagType() == StartTagType.NORMAL || tag.getTagType() == StartTagType.UNREGISTERED) { StartTag startTag = ((StartTag) tag); // is this an empty tag? if (startTag.isSyntacticalEmptyElementTag()) { codeType = TextFragment.TagType.PLACEHOLDER; } else if (startTag.isEndTagRequired()) { if (ruleState.isInlineExcludedState()) { codeType = TextFragment.TagType.PLACEHOLDER; } else { codeType = TextFragment.TagType.OPENING; } } else { codeType = TextFragment.TagType.PLACEHOLDER; } // create a list of Property or Text placeholders for this tag // If this list is empty we know that there are no attributes that // need special processing propertyTextUnitPlaceholders = null; propertyTextUnitPlaceholders = createPropertyTextUnitPlaceholders(startTag); if (propertyTextUnitPlaceholders != null && !propertyTextUnitPlaceholders.isEmpty()) { // add code and process actionable attributes addToTextUnit(new Code(codeType, getConfig().getElementType(tag), literalTag), endCodeNow, propertyTextUnitPlaceholders); } else { // no actionable attributes, just add the code as-is addToTextUnit(new Code(codeType, getConfig().getElementType(tag), literalTag), endCodeNow); } } else { // end or unknown tag if (tag.getTagType() == EndTagType.NORMAL || tag.getTagType() == EndTagType.UNREGISTERED) { codeType = TextFragment.TagType.CLOSING; } else { codeType = TextFragment.TagType.PLACEHOLDER; } addToTextUnit(new Code(codeType, getConfig().getElementType(tag), literalTag)); } } /** * For the given Jericho {@link StartTag} parse out all the actionable attributes and and store them as * {@link PropertyTextUnitPlaceholder}. {@link PlaceholderAccessType} are set based on the filter configuration for * each attribute. for the attribute name and value. * * @param startTag * - Jericho {@link StartTag} * @return all actionable (translatable, writable or read-only) attributes found in the {@link StartTag} */ protected List<PropertyTextUnitPlaceholder> createPropertyTextUnitPlaceholders(StartTag startTag) { // list to hold the properties or TextUnits List<PropertyTextUnitPlaceholder> propertyOrTextUnitPlaceholders = new LinkedList<PropertyTextUnitPlaceholder>(); HashMap<String, String> attributeMap = new HashMap<String, String>(); for (Attribute attribute : startTag.parseAttributes()) { attributeMap.clear(); switch (getConfig().findMatchingAttributeRule(startTag.getName(), startTag.getAttributes().populateMap(attributeMap, true), attribute.getName())) { case ATTRIBUTE_TRANS: propertyOrTextUnitPlaceholders.add(createPropertyTextUnitPlaceholder( PlaceholderAccessType.TRANSLATABLE, attribute.getName(), attribute.getValue(), startTag, attribute)); break; case ATTRIBUTE_WRITABLE: // for these non-translatable (but localizable) attributes use the raw value // given by attribute.getValueSegment() to avoid any entity unescaping that might // produce illegal output propertyOrTextUnitPlaceholders.add(createPropertyTextUnitPlaceholder( PlaceholderAccessType.WRITABLE_PROPERTY, attribute.getName(), attribute.getValueSegment().toString(), startTag, attribute)); break; case ATTRIBUTE_READONLY: propertyOrTextUnitPlaceholders.add(createPropertyTextUnitPlaceholder( PlaceholderAccessType.READ_ONLY_PROPERTY, attribute.getName(), attribute.getValue(), startTag, attribute)); break; case ATTRIBUTE_ID: propertyOrTextUnitPlaceholders.add(createPropertyTextUnitPlaceholder( PlaceholderAccessType.NAME, attribute.getName(), attribute.getValue(), startTag, attribute)); currentId = attribute.getValue() + "-" + attribute.getName(); break; case ATTRIBUTE_PRESERVE_WHITESPACE: boolean preserveWS = getConfig().isPreserveWhitespaceCondition(attribute.getName(), attributeMap); boolean defaultWS = getConfig().isDefaultWhitespaceCondition(attribute.getName(), attributeMap); // if its not reserve or default then the rule doesn't apply if (preserveWS || defaultWS) { if (preserveWS) { ruleState.pushPreserverWhitespaceRule(startTag.getName(), true); } else if (defaultWS) { ruleState.pushPreserverWhitespaceRule(startTag.getName(), false); } setPreserveWhitespace(ruleState.isPreserveWhitespaceState()); propertyOrTextUnitPlaceholders.add(createPropertyTextUnitPlaceholder( PlaceholderAccessType.WRITABLE_PROPERTY, attribute.getName(), attribute.getValue(), startTag, attribute)); } break; default: break; } } return propertyOrTextUnitPlaceholders; } /** * Create a {@link PropertyTextUnitPlaceholder} given the supplied type, name and Jericho {@link Tag} and * {@link Attribute}. * * @param type * - {@link PlaceholderAccessType} is one of TRANSLATABLE, READ_ONLY_PROPERTY, WRITABLE_PROPERTY * @param name * - attribute name * @param value * - attribute value * @param tag * - Jericho {@link Tag} which contains the attribute * @param attribute * - attribute as a Jericho {@link Attribute} * @return a {@link PropertyTextUnitPlaceholder} representing the attribute */ protected PropertyTextUnitPlaceholder createPropertyTextUnitPlaceholder( PlaceholderAccessType type, String name, String value, Tag tag, Attribute attribute) { // offset of attribute int mainStartPos = attribute.getBegin() - tag.getBegin(); int mainEndPos = attribute.getEnd() - tag.getBegin(); // offset of value of the attribute int valueStartPos = attribute.getValueSegment().getBegin() - tag.getBegin(); int valueEndPos = attribute.getValueSegment().getEnd() - tag.getBegin(); return new PropertyTextUnitPlaceholder(type, normalizeAttributeName(name, value, tag), value, mainStartPos, mainEndPos, valueStartPos, valueEndPos); } /** * Is the input encoded as UTF-8? * * @return true if the document is in utf8 encoding. */ @Override protected boolean isUtf8Encoding() { return hasUtf8Encoding; } /** * Does the input have a UTF-8 Byte Order Mark? * * @return true if the document has a utf-8 byte order mark. */ @Override protected boolean isUtf8Bom() { return hasUtf8Bom; } /** * Does the input have a BOM? * * @return true if the document has a BOM. */ protected boolean isBOM() { return hasBOM; } /** * Does this document have a document encoding specified? * @return true if has meta tag with encoding, false otherwise */ protected boolean isDocumentEncoding() { return documentEncoding; } /** * * @return the preserveWhitespace boolean. */ protected boolean isPreserveWhitespace() { return ruleState.isPreserveWhitespaceState(); } protected void setPreserveWhitespace(boolean preserveWhitespace) { eventBuilder.setPreserveWhitespace(preserveWhitespace); } protected void setTextUnitPreserveWhitespace(boolean preserveWhitespace) { eventBuilder.setTextUnitPreserveWhitespace(preserveWhitespace); } protected void addToDocumentPart(String part) { eventBuilder.addToDocumentPart(part); } protected void addToTextUnit(String text) { eventBuilder.addToTextUnit(text); } protected void startTextUnit(String text) { eventBuilder.startTextUnit(text); setTextUnitName(currentId); } protected void setTextUnitName(String name) { String n = name; if (name == null) { // we have no name for this TU but lets check for a parent // name. All children will inherit this n = eventBuilder.findMostRecentTextUnitName(); } eventBuilder.setTextUnitName(n); currentId = null; } protected void setTextUnitType(String type) { eventBuilder.setTextUnitType(type); } protected void setTextUnitTranslatable(boolean translatable) { eventBuilder.setTextUnitTranslatable(translatable); } protected void setCurrentDocName(String currentDocName) { this.currentDocName = currentDocName; } protected String getCurrentDocName() { return currentDocName; } protected boolean canStartNewTextUnit() { return eventBuilder.canStartNewTextUnit(); } protected boolean isInsideTextRun() { return eventBuilder.isInsideTextRun(); } protected void addToTextUnit(Code code, boolean endCodeNow) { eventBuilder.addToTextUnit(code, endCodeNow); } protected void addToTextUnit(Code code) { eventBuilder.addToTextUnit(code); } protected void addToTextUnit(Code code, boolean endCodeNow, List<PropertyTextUnitPlaceholder> propertyTextUnitPlaceholders) { eventBuilder.addToTextUnit(code, endCodeNow, propertyTextUnitPlaceholders); } protected void addToTextUnit(Code code, List<PropertyTextUnitPlaceholder> propertyTextUnitPlaceholders) { eventBuilder.addToTextUnit(code, true, propertyTextUnitPlaceholders); } protected void endDocumentPart() { eventBuilder.endDocumentPart(); } protected void startDocumentPart(String part, String name, List<PropertyTextUnitPlaceholder> propertyTextUnitPlaceholders) { eventBuilder.startDocumentPart(part, name, propertyTextUnitPlaceholders); } protected void startGroup(GenericSkeleton startMarker, String commonTagType) { eventBuilder.startGroup(startMarker, commonTagType); } protected void startGroup(GenericSkeleton startMarker, String commonTagType, LocaleId locale, List<PropertyTextUnitPlaceholder> propertyTextUnitPlaceholders) { eventBuilder.startGroup(startMarker, commonTagType, locale, propertyTextUnitPlaceholders); } protected void startTextUnit(GenericSkeleton startMarker) { eventBuilder.startTextUnit(startMarker); setTextUnitName(currentId); } protected void startTextUnit(GenericSkeleton startMarker, List<PropertyTextUnitPlaceholder> propertyTextUnitPlaceholders) { eventBuilder.startTextUnit(startMarker, propertyTextUnitPlaceholders); setTextUnitName(currentId); } protected void endTextUnit(GenericSkeleton endMarker) { eventBuilder.endTextUnit(endMarker); } protected void endGroup(GenericSkeleton endMarker) { eventBuilder.endGroup(endMarker); } protected void startTextUnit() { eventBuilder.startTextUnit(); setTextUnitName(currentId); } protected long getTextUnitId() { return eventBuilder.getTextUnitId(); } protected void setTextUnitId(long id) { eventBuilder.setTextUnitId(id); } protected void setTextUnitMimeType(String mimeType) { eventBuilder.setTextUnitMimeType(mimeType); } protected long getDocumentPartId() { return eventBuilder.getDocumentPartId(); } protected void setDocumentPartId(long id) { eventBuilder.setDocumentPartId(id); } protected void appendToFirstSkeletonPart(String text) { eventBuilder.appendToFirstSkeletonPart(text); } protected void addFilterEvent(Event event) { eventBuilder.addFilterEvent(event); } protected Event popTempEvent() { return eventBuilder.popTempEvent(); } protected Event peekTempEvent() { return eventBuilder.peekTempEvent(); } protected ExtractionRuleState getRuleState() { return ruleState; } /** * @return the eventBuilder */ public EventBuilder getEventBuilder() { return eventBuilder; } /** * Sets the input document mime type. * * @param mimeType * the new mime type */ @Override public void setMimeType(String mimeType) { super.setMimeType(mimeType); } public StringBuilder getBufferedWhiteSpace() { return bufferedWhitespace; } }
true
true
protected void handleEndTag(EndTag endTag) { RULE_TYPE ruleType = RULE_TYPE.RULE_NOT_FOUND; // if in excluded state everything is skeleton including text if (ruleState.isExludedState()) { addToDocumentPart(endTag.toString()); updateEndTagRuleState(endTag); return; } ruleType = updateEndTagRuleState(endTag); switch (ruleType) { case INLINE_EXCLUDED_ELEMENT: eventBuilder.endCode(endTag.toString()); break; case INLINE_ELEMENT: // check to see if we are inside a inline run that is excluded if (ruleState.isInlineExcludedState()) { eventBuilder.appendCodeOuterData(endTag.toString()); eventBuilder.appendCodeData(endTag.toString()); break; } if (canStartNewTextUnit()) { startTextUnit(); } addCodeToCurrentTextUnit(endTag); break; case GROUP_ELEMENT: endGroup(new GenericSkeleton(endTag.toString())); break; case EXCLUDED_ELEMENT: addToDocumentPart(endTag.toString()); break; case INCLUDED_ELEMENT: addToDocumentPart(endTag.toString()); break; case TEXT_UNIT_ELEMENT: // if a pcdata subfilter is configured let it do the processsing if (pcdataSubfilter != null && isInsideTextRun()) { // remove the TextUnit we have accumulated since the start tag ITextUnit pcdata = popTempEvent().getTextUnit(); String parentId = eventBuilder.findMostRecentParentId(); pcdataSubfilter.close(); parentId = (parentId == null ? getDocumentId().getLastId() : parentId); SubFilterEventConverter converter = new SubFilterEventConverter(parentId, // the first GenericSkekeletonPart should be the start tag new GenericSkeleton(((GenericSkeleton)pcdata.getSkeleton()).getFirstPart().toString()), new GenericSkeleton(endTag.toString())); // TODO: only AbstractFilter subclasses can be used as subfilters!!! ((AbstractFilter)pcdataSubfilter).setParentId(parentId); pcdataSubfilter.open(new RawDocument(pcdata.getSource().toString(), getSrcLoc())); int tuChildCount = 0; while (pcdataSubfilter.hasNext()) { Event event = converter.convertEvent(pcdataSubfilter.next()); // we need to escape back to the original format if ("okf_html".equals(getConfig().getGlobalPCDATASubfilter())) { switch(event.getEventType()) { case DOCUMENT_PART: DocumentPart dp = event.getDocumentPart(); dp.setSkeleton(new GenericSkeleton(Util.escapeToXML(dp.getSkeleton().toString(), 0, true, null))); break; case TEXT_UNIT: ITextUnit tu = event.getTextUnit(); // subfiltered textunits can inherit name from a parent TU if (tu.getName() == null) { String parentName = eventBuilder.findMostRecentTextUnitName(); // we need to add a child id so each tu name is unique for this subfiltered content if (parentName != null) { parentName = parentName + "-" + Integer.toString(++tuChildCount); } tu.setName(parentName); } // escape the skeleton parts GenericSkeleton s = (GenericSkeleton)tu.getSkeleton(); for (GenericSkeletonPart p : s.getParts()) { if (p.getParent() == null) { p.setData(Util.escapeToXML(p.getData().toString(), 0, true, null)); } } tu.setSkeleton(s); // now escape all the code content List<Code> codes = tu.getSource().getFirstContent().getCodes(); for (Code c : codes) { c.setData(Util.escapeToXML(c.getData(), 0, true, null)); if (c.hasOuterData()) { c.setOuterData(Util.escapeToXML(c.getOuterData(), 0, true, null)); } } // now escape any remaining text TextFragment f = new TextFragment(Util.escapeToXML(tu.getSource().getFirstContent().getCodedText(), 0, true, null), codes); tu.setSourceContent(f); break; } } eventBuilder.addFilterEvent(event); } pcdataSubfilter.close(); } else { endTextUnit(new GenericSkeleton(endTag.toString())); } break; default: addToDocumentPart(endTag.toString()); break; } // TODO: add conditional support for PRESERVE_WHITESPACE rules // does this tag have a PRESERVE_WHITESPACE rule? if (getConfig().isRuleType(endTag.getName(), RULE_TYPE.PRESERVE_WHITESPACE)) { ruleState.popPreserverWhitespaceRule(); setPreserveWhitespace(ruleState.isPreserveWhitespaceState()); // handle cases such as xml:space where we popped on an element while // processing the attributes } else if (ruleState.peekPreserverWhitespaceRule().ruleName.equalsIgnoreCase(endTag.getName())) { ruleState.popPreserverWhitespaceRule(); setPreserveWhitespace(ruleState.isPreserveWhitespaceState()); } }
protected void handleEndTag(EndTag endTag) { RULE_TYPE ruleType = RULE_TYPE.RULE_NOT_FOUND; // if in excluded state everything is skeleton including text if (ruleState.isExludedState()) { addToDocumentPart(endTag.toString()); updateEndTagRuleState(endTag); return; } ruleType = updateEndTagRuleState(endTag); switch (ruleType) { case INLINE_EXCLUDED_ELEMENT: eventBuilder.endCode(endTag.toString()); break; case INLINE_ELEMENT: // check to see if we are inside a inline run that is excluded if (ruleState.isInlineExcludedState()) { eventBuilder.appendCodeOuterData(endTag.toString()); eventBuilder.appendCodeData(endTag.toString()); break; } if (canStartNewTextUnit()) { startTextUnit(); } addCodeToCurrentTextUnit(endTag); break; case GROUP_ELEMENT: endGroup(new GenericSkeleton(endTag.toString())); break; case EXCLUDED_ELEMENT: addToDocumentPart(endTag.toString()); break; case INCLUDED_ELEMENT: addToDocumentPart(endTag.toString()); break; case TEXT_UNIT_ELEMENT: // if a pcdata subfilter is configured let it do the processsing if (pcdataSubfilter != null && isInsideTextRun()) { // remove the TextUnit we have accumulated since the start tag ITextUnit pcdata = popTempEvent().getTextUnit(); String parentId = eventBuilder.findMostRecentParentId(); pcdataSubfilter.close(); parentId = (parentId == null ? getDocumentId().getLastId() : parentId); SubFilterEventConverter converter = new SubFilterEventConverter(parentId, // the first GenericSkekeletonPart should be the start tag new GenericSkeleton(((GenericSkeleton)pcdata.getSkeleton()).getFirstPart().toString()), new GenericSkeleton(endTag.toString())); // TODO: only AbstractFilter subclasses can be used as subfilters!!! ((AbstractFilter)pcdataSubfilter).setParentId(parentId); pcdataSubfilter.open(new RawDocument(pcdata.getSource().toString(), getSrcLoc())); int tuChildCount = 0; while (pcdataSubfilter.hasNext()) { Event event = converter.convertEvent(pcdataSubfilter.next()); // we need to escape back to the original format if ("okf_html".equals(getConfig().getGlobalPCDATASubfilter())) { switch(event.getEventType()) { case DOCUMENT_PART: DocumentPart dp = event.getDocumentPart(); dp.setSkeleton(new GenericSkeleton(Util.escapeToXML(dp.getSkeleton().toString(), 0, true, null))); break; case TEXT_UNIT: ITextUnit tu = event.getTextUnit(); // subfiltered textunits can inherit name from a parent TU if (tu.getName() == null) { String parentName = eventBuilder.findMostRecentTextUnitName(); // we need to add a child id so each tu name is unique for this subfiltered content if (parentName != null) { parentName = parentName + "-" + Integer.toString(++tuChildCount); } tu.setName(parentName); } // escape the skeleton parts GenericSkeleton s = (GenericSkeleton)tu.getSkeleton(); if (s != null) { for (GenericSkeletonPart p : s.getParts()) { if (p.getParent() == null) { p.setData(Util.escapeToXML(p.getData().toString(), 0, true, null)); } } tu.setSkeleton(s); } // now escape all the code content List<Code> codes = tu.getSource().getFirstContent().getCodes(); for (Code c : codes) { c.setData(Util.escapeToXML(c.getData(), 0, true, null)); if (c.hasOuterData()) { c.setOuterData(Util.escapeToXML(c.getOuterData(), 0, true, null)); } } // now escape any remaining text TextFragment f = new TextFragment(Util.escapeToXML(tu.getSource().getFirstContent().getCodedText(), 0, true, null), codes); tu.setSourceContent(f); break; } } eventBuilder.addFilterEvent(event); } pcdataSubfilter.close(); } else { endTextUnit(new GenericSkeleton(endTag.toString())); } break; default: addToDocumentPart(endTag.toString()); break; } // TODO: add conditional support for PRESERVE_WHITESPACE rules // does this tag have a PRESERVE_WHITESPACE rule? if (getConfig().isRuleType(endTag.getName(), RULE_TYPE.PRESERVE_WHITESPACE)) { ruleState.popPreserverWhitespaceRule(); setPreserveWhitespace(ruleState.isPreserveWhitespaceState()); // handle cases such as xml:space where we popped on an element while // processing the attributes } else if (ruleState.peekPreserverWhitespaceRule().ruleName.equalsIgnoreCase(endTag.getName())) { ruleState.popPreserverWhitespaceRule(); setPreserveWhitespace(ruleState.isPreserveWhitespaceState()); } }
diff --git a/src/paulscode/android/mupen64plusae/MenuActivity.java b/src/paulscode/android/mupen64plusae/MenuActivity.java index f9d92150..775e202f 100644 --- a/src/paulscode/android/mupen64plusae/MenuActivity.java +++ b/src/paulscode/android/mupen64plusae/MenuActivity.java @@ -1,339 +1,339 @@ package paulscode.android.mupen64plusae; import java.io.File; import java.util.Locale; import android.app.DialogFragment; import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.preference.ListPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceActivity; import android.util.Log; import android.view.Gravity; import android.view.KeyEvent; import android.widget.Toast; // TODO: Comment thoroughly public class MenuActivity extends PreferenceActivity implements IOptionChooser { public static MenuActivity mInstance = null; // private OptionArrayAdapter optionArrayAdapter; // Array of menu options private static NotificationManager notificationManager = null; public static Config mupen64plus_cfg = new Config( Globals.DataDir + "/mupen64plus.cfg" ); public static Config gui_cfg = new Config( Globals.DataDir + "/data/gui.cfg" ); public static Config error_log = new Config( Globals.DataDir + "/error.log" ); @Override public void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); mInstance = this; Globals.checkLocale( this ); if( notificationManager == null ) notificationManager = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE ); notificationManager.cancel( Globals.NOTIFICATION_ID ); if( Globals.DataDir == null || Globals.DataDir.length() == 0 || !Globals.DataDirChecked ) //NOTE: isEmpty() not supported on some devices { Globals.PackageName = getPackageName(); Globals.LibsDir = "/data/data/" + Globals.PackageName; Globals.StorageDir = Globals.DownloadToSdcard ? Environment.getExternalStorageDirectory().getAbsolutePath() : getFilesDir().getAbsolutePath(); Globals.DataDir = Globals.DownloadToSdcard ? Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + Globals.PackageName : getFilesDir().getAbsolutePath(); Globals.DataDirChecked = true; mupen64plus_cfg = new Config( Globals.DataDir + "/mupen64plus.cfg" ); gui_cfg = new Config( Globals.DataDir + "/data/gui.cfg" ); error_log = new Config( Globals.DataDir + "/error.log" ); } Updater.checkFirstRun( this ); if( !Updater.checkv1_9( this ) ) { finish(); return; } Updater.checkCfgVer( this ); String val = gui_cfg.get( "GAME_PAD", "redraw_all" ); if( val != null ) MenuSkinsGamepadActivity.redrawAll = ( val.equals( "1" ) ? true : false ); val = gui_cfg.get( "KEYS", "disable_volume_keys" ); if( val != null ) // Remember the choice that was made about the volume keys Globals.volumeKeysDisabled = val.equals( "1" ) ? true : false; val = gui_cfg.get( "VIDEO_PLUGIN", "screen_stretch" ); if( val != null ) Globals.screen_stretch = ( val.equals( "1" ) ? true : false ); val = gui_cfg.get( "VIDEO_PLUGIN", "auto_frameskip" ); if( val != null ) Globals.auto_frameskip = ( val.equals( "1" ) ? true : false ); val = gui_cfg.get( "VIDEO_PLUGIN", "max_frameskip" ); if( val != null ) { try { // Make sure a valid integer was entered Globals.max_frameskip = Integer.valueOf( val ); } catch( NumberFormatException nfe ) {} // Skip it if this happens } val = gui_cfg.get( "GENERAL", "auto_save" ); if( val != null ) Globals.auto_save = ( val.equals( "1" ) ? true : false ); val = gui_cfg.get( "TOUCH_PAD", "is_xperia_play" ); if( val != null ) Globals.isXperiaPlay = ( val.equals( "1" ) ? true : false ); // Load preferences from XML addPreferencesFromResource( R.layout.preferences_menu ); final Preference menuOpenROM = findPreference( "menuOpenROM" ); menuOpenROM.setOnPreferenceClickListener( new OnPreferenceClickListener() { public boolean onPreferenceClick( Preference preference ) { // Open the file chooser to pick a ROM String path = gui_cfg.get( "LAST_SESSION", "rom_folder" ); if( path == null || path.length() < 1 ) FileChooserActivity.startPath = Globals.DataDir; else FileChooserActivity.startPath = path; FileChooserActivity.extensions = ".z64.v64.n64.zip"; FileChooserActivity.parentMenu = null; FileChooserActivity.function = FileChooserActivity.FUNCTION_ROM; Intent intent = new Intent( mInstance, FileChooserActivity.class ); intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP ); startActivity( intent ); return true; } }); final Preference menuResume = findPreference( "menuResume" ); menuResume.setOnPreferenceClickListener( new OnPreferenceClickListener() { public boolean onPreferenceClick( Preference preference ) { // Resume the last game File f = new File( Globals.StorageDir ); if( !f.exists() ) { Log.e( "MenuActivity", "SD Card not accessable in method onListItemClick (menuResume)" ); Runnable toastMessager = new Runnable() { public void run() { Toast toast = Toast.makeText( MenuActivity.mInstance, "App data not accessible (cable plugged in \"USB Mass Storage Device\" mode?)", Toast.LENGTH_LONG ); toast.setGravity( Gravity.BOTTOM, 0, 0 ); toast.show(); } }; runOnUiThread( toastMessager ); return true; } mupen64plus_cfg.save(); gui_cfg.save(); Globals.chosenROM = gui_cfg.get( "LAST_SESSION", "rom" ); GameActivityCommon.resumeLastSession = true; Intent intent; if( Globals.isXperiaPlay ) intent = new Intent( mInstance, GameActivityXperiaPlay.class ); else intent = new Intent( mInstance, GameActivity.class ); intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP ); startActivity( intent ); mInstance.finish(); mInstance = null; return true; } }); final Preference menuSettings = findPreference( "menuSettings" ); menuSettings.setOnPreferenceClickListener( new OnPreferenceClickListener() { public boolean onPreferenceClick( Preference preference ) { // Configure the plug-ins Intent intent = new Intent( mInstance, MenuSettingsActivity.class ); intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP ); startActivity( intent ); return true; } }); final Preference menuHelp = findPreference( "menuHelp" ); menuHelp.setOnPreferenceClickListener( new OnPreferenceClickListener() { public boolean onPreferenceClick( Preference preference ) { // Visit the FAQ page (opens browser) try { Intent browserIntent = new Intent( Intent.ACTION_VIEW, Uri.parse( "http://www.paulscode.com/forum/index.php?topic=197.msg3018#msg3018" ) ); startActivity( browserIntent ); } catch( Exception e ) { Log.e( "MenuActivity", "Unable to open the FAQ page", e ); Runnable toastMessager = new Runnable() { public void run() { Toast toast = Toast.makeText( MenuActivity.mInstance, "Problem opening the browser, please report at paulscode.com", Toast.LENGTH_LONG ); toast.setGravity( Gravity.BOTTOM, 0, 0 ); toast.show(); } }; runOnUiThread( toastMessager ); } return true; } }); final Preference menuCredits = findPreference( "menuCredits" ); menuCredits.setOnPreferenceClickListener( new OnPreferenceClickListener() { public boolean onPreferenceClick( Preference preference ) { // Keep things neat - String title = getString(R.string.app_credits_title); + String title = getString(R.string.main_credits); String message = getString(R.string.app_credits); // Show credits dialog DialogFragment credits = AlertFragment.newInstance(title, message); credits.show(getFragmentManager(), "creditsDialog"); return true; } }); final Preference menuCheats = findPreference( "menuCheats" ); menuCheats.setOnPreferenceClickListener( new OnPreferenceClickListener() { public boolean onPreferenceClick( Preference preference ) { // Open the file chooser to pick a ROM String path = gui_cfg.get( "LAST_SESSION", "rom_folder" ); if( path == null || path.length() < 1 ) FileChooserActivity.startPath = Globals.DataDir; else FileChooserActivity.startPath = path; FileChooserActivity.extensions = ".z64.v64.n64.zip"; FileChooserActivity.parentMenu = MenuActivity.this; FileChooserActivity.function = FileChooserActivity.FUNCTION_ROM; Intent intent = new Intent( mInstance, FileChooserActivity.class ); intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP ); startActivity( intent ); return true; } }); final ListPreference menuSettingsLanguage = (ListPreference) findPreference( "menuSettingsLanguage" ); menuSettingsLanguage.setOnPreferenceChangeListener( new OnPreferenceChangeListener() { public boolean onPreferenceChange( Preference preference, Object newValue ) { String code = String.valueOf( newValue ); if( Globals.locale_default == null ) Globals.locale_default = getBaseContext().getResources().getConfiguration().locale; if( code == null || code.equals( "00" ) || code.length() != 2 ) Globals.locale = Globals.locale_default; else Globals.locale = new Locale( code ); Intent intent = getIntent(); overridePendingTransition( 0, 0 ); intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP ); intent.addFlags( Intent.FLAG_ACTIVITY_NO_ANIMATION ); finish(); overridePendingTransition( 0, 0 ); startActivity(intent); return true; } }); final Preference menuClose = findPreference( "menuClose" ); menuClose.setOnPreferenceClickListener( new OnPreferenceClickListener() { public boolean onPreferenceClick( Preference preference ) { // Shut down the app File f = new File( Globals.StorageDir ); if( f.exists() ) { mupen64plus_cfg.save(); gui_cfg.save(); } mInstance.finish(); return true; } }); Globals.errorMessage = error_log.get( "OPEN_ROM", "fail_crash" ); if( Globals.errorMessage != null && Globals.errorMessage.length() > 0 ) { Runnable toastMessager = new Runnable() { public void run() { Toast toast = Toast.makeText( MenuActivity.mInstance, Globals.errorMessage, Toast.LENGTH_LONG ); toast.setGravity( Gravity.BOTTOM, 0, 0 ); toast.show(); } }; runOnUiThread( toastMessager ); } error_log.put( "OPEN_ROM", "fail_crash", "" ); error_log.save(); Globals.errorMessage = null; } @Override public boolean onKeyDown( int keyCode, KeyEvent event ) { if( keyCode == KeyEvent.KEYCODE_BACK ) return true; return false; } @Override public boolean onKeyUp( int keyCode, KeyEvent event ) { if( keyCode == KeyEvent.KEYCODE_BACK ) return true; return false; } public void optionChosen( String option ) { // selected a ROM file for cheats if( option == null ) { Log.e( "MenuActivity", "option null in method optionChosen" ); return; } MenuCheatsActivity.CRC = Utility.getHeaderCRC( option ); if( MenuCheatsActivity.CRC == null ) { Log.e( "MenuActivity", "getHeaderCRC returned null in method optionChosen" ); return; } MenuCheatsActivity.ROM = option; Intent intent = new Intent( mInstance, MenuCheatsActivity.class ); intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP ); startActivity( intent ); } }
true
true
public void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); mInstance = this; Globals.checkLocale( this ); if( notificationManager == null ) notificationManager = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE ); notificationManager.cancel( Globals.NOTIFICATION_ID ); if( Globals.DataDir == null || Globals.DataDir.length() == 0 || !Globals.DataDirChecked ) //NOTE: isEmpty() not supported on some devices { Globals.PackageName = getPackageName(); Globals.LibsDir = "/data/data/" + Globals.PackageName; Globals.StorageDir = Globals.DownloadToSdcard ? Environment.getExternalStorageDirectory().getAbsolutePath() : getFilesDir().getAbsolutePath(); Globals.DataDir = Globals.DownloadToSdcard ? Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + Globals.PackageName : getFilesDir().getAbsolutePath(); Globals.DataDirChecked = true; mupen64plus_cfg = new Config( Globals.DataDir + "/mupen64plus.cfg" ); gui_cfg = new Config( Globals.DataDir + "/data/gui.cfg" ); error_log = new Config( Globals.DataDir + "/error.log" ); } Updater.checkFirstRun( this ); if( !Updater.checkv1_9( this ) ) { finish(); return; } Updater.checkCfgVer( this ); String val = gui_cfg.get( "GAME_PAD", "redraw_all" ); if( val != null ) MenuSkinsGamepadActivity.redrawAll = ( val.equals( "1" ) ? true : false ); val = gui_cfg.get( "KEYS", "disable_volume_keys" ); if( val != null ) // Remember the choice that was made about the volume keys Globals.volumeKeysDisabled = val.equals( "1" ) ? true : false; val = gui_cfg.get( "VIDEO_PLUGIN", "screen_stretch" ); if( val != null ) Globals.screen_stretch = ( val.equals( "1" ) ? true : false ); val = gui_cfg.get( "VIDEO_PLUGIN", "auto_frameskip" ); if( val != null ) Globals.auto_frameskip = ( val.equals( "1" ) ? true : false ); val = gui_cfg.get( "VIDEO_PLUGIN", "max_frameskip" ); if( val != null ) { try { // Make sure a valid integer was entered Globals.max_frameskip = Integer.valueOf( val ); } catch( NumberFormatException nfe ) {} // Skip it if this happens } val = gui_cfg.get( "GENERAL", "auto_save" ); if( val != null ) Globals.auto_save = ( val.equals( "1" ) ? true : false ); val = gui_cfg.get( "TOUCH_PAD", "is_xperia_play" ); if( val != null ) Globals.isXperiaPlay = ( val.equals( "1" ) ? true : false ); // Load preferences from XML addPreferencesFromResource( R.layout.preferences_menu ); final Preference menuOpenROM = findPreference( "menuOpenROM" ); menuOpenROM.setOnPreferenceClickListener( new OnPreferenceClickListener() { public boolean onPreferenceClick( Preference preference ) { // Open the file chooser to pick a ROM String path = gui_cfg.get( "LAST_SESSION", "rom_folder" ); if( path == null || path.length() < 1 ) FileChooserActivity.startPath = Globals.DataDir; else FileChooserActivity.startPath = path; FileChooserActivity.extensions = ".z64.v64.n64.zip"; FileChooserActivity.parentMenu = null; FileChooserActivity.function = FileChooserActivity.FUNCTION_ROM; Intent intent = new Intent( mInstance, FileChooserActivity.class ); intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP ); startActivity( intent ); return true; } }); final Preference menuResume = findPreference( "menuResume" ); menuResume.setOnPreferenceClickListener( new OnPreferenceClickListener() { public boolean onPreferenceClick( Preference preference ) { // Resume the last game File f = new File( Globals.StorageDir ); if( !f.exists() ) { Log.e( "MenuActivity", "SD Card not accessable in method onListItemClick (menuResume)" ); Runnable toastMessager = new Runnable() { public void run() { Toast toast = Toast.makeText( MenuActivity.mInstance, "App data not accessible (cable plugged in \"USB Mass Storage Device\" mode?)", Toast.LENGTH_LONG ); toast.setGravity( Gravity.BOTTOM, 0, 0 ); toast.show(); } }; runOnUiThread( toastMessager ); return true; } mupen64plus_cfg.save(); gui_cfg.save(); Globals.chosenROM = gui_cfg.get( "LAST_SESSION", "rom" ); GameActivityCommon.resumeLastSession = true; Intent intent; if( Globals.isXperiaPlay ) intent = new Intent( mInstance, GameActivityXperiaPlay.class ); else intent = new Intent( mInstance, GameActivity.class ); intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP ); startActivity( intent ); mInstance.finish(); mInstance = null; return true; } }); final Preference menuSettings = findPreference( "menuSettings" ); menuSettings.setOnPreferenceClickListener( new OnPreferenceClickListener() { public boolean onPreferenceClick( Preference preference ) { // Configure the plug-ins Intent intent = new Intent( mInstance, MenuSettingsActivity.class ); intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP ); startActivity( intent ); return true; } }); final Preference menuHelp = findPreference( "menuHelp" ); menuHelp.setOnPreferenceClickListener( new OnPreferenceClickListener() { public boolean onPreferenceClick( Preference preference ) { // Visit the FAQ page (opens browser) try { Intent browserIntent = new Intent( Intent.ACTION_VIEW, Uri.parse( "http://www.paulscode.com/forum/index.php?topic=197.msg3018#msg3018" ) ); startActivity( browserIntent ); } catch( Exception e ) { Log.e( "MenuActivity", "Unable to open the FAQ page", e ); Runnable toastMessager = new Runnable() { public void run() { Toast toast = Toast.makeText( MenuActivity.mInstance, "Problem opening the browser, please report at paulscode.com", Toast.LENGTH_LONG ); toast.setGravity( Gravity.BOTTOM, 0, 0 ); toast.show(); } }; runOnUiThread( toastMessager ); } return true; } }); final Preference menuCredits = findPreference( "menuCredits" ); menuCredits.setOnPreferenceClickListener( new OnPreferenceClickListener() { public boolean onPreferenceClick( Preference preference ) { // Keep things neat String title = getString(R.string.app_credits_title); String message = getString(R.string.app_credits); // Show credits dialog DialogFragment credits = AlertFragment.newInstance(title, message); credits.show(getFragmentManager(), "creditsDialog"); return true; } }); final Preference menuCheats = findPreference( "menuCheats" ); menuCheats.setOnPreferenceClickListener( new OnPreferenceClickListener() { public boolean onPreferenceClick( Preference preference ) { // Open the file chooser to pick a ROM String path = gui_cfg.get( "LAST_SESSION", "rom_folder" ); if( path == null || path.length() < 1 ) FileChooserActivity.startPath = Globals.DataDir; else FileChooserActivity.startPath = path; FileChooserActivity.extensions = ".z64.v64.n64.zip"; FileChooserActivity.parentMenu = MenuActivity.this; FileChooserActivity.function = FileChooserActivity.FUNCTION_ROM; Intent intent = new Intent( mInstance, FileChooserActivity.class ); intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP ); startActivity( intent ); return true; } }); final ListPreference menuSettingsLanguage = (ListPreference) findPreference( "menuSettingsLanguage" ); menuSettingsLanguage.setOnPreferenceChangeListener( new OnPreferenceChangeListener() { public boolean onPreferenceChange( Preference preference, Object newValue ) { String code = String.valueOf( newValue ); if( Globals.locale_default == null ) Globals.locale_default = getBaseContext().getResources().getConfiguration().locale; if( code == null || code.equals( "00" ) || code.length() != 2 ) Globals.locale = Globals.locale_default; else Globals.locale = new Locale( code ); Intent intent = getIntent(); overridePendingTransition( 0, 0 ); intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP ); intent.addFlags( Intent.FLAG_ACTIVITY_NO_ANIMATION ); finish(); overridePendingTransition( 0, 0 ); startActivity(intent); return true; } }); final Preference menuClose = findPreference( "menuClose" ); menuClose.setOnPreferenceClickListener( new OnPreferenceClickListener() { public boolean onPreferenceClick( Preference preference ) { // Shut down the app File f = new File( Globals.StorageDir ); if( f.exists() ) { mupen64plus_cfg.save(); gui_cfg.save(); } mInstance.finish(); return true; } }); Globals.errorMessage = error_log.get( "OPEN_ROM", "fail_crash" ); if( Globals.errorMessage != null && Globals.errorMessage.length() > 0 ) { Runnable toastMessager = new Runnable() { public void run() { Toast toast = Toast.makeText( MenuActivity.mInstance, Globals.errorMessage, Toast.LENGTH_LONG ); toast.setGravity( Gravity.BOTTOM, 0, 0 ); toast.show(); } }; runOnUiThread( toastMessager ); } error_log.put( "OPEN_ROM", "fail_crash", "" ); error_log.save(); Globals.errorMessage = null; }
public void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); mInstance = this; Globals.checkLocale( this ); if( notificationManager == null ) notificationManager = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE ); notificationManager.cancel( Globals.NOTIFICATION_ID ); if( Globals.DataDir == null || Globals.DataDir.length() == 0 || !Globals.DataDirChecked ) //NOTE: isEmpty() not supported on some devices { Globals.PackageName = getPackageName(); Globals.LibsDir = "/data/data/" + Globals.PackageName; Globals.StorageDir = Globals.DownloadToSdcard ? Environment.getExternalStorageDirectory().getAbsolutePath() : getFilesDir().getAbsolutePath(); Globals.DataDir = Globals.DownloadToSdcard ? Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + Globals.PackageName : getFilesDir().getAbsolutePath(); Globals.DataDirChecked = true; mupen64plus_cfg = new Config( Globals.DataDir + "/mupen64plus.cfg" ); gui_cfg = new Config( Globals.DataDir + "/data/gui.cfg" ); error_log = new Config( Globals.DataDir + "/error.log" ); } Updater.checkFirstRun( this ); if( !Updater.checkv1_9( this ) ) { finish(); return; } Updater.checkCfgVer( this ); String val = gui_cfg.get( "GAME_PAD", "redraw_all" ); if( val != null ) MenuSkinsGamepadActivity.redrawAll = ( val.equals( "1" ) ? true : false ); val = gui_cfg.get( "KEYS", "disable_volume_keys" ); if( val != null ) // Remember the choice that was made about the volume keys Globals.volumeKeysDisabled = val.equals( "1" ) ? true : false; val = gui_cfg.get( "VIDEO_PLUGIN", "screen_stretch" ); if( val != null ) Globals.screen_stretch = ( val.equals( "1" ) ? true : false ); val = gui_cfg.get( "VIDEO_PLUGIN", "auto_frameskip" ); if( val != null ) Globals.auto_frameskip = ( val.equals( "1" ) ? true : false ); val = gui_cfg.get( "VIDEO_PLUGIN", "max_frameskip" ); if( val != null ) { try { // Make sure a valid integer was entered Globals.max_frameskip = Integer.valueOf( val ); } catch( NumberFormatException nfe ) {} // Skip it if this happens } val = gui_cfg.get( "GENERAL", "auto_save" ); if( val != null ) Globals.auto_save = ( val.equals( "1" ) ? true : false ); val = gui_cfg.get( "TOUCH_PAD", "is_xperia_play" ); if( val != null ) Globals.isXperiaPlay = ( val.equals( "1" ) ? true : false ); // Load preferences from XML addPreferencesFromResource( R.layout.preferences_menu ); final Preference menuOpenROM = findPreference( "menuOpenROM" ); menuOpenROM.setOnPreferenceClickListener( new OnPreferenceClickListener() { public boolean onPreferenceClick( Preference preference ) { // Open the file chooser to pick a ROM String path = gui_cfg.get( "LAST_SESSION", "rom_folder" ); if( path == null || path.length() < 1 ) FileChooserActivity.startPath = Globals.DataDir; else FileChooserActivity.startPath = path; FileChooserActivity.extensions = ".z64.v64.n64.zip"; FileChooserActivity.parentMenu = null; FileChooserActivity.function = FileChooserActivity.FUNCTION_ROM; Intent intent = new Intent( mInstance, FileChooserActivity.class ); intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP ); startActivity( intent ); return true; } }); final Preference menuResume = findPreference( "menuResume" ); menuResume.setOnPreferenceClickListener( new OnPreferenceClickListener() { public boolean onPreferenceClick( Preference preference ) { // Resume the last game File f = new File( Globals.StorageDir ); if( !f.exists() ) { Log.e( "MenuActivity", "SD Card not accessable in method onListItemClick (menuResume)" ); Runnable toastMessager = new Runnable() { public void run() { Toast toast = Toast.makeText( MenuActivity.mInstance, "App data not accessible (cable plugged in \"USB Mass Storage Device\" mode?)", Toast.LENGTH_LONG ); toast.setGravity( Gravity.BOTTOM, 0, 0 ); toast.show(); } }; runOnUiThread( toastMessager ); return true; } mupen64plus_cfg.save(); gui_cfg.save(); Globals.chosenROM = gui_cfg.get( "LAST_SESSION", "rom" ); GameActivityCommon.resumeLastSession = true; Intent intent; if( Globals.isXperiaPlay ) intent = new Intent( mInstance, GameActivityXperiaPlay.class ); else intent = new Intent( mInstance, GameActivity.class ); intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP ); startActivity( intent ); mInstance.finish(); mInstance = null; return true; } }); final Preference menuSettings = findPreference( "menuSettings" ); menuSettings.setOnPreferenceClickListener( new OnPreferenceClickListener() { public boolean onPreferenceClick( Preference preference ) { // Configure the plug-ins Intent intent = new Intent( mInstance, MenuSettingsActivity.class ); intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP ); startActivity( intent ); return true; } }); final Preference menuHelp = findPreference( "menuHelp" ); menuHelp.setOnPreferenceClickListener( new OnPreferenceClickListener() { public boolean onPreferenceClick( Preference preference ) { // Visit the FAQ page (opens browser) try { Intent browserIntent = new Intent( Intent.ACTION_VIEW, Uri.parse( "http://www.paulscode.com/forum/index.php?topic=197.msg3018#msg3018" ) ); startActivity( browserIntent ); } catch( Exception e ) { Log.e( "MenuActivity", "Unable to open the FAQ page", e ); Runnable toastMessager = new Runnable() { public void run() { Toast toast = Toast.makeText( MenuActivity.mInstance, "Problem opening the browser, please report at paulscode.com", Toast.LENGTH_LONG ); toast.setGravity( Gravity.BOTTOM, 0, 0 ); toast.show(); } }; runOnUiThread( toastMessager ); } return true; } }); final Preference menuCredits = findPreference( "menuCredits" ); menuCredits.setOnPreferenceClickListener( new OnPreferenceClickListener() { public boolean onPreferenceClick( Preference preference ) { // Keep things neat String title = getString(R.string.main_credits); String message = getString(R.string.app_credits); // Show credits dialog DialogFragment credits = AlertFragment.newInstance(title, message); credits.show(getFragmentManager(), "creditsDialog"); return true; } }); final Preference menuCheats = findPreference( "menuCheats" ); menuCheats.setOnPreferenceClickListener( new OnPreferenceClickListener() { public boolean onPreferenceClick( Preference preference ) { // Open the file chooser to pick a ROM String path = gui_cfg.get( "LAST_SESSION", "rom_folder" ); if( path == null || path.length() < 1 ) FileChooserActivity.startPath = Globals.DataDir; else FileChooserActivity.startPath = path; FileChooserActivity.extensions = ".z64.v64.n64.zip"; FileChooserActivity.parentMenu = MenuActivity.this; FileChooserActivity.function = FileChooserActivity.FUNCTION_ROM; Intent intent = new Intent( mInstance, FileChooserActivity.class ); intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP ); startActivity( intent ); return true; } }); final ListPreference menuSettingsLanguage = (ListPreference) findPreference( "menuSettingsLanguage" ); menuSettingsLanguage.setOnPreferenceChangeListener( new OnPreferenceChangeListener() { public boolean onPreferenceChange( Preference preference, Object newValue ) { String code = String.valueOf( newValue ); if( Globals.locale_default == null ) Globals.locale_default = getBaseContext().getResources().getConfiguration().locale; if( code == null || code.equals( "00" ) || code.length() != 2 ) Globals.locale = Globals.locale_default; else Globals.locale = new Locale( code ); Intent intent = getIntent(); overridePendingTransition( 0, 0 ); intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP ); intent.addFlags( Intent.FLAG_ACTIVITY_NO_ANIMATION ); finish(); overridePendingTransition( 0, 0 ); startActivity(intent); return true; } }); final Preference menuClose = findPreference( "menuClose" ); menuClose.setOnPreferenceClickListener( new OnPreferenceClickListener() { public boolean onPreferenceClick( Preference preference ) { // Shut down the app File f = new File( Globals.StorageDir ); if( f.exists() ) { mupen64plus_cfg.save(); gui_cfg.save(); } mInstance.finish(); return true; } }); Globals.errorMessage = error_log.get( "OPEN_ROM", "fail_crash" ); if( Globals.errorMessage != null && Globals.errorMessage.length() > 0 ) { Runnable toastMessager = new Runnable() { public void run() { Toast toast = Toast.makeText( MenuActivity.mInstance, Globals.errorMessage, Toast.LENGTH_LONG ); toast.setGravity( Gravity.BOTTOM, 0, 0 ); toast.show(); } }; runOnUiThread( toastMessager ); } error_log.put( "OPEN_ROM", "fail_crash", "" ); error_log.save(); Globals.errorMessage = null; }
diff --git a/metaobj/tool-lib/src/java/org/sakaiproject/metaobj/shared/control/tag/RichTextWrapperTag.java b/metaobj/tool-lib/src/java/org/sakaiproject/metaobj/shared/control/tag/RichTextWrapperTag.java index 6c24cf3..5ced7d1 100644 --- a/metaobj/tool-lib/src/java/org/sakaiproject/metaobj/shared/control/tag/RichTextWrapperTag.java +++ b/metaobj/tool-lib/src/java/org/sakaiproject/metaobj/shared/control/tag/RichTextWrapperTag.java @@ -1,198 +1,201 @@ /* * ********************************************************************************* * $URL: https://source.sakaiproject.org/svn/content/trunk/content-api/api/src/java/org/sakaiproject/content/api/ContentCollection.java $ * $Id: ContentCollection.java 8537 2006-05-01 02:13:28Z [email protected] $ * ********************************************************************************** * * Copyright (c) 2003, 2004, 2005, 2006 The Sakai Foundation. * * Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php * * 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.sakaiproject.metaobj.shared.control.tag; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.taglibs.standard.tag.el.core.ExpressionUtil; import org.sakaiproject.component.cover.ServerConfigurationService; import org.sakaiproject.content.cover.ContentHostingService; import org.sakaiproject.tool.cover.ToolManager; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.BodyTagSupport; import java.io.IOException; public class RichTextWrapperTag extends BodyTagSupport { protected final transient Log logger = LogFactory.getLog(getClass()); //private static final String SCRIPT_PATH; //private static final String HTMLAREA_SCRIPT_PATH; //private static final String RESOURCE_PATH; private String textAreaId; /* // we have static resources for our script path and built-in toolbars etc. static { ConfigurationResource cr = new ConfigurationResource(); SCRIPT_PATH = cr.get("inputRichTextScript"); HTMLAREA_SCRIPT_PATH = cr.get("inputRichTextHTMLArea"); RESOURCE_PATH = cr.get("resources"); } */ public int doStartTag() throws JspException { JspWriter writer = pageContext.getOut(); String textAreaId = (String) ExpressionUtil.evalNotNull("richTextWrapper", "textAreaId", getTextAreaId(), String.class, this, pageContext); try { String editor = ServerConfigurationService.getString("wysiwyg.editor"); if(editor != null && !editor.equalsIgnoreCase("FCKeditor")) { // Render JavaScripts. //writeExternalScripts(locale, writer); writer.write("<script type=\"text/javascript\" src=\"/library/editor/HTMLArea/sakai_editor.js\"></script>\n"); writer.write("<script type=\"text/javascript\" defer=\"1\">chef_setupformattedtextarea('"+textAreaId+"');</script>"); } else { String collectionId = ContentHostingService.getSiteCollection(ToolManager.getCurrentPlacement().getContext()); String tagFocus = ServerConfigurationService.getString("tags.focus"); writer.write("<script type=\"text/javascript\" src=\"/library/editor/FCKeditor/sakai_fckconfig.js\"></script>\n"); writer.write("<script type=\"text/javascript\" defer=\"1\">chef_setupfcktextarea('"+ - textAreaId+"', 450, 50, '" + collectionId + "', '" + tagFocus + "');</script>"); + textAreaId+"', 450, 50, '" + collectionId + "', '" + tagFocus + "');\n"); + writer.write("\t\tvar f = document.getElementById('"+textAreaId+"').form;\n" + + "\t\tif (typeof f.onsubmit != \"function\") f.onsubmit = function() {};\n"); + writer.write("</script>"); } } catch (IOException e) { logger.error("", e); throw new JspException(e); } return EVAL_BODY_INCLUDE; } /** * @todo do these as a document.write after testing if done * @param contextPath * @param writer * @throws IOException */ /* protected void writeExternalScripts(Locale locale, ResponseWriter writer) throws IOException { writer.write("<script type=\"text/javascript\">var _editor_url = \"" + "/" + RESOURCE_PATH + "/" + HTMLAREA_SCRIPT_PATH + "/" + "\";</script>\n"); writer.write("<script type=\"text/javascript\" src=\"" + "/" + RESOURCE_PATH + "/" + HTMLAREA_SCRIPT_PATH + "/" + "htmlarea.js\"></script>\n"); writer.write("<script type=\"text/javascript\" src=\"" + "/" + RESOURCE_PATH + "/" + HTMLAREA_SCRIPT_PATH + "/" + "dialog.js\"></script>\n"); writer.write("<script type=\"text/javascript\" src=\"" + "/" + RESOURCE_PATH + "/" + HTMLAREA_SCRIPT_PATH + "/" + "popupwin.js\"></script>\n"); writer.write("<script type=\"text/javascript\" src=\"" + "/" + RESOURCE_PATH + "/" + HTMLAREA_SCRIPT_PATH + "/" + "lang/en.js\"></script>\n"); String language = locale.getLanguage(); if (!Locale.ENGLISH.equals(language)) { writer.write("<script type=\"text/javascript\" src=\"" + "/" + RESOURCE_PATH + "/" + HTMLAREA_SCRIPT_PATH + "/" + "lang/" + language + ".js\"></script>\n"); } writer.write("<script type=\"text/javascript\" src=\"" + "/" + RESOURCE_PATH + "/" + SCRIPT_PATH + "\"></script>\n"); } protected void doFckStuff(JspWriter writer, String clientId) { // set up dimensions int widthPx = 450; int heightPx = 50; int textareaColumns = 80; int textareaRows = 4; widthPx = (DEFAULT_WIDTH_PX*textareaColumns)/DEFAULT_COLUMNS; heightPx = (DEFAULT_HEIGHT_PX*textareaRows)/DEFAULT_ROWS; // not as slick as the way htmlarea is rendered, but the difference in functionality doesn't all //make sense for FCK at this time since it's already got the ability to insert files and such. String collectionId = ContentHostingService.getSiteCollection(ToolManager.getCurrentPlacement().getContext()); //is there a slicker way to get this? String connector = "/sakai-fck-connector/web/editor/filemanager/browser/default/connectors/jsp/connector"; //writer.write("<table border=\"0\"><tr><td>"); writer.write("<script type=\"text/javascript\" src=\"/library/editor/FCKeditor/fckeditor.js\"></script>\n"); writer.write("<script type=\"text/javascript\" language=\"JavaScript\">\n"); writer.write("function chef_setupformattedtextarea(textarea_id){\n"); writer.write("var oFCKeditor = new FCKeditor(textarea_id);\n"); writer.write("oFCKeditor.BasePath = \"/library/editor/FCKeditor/\";\n"); if (widthPx < 0) widthPx = 600; if (heightPx < 0) heightPx = 400; //FCK's toolset is larger then htmlarea and this prevents tools from ending up with all toolbar //and no actual editing area. if (heightPx < 200) heightPx = 200; writer.write("oFCKeditor.Width = \"" + widthPx + "\" ;\n"); writer.write("oFCKeditor.Height = \"" + heightPx + "\" ;\n"); if ("archival".equals(ServerConfigurationService.getString("tags.focus"))) writer.write("\n\toFCKeditor.Config['CustomConfigurationsPath'] = \"/library/editor/FCKeditor/archival_config.js\";\n"); else { writer.write("\n\t\tvar courseId = \"" + collectionId + "\";"); writer.write("\n\toFCKeditor.Config['ImageBrowserURL'] = oFCKeditor.BasePath + " + "\"editor/filemanager/browser/default/browser.html?Connector=" + connector + "&Type=Image&CurrentFolder=\" + courseId;"); writer.write("\n\toFCKeditor.Config['LinkBrowserURL'] = oFCKeditor.BasePath + " + "\"editor/filemanager/browser/default/browser.html?Connector=" + connector + "&Type=Link&CurrentFolder=\" + courseId;"); writer.write("\n\toFCKeditor.Config['FlashBrowserURL'] = oFCKeditor.BasePath + " + "\"editor/filemanager/browser/default/browser.html?Connector=" + connector + "&Type=Flash&CurrentFolder=\" + courseId;"); writer.write("\n\toFCKeditor.Config['ImageUploadURL'] = oFCKeditor.BasePath + " + "\"" + connector + "?Type=Image&Command=QuickUpload&Type=Image&CurrentFolder=\" + courseId;"); writer.write("\n\toFCKeditor.Config['FlashUploadURL'] = oFCKeditor.BasePath + " + "\"" + connector + "?Type=Flash&Command=QuickUpload&Type=Flash&CurrentFolder=\" + courseId;"); writer.write("\n\toFCKeditor.Config['LinkUploadURL'] = oFCKeditor.BasePath + " + "\"" + connector + "?Type=File&Command=QuickUpload&Type=Link&CurrentFolder=\" + courseId;"); writer.write("\n\n\toFCKeditor.Config['CurrentFolder'] = courseId;"); writer.write("\n\toFCKeditor.Config['CustomConfigurationsPath'] = \"/library/editor/FCKeditor/config.js\";\n"); } } */ public String getTextAreaId() { return textAreaId; } public void setTextAreaId(String textAreaId) { this.textAreaId = textAreaId; } }
true
true
public int doStartTag() throws JspException { JspWriter writer = pageContext.getOut(); String textAreaId = (String) ExpressionUtil.evalNotNull("richTextWrapper", "textAreaId", getTextAreaId(), String.class, this, pageContext); try { String editor = ServerConfigurationService.getString("wysiwyg.editor"); if(editor != null && !editor.equalsIgnoreCase("FCKeditor")) { // Render JavaScripts. //writeExternalScripts(locale, writer); writer.write("<script type=\"text/javascript\" src=\"/library/editor/HTMLArea/sakai_editor.js\"></script>\n"); writer.write("<script type=\"text/javascript\" defer=\"1\">chef_setupformattedtextarea('"+textAreaId+"');</script>"); } else { String collectionId = ContentHostingService.getSiteCollection(ToolManager.getCurrentPlacement().getContext()); String tagFocus = ServerConfigurationService.getString("tags.focus"); writer.write("<script type=\"text/javascript\" src=\"/library/editor/FCKeditor/sakai_fckconfig.js\"></script>\n"); writer.write("<script type=\"text/javascript\" defer=\"1\">chef_setupfcktextarea('"+ textAreaId+"', 450, 50, '" + collectionId + "', '" + tagFocus + "');</script>"); } } catch (IOException e) { logger.error("", e); throw new JspException(e); } return EVAL_BODY_INCLUDE; }
public int doStartTag() throws JspException { JspWriter writer = pageContext.getOut(); String textAreaId = (String) ExpressionUtil.evalNotNull("richTextWrapper", "textAreaId", getTextAreaId(), String.class, this, pageContext); try { String editor = ServerConfigurationService.getString("wysiwyg.editor"); if(editor != null && !editor.equalsIgnoreCase("FCKeditor")) { // Render JavaScripts. //writeExternalScripts(locale, writer); writer.write("<script type=\"text/javascript\" src=\"/library/editor/HTMLArea/sakai_editor.js\"></script>\n"); writer.write("<script type=\"text/javascript\" defer=\"1\">chef_setupformattedtextarea('"+textAreaId+"');</script>"); } else { String collectionId = ContentHostingService.getSiteCollection(ToolManager.getCurrentPlacement().getContext()); String tagFocus = ServerConfigurationService.getString("tags.focus"); writer.write("<script type=\"text/javascript\" src=\"/library/editor/FCKeditor/sakai_fckconfig.js\"></script>\n"); writer.write("<script type=\"text/javascript\" defer=\"1\">chef_setupfcktextarea('"+ textAreaId+"', 450, 50, '" + collectionId + "', '" + tagFocus + "');\n"); writer.write("\t\tvar f = document.getElementById('"+textAreaId+"').form;\n" + "\t\tif (typeof f.onsubmit != \"function\") f.onsubmit = function() {};\n"); writer.write("</script>"); } } catch (IOException e) { logger.error("", e); throw new JspException(e); } return EVAL_BODY_INCLUDE; }
diff --git a/java/src/org/broadinstitute/sting/gatk/GenomeAnalysisEngine.java b/java/src/org/broadinstitute/sting/gatk/GenomeAnalysisEngine.java index 725bc3727..9ed27d046 100755 --- a/java/src/org/broadinstitute/sting/gatk/GenomeAnalysisEngine.java +++ b/java/src/org/broadinstitute/sting/gatk/GenomeAnalysisEngine.java @@ -1,970 +1,970 @@ /* * Copyright (c) 2010 The Broad Institute * * 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 org.broadinstitute.sting.gatk; import net.sf.picard.filter.SamRecordFilter; import net.sf.picard.reference.ReferenceSequenceFile; import net.sf.samtools.*; import org.apache.log4j.Logger; import org.broadinstitute.sting.gatk.arguments.GATKArgumentCollection; import org.broadinstitute.sting.gatk.refdata.utils.helpers.DbSNPHelper; import org.broadinstitute.sting.utils.exceptions.ReviewedStingException; import org.broadinstitute.sting.utils.exceptions.UserException; import org.broadinstitute.sting.utils.interval.IntervalMergingRule; import org.broadinstitute.sting.utils.interval.IntervalUtils; import org.broadinstitute.sting.gatk.arguments.ValidationExclusion; import org.broadinstitute.sting.gatk.datasources.shards.MonolithicShardStrategy; import org.broadinstitute.sting.gatk.datasources.shards.Shard; import org.broadinstitute.sting.gatk.datasources.shards.ShardStrategy; import org.broadinstitute.sting.gatk.datasources.shards.ShardStrategyFactory; import org.broadinstitute.sting.gatk.datasources.simpleDataSources.*; import org.broadinstitute.sting.gatk.executive.MicroScheduler; import org.broadinstitute.sting.gatk.filters.FilterManager; import org.broadinstitute.sting.gatk.filters.ReadGroupBlackListFilter; import org.broadinstitute.sting.gatk.io.OutputTracker; import org.broadinstitute.sting.gatk.io.stubs.*; import org.broadinstitute.sting.gatk.refdata.tracks.RMDTrack; import org.broadinstitute.sting.gatk.refdata.tracks.RMDTrackManager; import org.broadinstitute.sting.gatk.refdata.utils.RMDIntervalGenerator; import org.broadinstitute.sting.gatk.walkers.*; import org.broadinstitute.sting.utils.*; import org.broadinstitute.sting.utils.text.XReadLines; import org.broadinstitute.sting.commandline.ArgumentException; import org.broadinstitute.sting.commandline.ArgumentSource; import org.broadinstitute.sting.commandline.ArgumentTypeDescriptor; import java.io.File; import java.io.FileNotFoundException; import java.util.*; public class GenomeAnalysisEngine { // our instance of this genome analysis toolkit; it's used by other classes to extract the traversal engine // TODO: public static without final tends to indicate we're thinking about this the wrong way public static GenomeAnalysisEngine instance; /** * Accessor for sharded read data. */ private SAMDataSource readsDataSource = null; /** * Accessor for sharded reference data. */ private ReferenceDataSource referenceDataSource = null; /** * Accessor for sharded reference-ordered data. */ private List<ReferenceOrderedDataSource> rodDataSources; // our argument collection private GATKArgumentCollection argCollection; /** * Collection of inputs used by the walker. */ private Map<ArgumentSource, Object> inputs = new HashMap<ArgumentSource, Object>(); /** * Collection of intervals used by the walker. */ private GenomeLocSortedSet intervals = null; /** * Collection of outputs used by the walker. */ private Collection<Stub<?>> outputs = new ArrayList<Stub<?>>(); /** * List of tags associated with the given instantiation of the command-line argument. */ private final Map<Object,List<String>> tags = new IdentityHashMap<Object,List<String>>(); /** * Collection of the filters applied to the walker's input data. */ private Collection<SamRecordFilter> filters; /** * our log, which we want to capture anything from this class */ private static Logger logger = Logger.getLogger(GenomeAnalysisEngine.class); /** * our walker manager */ private final WalkerManager walkerManager; /** * Manage lists of filters. */ private final FilterManager filterManager; private Date startTime = null; // the start time for execution /** * our constructor, where all the work is done * <p/> * legacy traversal types are sent to legacyTraversal function; as we move more of the traversals to the * new MicroScheduler class we'll be able to delete that function. */ public GenomeAnalysisEngine() { // make sure our instance variable points to this analysis engine // if ( instance != null ) // throw new StingException("Instantiating GenomeAnalysisEngine but global instance variable isn't null, indicating that an instance has already been created: " + instance); instance = this; walkerManager = new WalkerManager(); filterManager = new FilterManager(); } /** * Actually run the GATK with the specified walker. * * @param args the argument collection, where we get all our setup information from * @param my_walker Walker to run over the dataset. Must not be null. * @return the value of this traversal. */ public Object execute(GATKArgumentCollection args, Walker<?, ?> my_walker, Collection<SamRecordFilter> filters) { //HeapSizeMonitor monitor = new HeapSizeMonitor(); //monitor.start(); startTime = new java.util.Date(); // validate our parameters if (args == null) { throw new ReviewedStingException("The GATKArgumentCollection passed to GenomeAnalysisEngine can not be null."); } // validate our parameters if (my_walker == null) throw new ReviewedStingException("The walker passed to GenomeAnalysisEngine can not be null."); // save our argument parameter this.argCollection = args; this.filters = filters; // Prepare the data for traversal. initializeDataSources(my_walker, filters, argCollection); // our microscheduler, which is in charge of running everything MicroScheduler microScheduler = createMicroscheduler(my_walker); // create the output streams " initializeOutputStreams(my_walker, microScheduler.getOutputTracker()); initializeIntervals(); ShardStrategy shardStrategy = getShardStrategy(my_walker, microScheduler.getReference(), intervals, readsDataSource != null ? readsDataSource.getReadsInfo().getValidationExclusionList() : null); // execute the microscheduler, storing the results Object result = microScheduler.execute(my_walker, shardStrategy); //monitor.stop(); //logger.info(String.format("Maximum heap size consumed: %d",monitor.getMaxMemoryUsed())); return result; } /** * @return the start time when the execute() function was last called */ public Date getStartTime() { return startTime; } /** * Setup the intervals to be processed */ private void initializeIntervals() { // return null if no interval arguments at all if ((argCollection.intervals == null) && (argCollection.excludeIntervals == null) && (argCollection.RODToInterval == null)) return; else { // if include argument isn't given, create new set of all possible intervals GenomeLocSortedSet includeSortedSet = (argCollection.intervals == null && argCollection.RODToInterval == null ? GenomeLocSortedSet.createSetFromSequenceDictionary(this.referenceDataSource.getReference().getSequenceDictionary()) : loadIntervals(argCollection.intervals, argCollection.intervalMerging, GenomeLocParser.mergeIntervalLocations(checkRODToIntervalArgument(),argCollection.intervalMerging))); // if no exclude arguments, can return parseIntervalArguments directly if (argCollection.excludeIntervals == null) intervals = includeSortedSet; // otherwise there are exclude arguments => must merge include and exclude GenomeLocSortedSets else { GenomeLocSortedSet excludeSortedSet = loadIntervals(argCollection.excludeIntervals, argCollection.intervalMerging, null); intervals = includeSortedSet.subtractRegions(excludeSortedSet); // logging messages only printed when exclude (-XL) arguments are given long toPruneSize = includeSortedSet.coveredSize(); long toExcludeSize = excludeSortedSet.coveredSize(); long intervalSize = intervals.coveredSize(); logger.info(String.format("Initial include intervals span %d loci; exclude intervals span %d loci", toPruneSize, toExcludeSize)); logger.info(String.format("Excluding %d loci from original intervals (%.2f%% reduction)", toPruneSize - intervalSize, (toPruneSize - intervalSize) / (0.01 * toPruneSize))); } } } /** * Loads the intervals relevant to the current execution * @param argList String representation of arguments; might include 'all', filenames, intervals in samtools * notation, or a combination of the * @param mergingRule Technique to use when merging interval data. * @param additionalIntervals a list of additional intervals to add to the returned set. Can be null. * @return A sorted, merged list of all intervals specified in this arg list. */ private GenomeLocSortedSet loadIntervals(List<String> argList, IntervalMergingRule mergingRule, List<GenomeLoc> additionalIntervals) { return IntervalUtils.sortAndMergeIntervals(IntervalUtils.mergeListsBySetOperator(additionalIntervals, IntervalUtils.parseIntervalArguments(argList), argCollection.BTIMergeRule), mergingRule); } /** * if we have a ROD specified as a 'rodToIntervalTrackName', convert its records to RODs */ private static List<GenomeLoc> checkRODToIntervalArgument() { Map<String, ReferenceOrderedDataSource> rodNames = RMDIntervalGenerator.getRMDTrackNames(instance.rodDataSources); // Do we have any RODs that overloaded as interval lists with the 'rodToIntervalTrackName' flag? List<GenomeLoc> ret = new ArrayList<GenomeLoc>(); if (rodNames != null && instance.argCollection.RODToInterval != null) { String rodName = GenomeAnalysisEngine.instance.argCollection.RODToInterval; // check to make sure we have a rod of that name if (!rodNames.containsKey(rodName)) throw new UserException.CommandLineException("--rodToIntervalTrackName (-BTI) was passed the name '"+rodName+"', which wasn't given as a ROD name in the -B option"); for (String str : rodNames.keySet()) if (str.equals(rodName)) { logger.info("Adding interval list from track (ROD) named " + rodName); RMDIntervalGenerator intervalGenerator = new RMDIntervalGenerator(rodNames.get(str).getReferenceOrderedData()); ret.addAll(intervalGenerator.toGenomeLocList()); } } return ret; } /** * Add additional, externally managed IO streams for walker input. * * @param argumentSource Field in the walker into which to inject the value. * @param value Instance to inject. */ public void addInput(ArgumentSource argumentSource, Object value) { inputs.put(argumentSource, value); } /** * Add additional, externally managed IO streams for walker output. * * @param stub Instance to inject. */ public void addOutput(Stub<?> stub) { outputs.add(stub); } /** * Adds an association between a object created by the * command-line argument system and a freeform list of tags. * @param key Object created by the command-line argument system. * @param tags List of tags to use when reading arguments. */ public void addTags(Object key, List<String> tags) { this.tags.put(key,tags); } /** * Gets the tags associated with a given object. * @param key Key for which to find a tag. * @return List of tags associated with this key. */ public List<String> getTags(Object key) { if(!tags.containsKey(key)) return Collections.emptyList(); return tags.get(key); } /** * Retrieves an instance of the walker based on the walker name. * * @param walkerName Name of the walker. Must not be null. If the walker cannot be instantiated, an exception will be thrown. * @return An instance of the walker. */ public Walker<?, ?> getWalkerByName(String walkerName) { return walkerManager.createByName(walkerName); } /** * Gets the name of a given walker type. * @param walkerType Type of walker. * @return Name of the walker. */ public String getWalkerName(Class<? extends Walker> walkerType) { return walkerManager.getName(walkerType); } /** * Gets a list of the filters to associate with the given walker. Will NOT initialize the engine with this filters; * the caller must handle that directly. * @param args Existing argument collection, for compatibility with legacy command-line walkers. * @param walker Walker to use when determining which filters to apply. * @return A collection of available filters. */ protected Collection<SamRecordFilter> createFiltersForWalker(GATKArgumentCollection args, Walker walker) { Set<SamRecordFilter> filters = new HashSet<SamRecordFilter>(); filters.addAll(WalkerManager.getReadFilters(walker,filterManager)); if (args.readGroupBlackList != null && args.readGroupBlackList.size() > 0) filters.add(new ReadGroupBlackListFilter(args.readGroupBlackList)); for(String filterName: args.readFilters) filters.add(filterManager.createByName(filterName)); return Collections.unmodifiableSet(filters); } /** * Allow subclasses and others within this package direct access to the walker manager. * @return The walker manager used by this package. */ protected WalkerManager getWalkerManager() { return walkerManager; } private void initializeDataSources(Walker my_walker, Collection<SamRecordFilter> filters, GATKArgumentCollection argCollection) { validateSuppliedReadsAgainstWalker(my_walker, argCollection); logger.info("Strictness is " + argCollection.strictnessLevel); readsDataSource = createReadsDataSource(extractSourceInfo(my_walker, filters, argCollection)); validateSuppliedReferenceAgainstWalker(my_walker, argCollection); referenceDataSource = openReferenceSequenceFile(argCollection.referenceFile); if (argCollection.DBSNPFile != null) bindConvenienceRods(DbSNPHelper.STANDARD_DBSNP_TRACK_NAME, "dbsnp", argCollection.DBSNPFile); // TODO: The ROD iterator currently does not understand multiple intervals file. Fix this by cleaning the ROD system. if (argCollection.intervals != null && argCollection.intervals.size() == 1) { bindConvenienceRods("interval", "Intervals", argCollection.intervals.get(0).replaceAll(",", "")); } RMDTrackManager manager = new RMDTrackManager(); List<RMDTrack> tracks = manager.getReferenceMetaDataSources(this,argCollection.RODBindings); validateSuppliedReferenceOrderedDataAgainstWalker(my_walker, tracks); // validate all the sequence dictionaries against the reference validateSourcesAgainstReference(readsDataSource, referenceDataSource.getReference(), tracks); rodDataSources = getReferenceOrderedDataSources(my_walker, tracks); } /** * setup a microscheduler * * @param my_walker our walker of type LocusWalker * @return a new microscheduler */ private MicroScheduler createMicroscheduler(Walker my_walker) { // the mircoscheduler to return MicroScheduler microScheduler = null; // Temporarily require all walkers to have a reference, even if that reference is not conceptually necessary. if ((my_walker instanceof ReadWalker || my_walker instanceof DuplicateWalker || my_walker instanceof ReadPairWalker) && argCollection.referenceFile == null) { throw new UserException.CommandLineException("Read-based traversals require a reference file but none was given"); } return MicroScheduler.create(this,my_walker,readsDataSource,referenceDataSource.getReference(),rodDataSources,argCollection.numberOfThreads); } /** * Gets a unique identifier for the reader sourcing this read. * @param read Read to examine. * @return A unique identifier for the source file of this read. Exception if not found. */ public SAMReaderID getReaderIDForRead(final SAMRecord read) { return getDataSource().getReaderID(read); } /** * Gets the source file for this read. * @param id Unique identifier determining which input file to use. * @return The source filename for this read. */ public File getSourceFileForReaderID(final SAMReaderID id) { return getDataSource().getSAMFile(id); } /** * Returns sets of samples present in the (merged) input SAM stream, grouped by readers (i.e. underlying * individual bam files). For instance: if GATK is run with three input bam files (three -I arguments), then the list * returned by this method will contain 3 elements (one for each reader), with each element being a set of sample names * found in the corresponding bam file. * * @return */ public List<Set<String>> getSamplesByReaders() { List<SAMReaderID> readers = getDataSource().getReaderIDs(); List<Set<String>> sample_sets = new ArrayList<Set<String>>(readers.size()); for (SAMReaderID r : readers) { Set<String> samples = new HashSet<String>(1); sample_sets.add(samples); for (SAMReadGroupRecord g : getDataSource().getHeader(r).getReadGroups()) { samples.add(g.getSample()); } } return sample_sets; } /** * Returns sets of libraries present in the (merged) input SAM stream, grouped by readers (i.e. underlying * individual bam files). For instance: if GATK is run with three input bam files (three -I arguments), then the list * returned by this method will contain 3 elements (one for each reader), with each element being a set of library names * found in the corresponding bam file. * * @return */ public List<Set<String>> getLibrariesByReaders() { List<SAMReaderID> readers = getDataSource().getReaderIDs(); List<Set<String>> lib_sets = new ArrayList<Set<String>>(readers.size()); for (SAMReaderID r : readers) { Set<String> libs = new HashSet<String>(2); lib_sets.add(libs); for (SAMReadGroupRecord g : getDataSource().getHeader(r).getReadGroups()) { libs.add(g.getLibrary()); } } return lib_sets; } /** * Returns a mapping from original input files to their (merged) read group ids * * @return the mapping */ public Map<File, Set<String>> getFileToReadGroupIdMapping() { // populate the file -> read group mapping Map<File, Set<String>> fileToReadGroupIdMap = new HashMap<File, Set<String>>(); for (SAMReaderID id: getDataSource().getReaderIDs()) { Set<String> readGroups = new HashSet<String>(5); for (SAMReadGroupRecord g : getDataSource().getHeader(id).getReadGroups()) { if (getDataSource().hasReadGroupCollisions()) { // Check if there were read group clashes. // If there were, use the SamFileHeaderMerger to translate from the // original read group id to the read group id in the merged stream readGroups.add(getDataSource().getReadGroupId(id,g.getReadGroupId())); } else { // otherwise, pass through the unmapped read groups since this is what Picard does as well readGroups.add(g.getReadGroupId()); } } fileToReadGroupIdMap.put(getDataSource().getSAMFile(id),readGroups); } return fileToReadGroupIdMap; } /** * **** UNLESS YOU HAVE GOOD REASON TO, DO NOT USE THIS METHOD; USE getFileToReadGroupIdMapping() INSTEAD **** * * Returns sets of (remapped) read groups in input SAM stream, grouped by readers (i.e. underlying * individual bam files). For instance: if GATK is run with three input bam files (three -I arguments), then the list * returned by this method will contain 3 elements (one for each reader), with each element being a set of remapped read groups * (i.e. as seen by read.getReadGroup().getReadGroupId() in the merged stream) that come from the corresponding bam file. * * @return sets of (merged) read group ids in order of input bams */ public List<Set<String>> getMergedReadGroupsByReaders() { List<SAMReaderID> readers = getDataSource().getReaderIDs(); List<Set<String>> rg_sets = new ArrayList<Set<String>>(readers.size()); for (SAMReaderID r : readers) { Set<String> groups = new HashSet<String>(5); rg_sets.add(groups); for (SAMReadGroupRecord g : getDataSource().getHeader(r).getReadGroups()) { if (getDataSource().hasReadGroupCollisions()) { // Check if there were read group clashes with hasGroupIdDuplicates and if so: // use HeaderMerger to translate original read group id from the reader into the read group id in the // merged stream, and save that remapped read group id to associate it with specific reader groups.add(getDataSource().getReadGroupId(r, g.getReadGroupId())); } else { // otherwise, pass through the unmapped read groups since this is what Picard does as well groups.add(g.getReadGroupId()); } } } return rg_sets; } /** * Subclasses of CommandLinePrograms can provide their own types of command-line arguments. * @return A collection of type descriptors generating implementation-dependent placeholders. */ protected Collection<ArgumentTypeDescriptor> getArgumentTypeDescriptors() { return Arrays.asList( new VCFWriterArgumentTypeDescriptor(this,System.out), new SAMFileReaderArgumentTypeDescriptor(this), new SAMFileWriterArgumentTypeDescriptor(this,System.out), new OutputStreamArgumentTypeDescriptor(this,System.out) ); } /** * Bundles all the source information about the reads into a unified data structure. * * @param walker The walker for which to extract info. * @param argCollection The collection of arguments passed to the engine. * @return The reads object providing reads source info. */ private ReadProperties extractSourceInfo(Walker walker, Collection<SamRecordFilter> filters, GATKArgumentCollection argCollection) { DownsamplingMethod method = null; if(argCollection.getDownsamplingMethod() != null) method = argCollection.getDownsamplingMethod(); else if(WalkerManager.getDownsamplingMethod(walker) != null) method = WalkerManager.getDownsamplingMethod(walker); else method = argCollection.getDefaultDownsamplingMethod(); return new ReadProperties(unpackBAMFileList(argCollection.samFiles), argCollection.strictnessLevel, argCollection.readBufferSize, method, new ValidationExclusion(Arrays.asList(argCollection.unsafe)), filters, walker.includeReadsWithDeletionAtLoci(), walker.generateExtendedEvents()); } /** * Verifies that the supplied set of reads files mesh with what the walker says it requires. * * @param walker Walker to test. * @param arguments Supplied reads files. */ private void validateSuppliedReadsAgainstWalker(Walker walker, GATKArgumentCollection arguments) { // Check what the walker says is required against what was provided on the command line. if (WalkerManager.isRequired(walker, DataSource.READS) && (arguments.samFiles == null || arguments.samFiles.size() == 0)) throw new ArgumentException("Walker requires reads but none were provided. If this is incorrect, alter the walker's @Requires annotation."); // Check what the walker says is allowed against what was provided on the command line. if ((arguments.samFiles != null && arguments.samFiles.size() > 0) && !WalkerManager.isAllowed(walker, DataSource.READS)) throw new ArgumentException("Walker does not allow reads but reads were provided. If this is incorrect, alter the walker's @Allows annotation"); } /** * Verifies that the supplied reference file mesh with what the walker says it requires. * * @param walker Walker to test. * @param arguments Supplied reads files. */ private void validateSuppliedReferenceAgainstWalker(Walker walker, GATKArgumentCollection arguments) { // Check what the walker says is required against what was provided on the command line. // TODO: Temporarily disabling WalkerManager.isRequired check on the reference because the reference is always required. if (/*WalkerManager.isRequired(walker, DataSource.REFERENCE) &&*/ arguments.referenceFile == null) throw new ArgumentException("Walker requires a reference but none was provided. If this is incorrect, alter the walker's @Requires annotation."); // Check what the walker says is allowed against what was provided on the command line. if (arguments.referenceFile != null && !WalkerManager.isAllowed(walker, DataSource.REFERENCE)) throw new ArgumentException("Walker does not allow a reference but one was provided. If this is incorrect, alter the walker's @Allows annotation"); } /** * Verifies that all required reference-ordered data has been supplied, and any reference-ordered data that was not * 'allowed' is still present. * * @param walker Walker to test. * @param rods Reference-ordered data to load. */ private void validateSuppliedReferenceOrderedDataAgainstWalker(Walker walker, List<RMDTrack> rods) { // Check to make sure that all required metadata is present. List<RMD> allRequired = WalkerManager.getRequiredMetaData(walker); for (RMD required : allRequired) { boolean found = false; for (RMDTrack rod : rods) { if (rod.matchesNameAndRecordType(required.name(), required.type())) found = true; } if (!found) throw new ArgumentException(String.format("Unable to find reference metadata (%s,%s)", required.name(), required.type())); } // Check to see that no forbidden rods are present. for (RMDTrack rod : rods) { if (!WalkerManager.isAllowed(walker, rod)) throw new ArgumentException(String.format("Walker of type %s does not allow access to metadata: %s. If this is incorrect, change the @Allows metadata", walker.getClass(), rod.getName())); } } /** * Now that all files are open, validate the sequence dictionaries of the reads vs. the reference vrs the reference ordered data (if available). * * @param reads Reads data source. * @param reference Reference data source. * @param tracks a collection of the reference ordered data tracks */ private void validateSourcesAgainstReference(SAMDataSource reads, ReferenceSequenceFile reference, Collection<RMDTrack> tracks) { if ((reads.isEmpty() && (tracks == null || tracks.isEmpty())) || reference == null ) return; // Compile a set of sequence names that exist in the reference file. SAMSequenceDictionary referenceDictionary = reference.getSequenceDictionary(); if (!reads.isEmpty()) { // Compile a set of sequence names that exist in the BAM files. SAMSequenceDictionary readsDictionary = reads.getHeader().getSequenceDictionary(); Set<String> readsSequenceNames = new TreeSet<String>(); for (SAMSequenceRecord dictionaryEntry : readsDictionary.getSequences()) readsSequenceNames.add(dictionaryEntry.getSequenceName()); if (readsSequenceNames.size() == 0) { logger.info("Reads file is unmapped. Skipping validation against reference."); return; } // compare the reads to the reference SequenceDictionaryUtils.validateDictionaries(logger, "reads", readsDictionary, "reference", referenceDictionary); } // compare the tracks to the reference, if they have a sequence dictionary for (RMDTrack track : tracks) { SAMSequenceDictionary trackDict = track.getSequenceDictionary(); // hack: if the sequence dictionary is empty (as well as null which means it doesn't have a dictionary), skip validation if (trackDict == null || trackDict.size() == 0) { logger.info("Track " + track.getName() + " doesn't have a sequence dictionary built in, skipping dictionary validation"); continue; } Set<String> trackSequences = new TreeSet<String>(); for (SAMSequenceRecord dictionaryEntry : trackDict.getSequences()) trackSequences.add(dictionaryEntry.getSequenceName()); SequenceDictionaryUtils.validateDictionaries(logger, track.getName(), trackDict, "reference", referenceDictionary); } } /** * Convenience function that binds RODs using the old-style command line parser to the new style list for * a uniform processing. * * @param name the name of the rod * @param type its type * @param file the file to load the rod from */ private void bindConvenienceRods(final String name, final String type, final String file) { argCollection.RODBindings.add(Utils.join(",", new String[]{name, type, file})); } /** * Get the sharding strategy given a driving data source. * * @param walker Walker for which to infer sharding strategy. * @param drivingDataSource Data on which to shard. * @param intervals Intervals to use when limiting sharding. * @return Sharding strategy for this driving data source. */ protected ShardStrategy getShardStrategy(Walker walker, ReferenceSequenceFile drivingDataSource, GenomeLocSortedSet intervals, ValidationExclusion exclusions) { // Use monolithic sharding if no index is present. Monolithic sharding is always required for the original // sharding system; it's required with the new sharding system only for locus walkers. if(readsDataSource != null && !readsDataSource.hasIndex() ) { if(!exclusions.contains(ValidationExclusion.TYPE.ALLOW_UNINDEXED_BAM)) throw new UserException.CommandLineException("The GATK cannot currently process unindexed BAM files without the -U ALLOW_UNINDEXED_BAM"); if(intervals != null && WalkerManager.getWalkerDataSource(walker) != DataSource.REFERENCE) throw new UserException.CommandLineException("Cannot perform interval processing when walker is not driven by reference and no index is available."); Shard.ShardType shardType; if(walker instanceof LocusWalker) { if (readsDataSource.getSortOrder() != SAMFileHeader.SortOrder.coordinate) - throw new UserException.MissortedBAM(SAMFileHeader.SortOrder.coordinate, "Locus walkers can only walk over coordinate-sorted data. Please resort your input BAM file(s)."); + throw new UserException.MissortedBAM(SAMFileHeader.SortOrder.coordinate, "Locus walkers can only traverse coordinate-sorted data. Please resort your input BAM file(s) or set the Sort Order tag in the header appropriately."); shardType = Shard.ShardType.LOCUS; } else if(walker instanceof ReadWalker || walker instanceof DuplicateWalker || walker instanceof ReadPairWalker) shardType = Shard.ShardType.READ; else throw new UserException.CommandLineException("The GATK cannot currently process unindexed BAM files"); List<GenomeLoc> region; if(intervals != null) region = intervals.toList(); else { region = new ArrayList<GenomeLoc>(); for(SAMSequenceRecord sequenceRecord: drivingDataSource.getSequenceDictionary().getSequences()) region.add(GenomeLocParser.createGenomeLoc(sequenceRecord.getSequenceName(),1,sequenceRecord.getSequenceLength())); } return new MonolithicShardStrategy(readsDataSource,shardType,region); } ShardStrategy shardStrategy = null; ShardStrategyFactory.SHATTER_STRATEGY shardType; long SHARD_SIZE = 100000L; if (walker instanceof LocusWalker) { if (walker instanceof RodWalker) SHARD_SIZE *= 1000; if (intervals != null && !intervals.isEmpty()) { if(!readsDataSource.isEmpty() && readsDataSource.getSortOrder() != SAMFileHeader.SortOrder.coordinate) - throw new UserException.MissortedBAM(SAMFileHeader.SortOrder.coordinate, "Locus walkers can only walk over coordinate-sorted data. Please resort your input BAM file(s)."); + throw new UserException.MissortedBAM(SAMFileHeader.SortOrder.coordinate, "Locus walkers can only traverse coordinate-sorted data. Please resort your input BAM file(s) or set the Sort Order tag in the header appropriately."); shardStrategy = ShardStrategyFactory.shatter(readsDataSource, referenceDataSource.getReference(), ShardStrategyFactory.SHATTER_STRATEGY.LOCUS_EXPERIMENTAL, drivingDataSource.getSequenceDictionary(), SHARD_SIZE, intervals); } else shardStrategy = ShardStrategyFactory.shatter(readsDataSource, referenceDataSource.getReference(), ShardStrategyFactory.SHATTER_STRATEGY.LOCUS_EXPERIMENTAL, drivingDataSource.getSequenceDictionary(), SHARD_SIZE); } else if (walker instanceof ReadWalker || walker instanceof DuplicateWalker) { shardType = ShardStrategyFactory.SHATTER_STRATEGY.READS_EXPERIMENTAL; if (intervals != null && !intervals.isEmpty()) { shardStrategy = ShardStrategyFactory.shatter(readsDataSource, referenceDataSource.getReference(), shardType, drivingDataSource.getSequenceDictionary(), SHARD_SIZE, intervals); } else { shardStrategy = ShardStrategyFactory.shatter(readsDataSource, referenceDataSource.getReference(), shardType, drivingDataSource.getSequenceDictionary(), SHARD_SIZE); } } else if (walker instanceof ReadPairWalker) { if(readsDataSource != null && readsDataSource.getSortOrder() != SAMFileHeader.SortOrder.queryname) throw new UserException.MissortedBAM(SAMFileHeader.SortOrder.queryname, "Read pair walkers can only walk over query name-sorted data. Please resort your input BAM file."); if(intervals != null && !intervals.isEmpty()) throw new UserException.CommandLineException("Pairs traversal cannot be used in conjunction with intervals."); shardStrategy = ShardStrategyFactory.shatter(readsDataSource, referenceDataSource.getReference(), ShardStrategyFactory.SHATTER_STRATEGY.READS_EXPERIMENTAL, drivingDataSource.getSequenceDictionary(), SHARD_SIZE); } else throw new ReviewedStingException("Unable to support walker of type" + walker.getClass().getName()); return shardStrategy; } /** * Gets a data source for the given set of reads. * * @param reads the read source information * @return A data source for the given set of reads. */ private SAMDataSource createReadsDataSource(ReadProperties reads) { return new SAMDataSource(reads); } /** * Opens a reference sequence file paired with an index. * * @param refFile Handle to a reference sequence file. Non-null. * @return A thread-safe file wrapper. */ private ReferenceDataSource openReferenceSequenceFile(File refFile) { ReferenceDataSource ref = new ReferenceDataSource(refFile); GenomeLocParser.setupRefContigOrdering(ref.getReference()); return ref; } /** * Open the reference-ordered data sources. * * @param rods the reference order data to execute using * @return A list of reference-ordered data sources. */ private List<ReferenceOrderedDataSource> getReferenceOrderedDataSources(Walker walker, List<RMDTrack> rods) { List<ReferenceOrderedDataSource> dataSources = new ArrayList<ReferenceOrderedDataSource>(); for (RMDTrack rod : rods) dataSources.add(new ReferenceOrderedDataSource(walker, rod)); return dataSources; } /** * Initialize the output streams as specified by the user. * * @param walker the walker to initialize output streams for * @param outputTracker the tracker supplying the initialization data. */ private void initializeOutputStreams(Walker walker, OutputTracker outputTracker) { for (Map.Entry<ArgumentSource, Object> input : inputs.entrySet()) outputTracker.addInput(input.getKey(), input.getValue()); for (Stub<?> stub : outputs) outputTracker.addOutput(stub); outputTracker.prepareWalker(walker); } /** * Returns the SAM File Header from the input reads' data source file * @return the SAM File Header from the input reads' data source file */ public SAMFileHeader getSAMFileHeader() { return readsDataSource.getHeader(); } /** * Returns the unmerged SAM file header for an individual reader. * @param reader The reader. * @return Header for that reader. */ public SAMFileHeader getSAMFileHeader(SAMReaderID reader) { return readsDataSource.getHeader(reader); } /** * Returns data source object encapsulating all essential info and handlers used to traverse * reads; header merger, individual file readers etc can be accessed through the returned data source object. * * @return the reads data source */ public SAMDataSource getDataSource() { return this.readsDataSource; } /** * Gets the collection of GATK main application arguments for enhanced walker validation. * * @return the GATK argument collection */ public GATKArgumentCollection getArguments() { return this.argCollection; } /** * Get the list of intervals passed to the engine. * @return List of intervals. */ public GenomeLocSortedSet getIntervals() { return this.intervals; } /** * Gets the list of filters employed by this walker. * @return Collection of filters (actual instances) used by this walker. */ public Collection<SamRecordFilter> getFilters() { return this.filters; } /** * Returns data source objects encapsulating all rod data; * individual rods can be accessed through the returned data source objects. * * @return the rods data sources */ public List<ReferenceOrderedDataSource> getRodDataSources() { return this.rodDataSources; } /** * Gets cumulative metrics about the entire run to this point. * @return cumulative metrics about the entire run. */ public ReadMetrics getCumulativeMetrics() { return readsDataSource == null ? null : readsDataSource.getCumulativeReadMetrics(); } /** * Unpack the bam files to be processed, given a list of files. That list of files can * itself contain entries which are lists of other files to be read (note: you cannot have lists of lists of lists) * * @param inputFiles a list of files that represent either bam files themselves, or a file containing a list of bam files to process * * @return a flattened list of the bam files provided */ private List<SAMReaderID> unpackBAMFileList( List<File> inputFiles ) { List<SAMReaderID> unpackedReads = new ArrayList<SAMReaderID>(); for( File inputFile: inputFiles ) { if (inputFile.getName().toLowerCase().endsWith(".list") ) { try { for(String fileName : new XReadLines(inputFile)) unpackedReads.add(new SAMReaderID(new File(fileName),getTags(inputFile))); } catch( FileNotFoundException ex ) { throw new UserException.CouldNotReadInputFile(inputFile, "Unable to find file while unpacking reads", ex); } } else if(inputFile.getName().toLowerCase().endsWith(".bam")) { unpackedReads.add( new SAMReaderID(inputFile,getTags(inputFile)) ); } else if(inputFile.getName().equals("-")) { unpackedReads.add(new SAMReaderID(new File("/dev/stdin"),Collections.<String>emptyList())); } else { throw new UserException.CommandLineException(String.format("The GATK reads argument (-I) supports only BAM files with the .bam extension and lists of BAM files " + "with the .list extension, but the file %s has neither extension. Please ensure that your BAM file or list " + "of BAM files is in the correct format, update the extension, and try again.",inputFile.getName())); } } return unpackedReads; } }
false
true
protected ShardStrategy getShardStrategy(Walker walker, ReferenceSequenceFile drivingDataSource, GenomeLocSortedSet intervals, ValidationExclusion exclusions) { // Use monolithic sharding if no index is present. Monolithic sharding is always required for the original // sharding system; it's required with the new sharding system only for locus walkers. if(readsDataSource != null && !readsDataSource.hasIndex() ) { if(!exclusions.contains(ValidationExclusion.TYPE.ALLOW_UNINDEXED_BAM)) throw new UserException.CommandLineException("The GATK cannot currently process unindexed BAM files without the -U ALLOW_UNINDEXED_BAM"); if(intervals != null && WalkerManager.getWalkerDataSource(walker) != DataSource.REFERENCE) throw new UserException.CommandLineException("Cannot perform interval processing when walker is not driven by reference and no index is available."); Shard.ShardType shardType; if(walker instanceof LocusWalker) { if (readsDataSource.getSortOrder() != SAMFileHeader.SortOrder.coordinate) throw new UserException.MissortedBAM(SAMFileHeader.SortOrder.coordinate, "Locus walkers can only walk over coordinate-sorted data. Please resort your input BAM file(s)."); shardType = Shard.ShardType.LOCUS; } else if(walker instanceof ReadWalker || walker instanceof DuplicateWalker || walker instanceof ReadPairWalker) shardType = Shard.ShardType.READ; else throw new UserException.CommandLineException("The GATK cannot currently process unindexed BAM files"); List<GenomeLoc> region; if(intervals != null) region = intervals.toList(); else { region = new ArrayList<GenomeLoc>(); for(SAMSequenceRecord sequenceRecord: drivingDataSource.getSequenceDictionary().getSequences()) region.add(GenomeLocParser.createGenomeLoc(sequenceRecord.getSequenceName(),1,sequenceRecord.getSequenceLength())); } return new MonolithicShardStrategy(readsDataSource,shardType,region); } ShardStrategy shardStrategy = null; ShardStrategyFactory.SHATTER_STRATEGY shardType; long SHARD_SIZE = 100000L; if (walker instanceof LocusWalker) { if (walker instanceof RodWalker) SHARD_SIZE *= 1000; if (intervals != null && !intervals.isEmpty()) { if(!readsDataSource.isEmpty() && readsDataSource.getSortOrder() != SAMFileHeader.SortOrder.coordinate) throw new UserException.MissortedBAM(SAMFileHeader.SortOrder.coordinate, "Locus walkers can only walk over coordinate-sorted data. Please resort your input BAM file(s)."); shardStrategy = ShardStrategyFactory.shatter(readsDataSource, referenceDataSource.getReference(), ShardStrategyFactory.SHATTER_STRATEGY.LOCUS_EXPERIMENTAL, drivingDataSource.getSequenceDictionary(), SHARD_SIZE, intervals); } else shardStrategy = ShardStrategyFactory.shatter(readsDataSource, referenceDataSource.getReference(), ShardStrategyFactory.SHATTER_STRATEGY.LOCUS_EXPERIMENTAL, drivingDataSource.getSequenceDictionary(), SHARD_SIZE); } else if (walker instanceof ReadWalker || walker instanceof DuplicateWalker) { shardType = ShardStrategyFactory.SHATTER_STRATEGY.READS_EXPERIMENTAL; if (intervals != null && !intervals.isEmpty()) { shardStrategy = ShardStrategyFactory.shatter(readsDataSource, referenceDataSource.getReference(), shardType, drivingDataSource.getSequenceDictionary(), SHARD_SIZE, intervals); } else { shardStrategy = ShardStrategyFactory.shatter(readsDataSource, referenceDataSource.getReference(), shardType, drivingDataSource.getSequenceDictionary(), SHARD_SIZE); } } else if (walker instanceof ReadPairWalker) { if(readsDataSource != null && readsDataSource.getSortOrder() != SAMFileHeader.SortOrder.queryname) throw new UserException.MissortedBAM(SAMFileHeader.SortOrder.queryname, "Read pair walkers can only walk over query name-sorted data. Please resort your input BAM file."); if(intervals != null && !intervals.isEmpty()) throw new UserException.CommandLineException("Pairs traversal cannot be used in conjunction with intervals."); shardStrategy = ShardStrategyFactory.shatter(readsDataSource, referenceDataSource.getReference(), ShardStrategyFactory.SHATTER_STRATEGY.READS_EXPERIMENTAL, drivingDataSource.getSequenceDictionary(), SHARD_SIZE); } else throw new ReviewedStingException("Unable to support walker of type" + walker.getClass().getName()); return shardStrategy; }
protected ShardStrategy getShardStrategy(Walker walker, ReferenceSequenceFile drivingDataSource, GenomeLocSortedSet intervals, ValidationExclusion exclusions) { // Use monolithic sharding if no index is present. Monolithic sharding is always required for the original // sharding system; it's required with the new sharding system only for locus walkers. if(readsDataSource != null && !readsDataSource.hasIndex() ) { if(!exclusions.contains(ValidationExclusion.TYPE.ALLOW_UNINDEXED_BAM)) throw new UserException.CommandLineException("The GATK cannot currently process unindexed BAM files without the -U ALLOW_UNINDEXED_BAM"); if(intervals != null && WalkerManager.getWalkerDataSource(walker) != DataSource.REFERENCE) throw new UserException.CommandLineException("Cannot perform interval processing when walker is not driven by reference and no index is available."); Shard.ShardType shardType; if(walker instanceof LocusWalker) { if (readsDataSource.getSortOrder() != SAMFileHeader.SortOrder.coordinate) throw new UserException.MissortedBAM(SAMFileHeader.SortOrder.coordinate, "Locus walkers can only traverse coordinate-sorted data. Please resort your input BAM file(s) or set the Sort Order tag in the header appropriately."); shardType = Shard.ShardType.LOCUS; } else if(walker instanceof ReadWalker || walker instanceof DuplicateWalker || walker instanceof ReadPairWalker) shardType = Shard.ShardType.READ; else throw new UserException.CommandLineException("The GATK cannot currently process unindexed BAM files"); List<GenomeLoc> region; if(intervals != null) region = intervals.toList(); else { region = new ArrayList<GenomeLoc>(); for(SAMSequenceRecord sequenceRecord: drivingDataSource.getSequenceDictionary().getSequences()) region.add(GenomeLocParser.createGenomeLoc(sequenceRecord.getSequenceName(),1,sequenceRecord.getSequenceLength())); } return new MonolithicShardStrategy(readsDataSource,shardType,region); } ShardStrategy shardStrategy = null; ShardStrategyFactory.SHATTER_STRATEGY shardType; long SHARD_SIZE = 100000L; if (walker instanceof LocusWalker) { if (walker instanceof RodWalker) SHARD_SIZE *= 1000; if (intervals != null && !intervals.isEmpty()) { if(!readsDataSource.isEmpty() && readsDataSource.getSortOrder() != SAMFileHeader.SortOrder.coordinate) throw new UserException.MissortedBAM(SAMFileHeader.SortOrder.coordinate, "Locus walkers can only traverse coordinate-sorted data. Please resort your input BAM file(s) or set the Sort Order tag in the header appropriately."); shardStrategy = ShardStrategyFactory.shatter(readsDataSource, referenceDataSource.getReference(), ShardStrategyFactory.SHATTER_STRATEGY.LOCUS_EXPERIMENTAL, drivingDataSource.getSequenceDictionary(), SHARD_SIZE, intervals); } else shardStrategy = ShardStrategyFactory.shatter(readsDataSource, referenceDataSource.getReference(), ShardStrategyFactory.SHATTER_STRATEGY.LOCUS_EXPERIMENTAL, drivingDataSource.getSequenceDictionary(), SHARD_SIZE); } else if (walker instanceof ReadWalker || walker instanceof DuplicateWalker) { shardType = ShardStrategyFactory.SHATTER_STRATEGY.READS_EXPERIMENTAL; if (intervals != null && !intervals.isEmpty()) { shardStrategy = ShardStrategyFactory.shatter(readsDataSource, referenceDataSource.getReference(), shardType, drivingDataSource.getSequenceDictionary(), SHARD_SIZE, intervals); } else { shardStrategy = ShardStrategyFactory.shatter(readsDataSource, referenceDataSource.getReference(), shardType, drivingDataSource.getSequenceDictionary(), SHARD_SIZE); } } else if (walker instanceof ReadPairWalker) { if(readsDataSource != null && readsDataSource.getSortOrder() != SAMFileHeader.SortOrder.queryname) throw new UserException.MissortedBAM(SAMFileHeader.SortOrder.queryname, "Read pair walkers can only walk over query name-sorted data. Please resort your input BAM file."); if(intervals != null && !intervals.isEmpty()) throw new UserException.CommandLineException("Pairs traversal cannot be used in conjunction with intervals."); shardStrategy = ShardStrategyFactory.shatter(readsDataSource, referenceDataSource.getReference(), ShardStrategyFactory.SHATTER_STRATEGY.READS_EXPERIMENTAL, drivingDataSource.getSequenceDictionary(), SHARD_SIZE); } else throw new ReviewedStingException("Unable to support walker of type" + walker.getClass().getName()); return shardStrategy; }
diff --git a/src/net/sf/hajdbc/sql/AbstractDatabaseCluster.java b/src/net/sf/hajdbc/sql/AbstractDatabaseCluster.java index 116bb890..b52ceced 100644 --- a/src/net/sf/hajdbc/sql/AbstractDatabaseCluster.java +++ b/src/net/sf/hajdbc/sql/AbstractDatabaseCluster.java @@ -1,1007 +1,1007 @@ /* * HA-JDBC: High-Availability JDBC * Copyright (c) 2004-2007 Paul Ferraro * * This library 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 2.1 of the License, or (at your * option) any later version. * * This library 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 library; if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact: [email protected] */ package net.sf.hajdbc.sql; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.nio.channels.Channels; import java.nio.channels.FileChannel; import java.nio.channels.WritableByteChannel; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import javax.management.DynamicMBean; import javax.management.JMException; import javax.management.MBeanRegistration; import javax.management.MBeanServer; import javax.management.ObjectName; import net.sf.hajdbc.Balancer; import net.sf.hajdbc.Database; import net.sf.hajdbc.DatabaseCluster; import net.sf.hajdbc.DatabaseClusterDecorator; import net.sf.hajdbc.DatabaseClusterFactory; import net.sf.hajdbc.DatabaseClusterMBean; import net.sf.hajdbc.DatabaseMetaDataCache; import net.sf.hajdbc.Dialect; import net.sf.hajdbc.LockManager; import net.sf.hajdbc.Messages; import net.sf.hajdbc.StateManager; import net.sf.hajdbc.SynchronizationContext; import net.sf.hajdbc.SynchronizationStrategy; import net.sf.hajdbc.SynchronizationStrategyBuilder; import net.sf.hajdbc.TransactionMode; import net.sf.hajdbc.local.LocalLockManager; import net.sf.hajdbc.local.LocalStateManager; import net.sf.hajdbc.sync.SynchronizationContextImpl; import net.sf.hajdbc.util.concurrent.CronThreadPoolExecutor; import net.sf.hajdbc.util.concurrent.SynchronousExecutor; import org.jibx.runtime.BindingDirectory; import org.jibx.runtime.IMarshallingContext; import org.jibx.runtime.IUnmarshallingContext; import org.jibx.runtime.JiBXException; import org.quartz.CronExpression; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Paul Ferraro * @param <D> either java.sql.Driver or javax.sql.DataSource * @since 1.0 */ public abstract class AbstractDatabaseCluster<D> implements DatabaseCluster<D>, DatabaseClusterMBean, MBeanRegistration { private static Logger logger = LoggerFactory.getLogger(AbstractDatabaseCluster.class); private String id; private Balancer<D> balancer; private Dialect dialect; private DatabaseMetaDataCache databaseMetaDataCache; private String defaultSynchronizationStrategyId; private CronExpression failureDetectionExpression; private CronExpression autoActivationExpression; private int minThreads; private int maxThreads; private int maxIdle; private TransactionMode transactionMode; private boolean identityColumnDetectionEnabled; private boolean sequenceDetectionEnabled; private MBeanServer server; private URL url; private Map<String, SynchronizationStrategy> synchronizationStrategyMap = new HashMap<String, SynchronizationStrategy>(); private DatabaseClusterDecorator decorator; private Map<String, Database<D>> databaseMap = new ConcurrentHashMap<String, Database<D>>(); private Map<Database<D>, D> connectionFactoryMap = new ConcurrentHashMap<Database<D>, D>(); private ExecutorService transactionalExecutor; private ExecutorService nonTransactionalExecutor; private CronThreadPoolExecutor cronExecutor = new CronThreadPoolExecutor(2); private LockManager lockManager = new LocalLockManager(); private StateManager stateManager = new LocalStateManager(this); public AbstractDatabaseCluster(String id, URL url) { this.id = id; this.url = url; } /** * @see net.sf.hajdbc.DatabaseCluster#getConnectionFactoryMap() */ public Map<Database<D>, D> getConnectionFactoryMap() { return this.connectionFactoryMap; } private boolean isAlive(Database<D> database) { try { this.test(database); return true; } catch (SQLException e) { logger.info(Messages.getMessage(Messages.DATABASE_NOT_ALIVE, database, this), e); return false; } } private void test(Database<D> database) throws SQLException { Connection connection = null; try { connection = database.connect(this.connectionFactoryMap.get(database)); Statement statement = connection.createStatement(); statement.execute(this.dialect.getSimpleSQL()); statement.close(); } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { logger.warn(e.toString(), e); } } } } /** * @see net.sf.hajdbc.DatabaseCluster#deactivate(net.sf.hajdbc.Database) */ public synchronized boolean deactivate(Database<D> database) { this.unregister(database); // Reregister database mbean using "inactive" interface this.register(database, database.getInactiveMBean()); boolean removed = this.balancer.remove(database); if (removed) { this.stateManager.remove(database.getId()); } return removed; } /** * @see net.sf.hajdbc.DatabaseCluster#getId() */ public String getId() { return this.id; } /** * @see net.sf.hajdbc.DatabaseClusterMBean#getVersion() */ public String getVersion() { return DatabaseClusterFactory.getVersion(); } /** * @see net.sf.hajdbc.DatabaseCluster#activate(net.sf.hajdbc.Database) */ public synchronized boolean activate(Database<D> database) { this.unregister(database); // Reregister database mbean using "active" interface this.register(database, database.getActiveMBean()); if (database.isDirty()) { this.export(); database.clean(); } boolean added = this.balancer.add(database); if (added) { this.stateManager.add(database.getId()); } return added; } /** * @see net.sf.hajdbc.DatabaseClusterMBean#getActiveDatabases() */ public Set<String> getActiveDatabases() { Set<String> databaseSet = new TreeSet<String>(); for (Database<D> database: this.balancer.all()) { databaseSet.add(database.getId()); } return databaseSet; } /** * @see net.sf.hajdbc.DatabaseClusterMBean#getInactiveDatabases() */ public Set<String> getInactiveDatabases() { Set<String> databaseSet = new TreeSet<String>(this.databaseMap.keySet()); for (Database<D> database: this.balancer.all()) { databaseSet.remove(database.getId()); } return databaseSet; } /** * @see net.sf.hajdbc.DatabaseCluster#getDatabase(java.lang.String) */ public Database<D> getDatabase(String id) { Database<D> database = this.databaseMap.get(id); if (database == null) { throw new IllegalArgumentException(Messages.getMessage(Messages.INVALID_DATABASE, id, this)); } return database; } /** * @see net.sf.hajdbc.DatabaseClusterMBean#getDefaultSynchronizationStrategy() */ public String getDefaultSynchronizationStrategy() { return this.defaultSynchronizationStrategyId; } /** * @see net.sf.hajdbc.DatabaseClusterMBean#getSynchronizationStrategies() */ public Set<String> getSynchronizationStrategies() { return new TreeSet<String>(this.synchronizationStrategyMap.keySet()); } /** * @see net.sf.hajdbc.DatabaseCluster#getBalancer() */ public Balancer<D> getBalancer() { return this.balancer; } /** * @see net.sf.hajdbc.DatabaseCluster#getTransactionalExecutor() */ public ExecutorService getTransactionalExecutor() { return this.transactionalExecutor; } /** * @see net.sf.hajdbc.DatabaseCluster#getNonTransactionalExecutor() */ public ExecutorService getNonTransactionalExecutor() { return this.nonTransactionalExecutor; } /** * @see net.sf.hajdbc.DatabaseCluster#getDialect() */ public Dialect getDialect() { return this.dialect; } /** * @see net.sf.hajdbc.DatabaseCluster#getDatabaseMetaDataCache() */ public DatabaseMetaDataCache getDatabaseMetaDataCache() { return this.databaseMetaDataCache; } /** * @see net.sf.hajdbc.DatabaseCluster#getLockManager() */ public LockManager getLockManager() { return this.lockManager; } /** * @see net.sf.hajdbc.DatabaseClusterMBean#isAlive(java.lang.String) */ public boolean isAlive(String id) { return this.isAlive(this.getDatabase(id)); } /** * @see net.sf.hajdbc.DatabaseClusterMBean#deactivate(java.lang.String) */ public void deactivate(String databaseId) { if (this.deactivate(this.getDatabase(databaseId))) { logger.info(Messages.getMessage(Messages.DATABASE_DEACTIVATED, databaseId, this)); } } /** * @see net.sf.hajdbc.DatabaseClusterMBean#activate(java.lang.String) */ public void activate(String databaseId) { this.activate(databaseId, this.getDefaultSynchronizationStrategy()); } /** * @see net.sf.hajdbc.DatabaseClusterMBean#activate(java.lang.String, java.lang.String) */ public void activate(String databaseId, String strategyId) { SynchronizationStrategy strategy = this.synchronizationStrategyMap.get(strategyId); if (strategy == null) { throw new IllegalArgumentException(Messages.getMessage(Messages.INVALID_SYNC_STRATEGY, strategyId)); } this.activate(databaseId, strategy); } /** * Handles a failure caused by the specified cause on the specified database. * If the database is not alive, then it is deactivated, otherwise an exception is thrown back to the caller. * @param database a database descriptor * @param cause the cause of the failure * @throws SQLException if the database is alive */ public void handleFailure(Database<D> database, SQLException cause) throws SQLException { if ((this.balancer.size() <= 1) || this.isAlive(database)) { throw cause; } if (this.deactivate(database)) { logger.error(Messages.getMessage(Messages.DATABASE_DEACTIVATED, database, this), cause); } } protected void register(Database<D> database, DynamicMBean mbean) { try { ObjectName name = DatabaseClusterFactory.getObjectName(this.id, database.getId()); this.server.registerMBean(mbean, name); } catch (JMException e) { logger.error(e.toString(), e); throw new IllegalStateException(e); } } /** * @see net.sf.hajdbc.DatabaseClusterMBean#remove(java.lang.String) */ public synchronized void remove(String id) { Database<D> database = this.getDatabase(id); if (this.balancer.contains(database)) { throw new IllegalStateException(Messages.getMessage(Messages.DATABASE_STILL_ACTIVE, id, this)); } this.unregister(database); this.databaseMap.remove(id); this.connectionFactoryMap.remove(database); this.export(); } private void unregister(Database<D> database) { try { ObjectName name = DatabaseClusterFactory.getObjectName(this.id, database.getId()); if (this.server.isRegistered(name)) { this.server.unregisterMBean(name); } } catch (JMException e) { logger.error(e.toString(), e); throw new IllegalStateException(e); } } /** * Starts this database cluster * @throws Exception if database cluster start fails */ public synchronized void start() throws Exception { for (Database<D> database: this.databaseMap.values()) { this.register(database, database.getInactiveMBean()); } this.lockManager.start(); this.stateManager.start(); Set<String> databaseSet = this.stateManager.getInitialState(); if (databaseSet != null) { for (String databaseId: databaseSet) { Database<D> database = this.getDatabase(databaseId); if (database != null) { this.activate(database); } } } else { for (Database<D> database: this.databaseMap.values()) { if (this.isAlive(database)) { this.activate(database); } } } this.nonTransactionalExecutor = new ThreadPoolExecutor(this.minThreads, this.maxThreads, this.maxIdle, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), new ThreadPoolExecutor.CallerRunsPolicy()); this.transactionalExecutor = this.transactionMode.equals(TransactionMode.SERIAL) ? new SynchronousExecutor() : this.nonTransactionalExecutor; this.databaseMetaDataCache.setDialect(this.dialect); try { this.flushMetaDataCache(); } catch (IllegalStateException e) { // Ignore - cache will initialize lazily. } if (this.failureDetectionExpression != null) { this.cronExecutor.schedule(new FailureDetectionTask(), this.failureDetectionExpression); } if (this.autoActivationExpression != null) { this.cronExecutor.schedule(new AutoActivationTask(), this.autoActivationExpression); } } /** * Stops this database cluster */ public synchronized void stop() { for (Database<D> database: this.databaseMap.values()) { this.unregister(database); } this.stateManager.stop(); this.lockManager.stop(); this.cronExecutor.shutdownNow(); if (this.nonTransactionalExecutor != null) { this.nonTransactionalExecutor.shutdownNow(); } if (this.transactionalExecutor != null) { this.transactionalExecutor.shutdownNow(); } } /** * @see net.sf.hajdbc.DatabaseClusterMBean#flushMetaDataCache() */ @SuppressWarnings("unchecked") public void flushMetaDataCache() { Connection connection = null; try { Database database = this.balancer.next(); connection = database.connect(this.connectionFactoryMap.get(database)); this.databaseMetaDataCache.flush(connection); } catch (NoSuchElementException e) { throw new IllegalStateException(Messages.getMessage(Messages.NO_ACTIVE_DATABASES, this)); } catch (SQLException e) { throw new IllegalStateException(e.toString(), e); } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { logger.warn(e.toString(), e); } } } } /** * @see net.sf.hajdbc.DatabaseCluster#isIdentityColumnDetectionEnabled() */ public boolean isIdentityColumnDetectionEnabled() { return this.identityColumnDetectionEnabled; } /** * @see net.sf.hajdbc.DatabaseCluster#isSequenceDetectionEnabled() */ public boolean isSequenceDetectionEnabled() { return this.sequenceDetectionEnabled; } /** * @see java.lang.Object#toString() */ @Override public String toString() { return this.getId(); } /** * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object object) { return (object != null) && DatabaseCluster.class.isInstance(object) && this.id.equals(DatabaseCluster.class.cast(object).getId()); } /** * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return this.id.hashCode(); } SynchronizationStrategyBuilder getDefaultSynchronizationStrategyBuilder() { return new SynchronizationStrategyBuilder(this.defaultSynchronizationStrategyId); } void setDefaultSynchronizationStrategyBuilder(SynchronizationStrategyBuilder builder) { this.defaultSynchronizationStrategyId = builder.getId(); } DatabaseClusterDecorator getDecorator() { return this.decorator; } void setDecorator(DatabaseClusterDecorator decorator) { this.decorator = decorator; } protected synchronized void add(Database<D> database) { String id = database.getId(); if (this.databaseMap.containsKey(id)) { throw new IllegalArgumentException(Messages.getMessage(Messages.DATABASE_ALREADY_EXISTS, id, this)); } this.connectionFactoryMap.put(database, database.createConnectionFactory()); this.databaseMap.put(id, database); } Iterator<Database<D>> getDatabases() { return this.databaseMap.values().iterator(); } /** * @see net.sf.hajdbc.DatabaseCluster#getStateManager() */ public StateManager getStateManager() { return this.stateManager; } /** * @see net.sf.hajdbc.DatabaseCluster#setStateManager(net.sf.hajdbc.StateManager) */ public void setStateManager(StateManager stateManager) { this.stateManager = stateManager; } /** * @see net.sf.hajdbc.DatabaseCluster#setLockManager(net.sf.hajdbc.LockManager) */ public void setLockManager(LockManager lockManager) { this.lockManager = lockManager; } /** * @see net.sf.hajdbc.DatabaseClusterMBean#getUrl() */ public URL getUrl() { return this.url; } private void activate(String databaseId, SynchronizationStrategy strategy) { try { if (this.activate(this.getDatabase(databaseId), strategy)) { logger.info(Messages.getMessage(Messages.DATABASE_ACTIVATED, databaseId, this)); } } catch (SQLException e) { logger.warn(Messages.getMessage(Messages.DATABASE_ACTIVATE_FAILED, databaseId, this), e); SQLException exception = e.getNextException(); while (exception != null) { logger.error(exception.getMessage(), e); exception = exception.getNextException(); } throw new IllegalStateException(e.toString()); } catch (InterruptedException e) { logger.warn(e.toString(), e); throw new IllegalMonitorStateException(e.toString()); } } private boolean activate(Database<D> database, SynchronizationStrategy strategy) throws SQLException, InterruptedException { Lock lock = this.lockManager.writeLock(LockManager.GLOBAL); lock.lockInterruptibly(); try { if (this.balancer.contains(database)) { return false; } this.test(database); SynchronizationContext<D> context = new SynchronizationContextImpl<D>(this, database); try { strategy.prepare(context); logger.info(Messages.getMessage(Messages.DATABASE_SYNC_START, database, this)); strategy.synchronize(context); logger.info(Messages.getMessage(Messages.DATABASE_SYNC_END, database, this)); boolean activated = this.activate(database); strategy.cleanup(context); return activated; } finally { context.close(); } } catch (NoSuchElementException e) { return this.activate(database); } finally { lock.unlock(); } } /** * @see javax.management.MBeanRegistration#postDeregister() */ @Override public void postDeregister() { this.stop(); } /** * @see javax.management.MBeanRegistration#postRegister(java.lang.Boolean) */ @Override public void postRegister(Boolean registered) { if (!registered) { this.stop(); } } /** * @see javax.management.MBeanRegistration#preDeregister() */ @Override public void preDeregister() throws Exception { } /** * @see javax.management.MBeanRegistration#preRegister(javax.management.MBeanServer, javax.management.ObjectName) */ @Override public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { this.server = server; InputStream inputStream = null; logger.info(Messages.getMessage(Messages.HA_JDBC_INIT, this.getVersion(), this.url)); try { inputStream = url.openStream(); IUnmarshallingContext context = BindingDirectory.getFactory(this.getClass()).createUnmarshallingContext(); context.setDocument(inputStream, null); context.setUserContext(this); context.unmarshalElement(); if (this.decorator != null) { this.decorator.decorate(this); } this.start(); return name; } catch (IOException e) { logger.error(Messages.getMessage(Messages.CONFIG_NOT_FOUND, url), e); throw e; } catch (JiBXException e) { logger.error(Messages.getMessage(Messages.CONFIG_LOAD_FAILED, url), e); throw e; } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { logger.warn(e.toString(), e); } } } } private void export() { File file = null; WritableByteChannel outputChannel = null; FileChannel fileChannel = null; try { file = File.createTempFile("ha-jdbc", ".xml"); IMarshallingContext context = BindingDirectory.getFactory(this.getClass()).createMarshallingContext(); context.setIndent(1, System.getProperty("line.separator"), '\t'); // This method closes the writer context.marshalDocument(this, null, null, new FileWriter(file)); fileChannel = new FileInputStream(file).getChannel(); - // We cannot use URLConnection for files becuase Sun's implementation does not support output. + // We cannot use URLConnection for files because Sun's implementation does not support output. if (this.url.getProtocol().equals("file")) { outputChannel = new FileOutputStream(new File(this.url.getPath())).getChannel(); } else { URLConnection connection = this.url.openConnection(); connection.connect(); outputChannel = Channels.newChannel(connection.getOutputStream()); } fileChannel.transferTo(0, file.length(), outputChannel); } catch (Exception e) { logger.warn(Messages.getMessage(Messages.CONFIG_STORE_FAILED, this.url), e); } finally { if (outputChannel != null) { try { outputChannel.close(); } catch (IOException e) { logger.warn(e.getMessage(), e); } } if (fileChannel != null) { try { fileChannel.close(); } catch (IOException e) { logger.warn(e.getMessage(), e); } } if (file != null) { file.delete(); } } } void addSynchronizationStrategyBuilder(SynchronizationStrategyBuilder builder) throws Exception { this.synchronizationStrategyMap.put(builder.getId(), builder.buildStrategy()); } Iterator<SynchronizationStrategyBuilder> getSynchronizationStrategyBuilders() throws Exception { List<SynchronizationStrategyBuilder> builderList = new ArrayList<SynchronizationStrategyBuilder>(this.synchronizationStrategyMap.size()); for (Map.Entry<String, SynchronizationStrategy> mapEntry: this.synchronizationStrategyMap.entrySet()) { builderList.add(SynchronizationStrategyBuilder.getBuilder(mapEntry.getKey(), mapEntry.getValue())); } return builderList.iterator(); } class FailureDetectionTask implements Runnable { /** * @see java.lang.Runnable#run() */ public void run() { Balancer<D> balancer = AbstractDatabaseCluster.this.getBalancer(); for (Database<D> database: AbstractDatabaseCluster.this.getBalancer().all()) { if ((balancer.size() > 1) && !AbstractDatabaseCluster.this.isAlive(database)) { if (AbstractDatabaseCluster.this.deactivate(database)) { logger.error(Messages.getMessage(Messages.DATABASE_DEACTIVATED, database, this)); } } } } } class AutoActivationTask implements Runnable { /** * @see java.lang.Runnable#run() */ public void run() { for (String databaseId: AbstractDatabaseCluster.this.getInactiveDatabases()) { AbstractDatabaseCluster.this.activate(databaseId); } } } }
true
true
private void export() { File file = null; WritableByteChannel outputChannel = null; FileChannel fileChannel = null; try { file = File.createTempFile("ha-jdbc", ".xml"); IMarshallingContext context = BindingDirectory.getFactory(this.getClass()).createMarshallingContext(); context.setIndent(1, System.getProperty("line.separator"), '\t'); // This method closes the writer context.marshalDocument(this, null, null, new FileWriter(file)); fileChannel = new FileInputStream(file).getChannel(); // We cannot use URLConnection for files becuase Sun's implementation does not support output. if (this.url.getProtocol().equals("file")) { outputChannel = new FileOutputStream(new File(this.url.getPath())).getChannel(); } else { URLConnection connection = this.url.openConnection(); connection.connect(); outputChannel = Channels.newChannel(connection.getOutputStream()); } fileChannel.transferTo(0, file.length(), outputChannel); } catch (Exception e) { logger.warn(Messages.getMessage(Messages.CONFIG_STORE_FAILED, this.url), e); } finally { if (outputChannel != null) { try { outputChannel.close(); } catch (IOException e) { logger.warn(e.getMessage(), e); } } if (fileChannel != null) { try { fileChannel.close(); } catch (IOException e) { logger.warn(e.getMessage(), e); } } if (file != null) { file.delete(); } } }
private void export() { File file = null; WritableByteChannel outputChannel = null; FileChannel fileChannel = null; try { file = File.createTempFile("ha-jdbc", ".xml"); IMarshallingContext context = BindingDirectory.getFactory(this.getClass()).createMarshallingContext(); context.setIndent(1, System.getProperty("line.separator"), '\t'); // This method closes the writer context.marshalDocument(this, null, null, new FileWriter(file)); fileChannel = new FileInputStream(file).getChannel(); // We cannot use URLConnection for files because Sun's implementation does not support output. if (this.url.getProtocol().equals("file")) { outputChannel = new FileOutputStream(new File(this.url.getPath())).getChannel(); } else { URLConnection connection = this.url.openConnection(); connection.connect(); outputChannel = Channels.newChannel(connection.getOutputStream()); } fileChannel.transferTo(0, file.length(), outputChannel); } catch (Exception e) { logger.warn(Messages.getMessage(Messages.CONFIG_STORE_FAILED, this.url), e); } finally { if (outputChannel != null) { try { outputChannel.close(); } catch (IOException e) { logger.warn(e.getMessage(), e); } } if (fileChannel != null) { try { fileChannel.close(); } catch (IOException e) { logger.warn(e.getMessage(), e); } } if (file != null) { file.delete(); } } }
diff --git a/components/bio-formats/src/loci/formats/in/OMETiffReader.java b/components/bio-formats/src/loci/formats/in/OMETiffReader.java index 747f09a2c..bee07f44a 100644 --- a/components/bio-formats/src/loci/formats/in/OMETiffReader.java +++ b/components/bio-formats/src/loci/formats/in/OMETiffReader.java @@ -1,710 +1,715 @@ // // OMETiffReader.java // /* OME Bio-Formats package for reading and converting biological file formats. Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc. 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package loci.formats.in; import java.io.File; import java.io.IOException; import java.util.Enumeration; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.Vector; import ome.xml.model.primitives.NonNegativeInteger; import ome.xml.model.primitives.PositiveInteger; import loci.common.Location; import loci.common.RandomAccessInputStream; import loci.common.services.DependencyException; import loci.common.services.ServiceException; import loci.common.services.ServiceFactory; import loci.formats.CoreMetadata; import loci.formats.FormatException; import loci.formats.FormatReader; import loci.formats.FormatTools; import loci.formats.IFormatReader; import loci.formats.MetadataTools; import loci.formats.MissingLibraryException; import loci.formats.meta.MetadataStore; import loci.formats.ome.OMEXMLMetadata; import loci.formats.services.OMEXMLService; import loci.formats.tiff.IFD; import loci.formats.tiff.IFDList; import loci.formats.tiff.PhotoInterp; import loci.formats.tiff.TiffParser; /** * OMETiffReader is the file format reader for * <a href="http://ome-xml.org/wiki/OmeTiff">OME-TIFF</a> files. * * <dl><dt><b>Source code:</b></dt> * <dd><a href="http://dev.loci.wisc.edu/trac/java/browser/trunk/components/bio-formats/src/loci/formats/in/OMETiffReader.java">Trac</a>, * <a href="http://dev.loci.wisc.edu/svn/java/trunk/components/bio-formats/src/loci/formats/in/OMETiffReader.java">SVN</a></dd></dl> */ public class OMETiffReader extends FormatReader { // -- Constants -- public static final String NO_OME_XML_MSG = "ome-xml.jar is required to read OME-TIFF files. " + "Please download it from " + FormatTools.URL_BIO_FORMATS_LIBRARIES; // -- Fields -- /** Mapping from series and plane numbers to files and IFD entries. */ protected OMETiffPlane[][] info; // dimensioned [numSeries][numPlanes] /** List of used files. */ protected String[] used; private int lastPlane; private boolean hasSPW; private OMEXMLService service; // -- Constructor -- /** Constructs a new OME-TIFF reader. */ public OMETiffReader() { super("OME-TIFF", new String[] {"ome.tif", "ome.tiff"}); suffixNecessary = false; suffixSufficient = false; domains = FormatTools.NON_GRAPHICS_DOMAINS; hasCompanionFiles = true; } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#isSingleFile(String) */ public boolean isSingleFile(String id) throws FormatException, IOException { // parse and populate OME-XML metadata String fileName = new Location(id).getAbsoluteFile().getAbsolutePath(); RandomAccessInputStream ras = new RandomAccessInputStream(fileName); TiffParser tp = new TiffParser(ras); IFD ifd = tp.getFirstIFD(); long[] ifdOffsets = tp.getIFDOffsets(); ras.close(); String xml = ifd.getComment(); if (service == null) setupService(); OMEXMLMetadata meta; try { meta = service.createOMEXMLMetadata(xml); } catch (ServiceException se) { throw new FormatException(se); } if (meta.getRoot() == null) { throw new FormatException("Could not parse OME-XML from TIFF comment"); } int nImages = 0; for (int i=0; i<meta.getImageCount(); i++) { int nChannels = meta.getChannelCount(i); if (nChannels == 0) nChannels = 1; int z = meta.getPixelsSizeZ(i).getValue().intValue(); int t = meta.getPixelsSizeT(i).getValue().intValue(); nImages += z * t * nChannels; } return nImages <= ifdOffsets.length; } /* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */ public boolean isThisType(RandomAccessInputStream stream) throws IOException { TiffParser tp = new TiffParser(stream); boolean validHeader = tp.isValidHeader(); if (!validHeader) return false; // look for OME-XML in first IFD's comment IFD ifd = tp.getFirstIFD(); if (ifd == null) return false; String comment = ifd.getComment(); if (comment == null || comment.trim().length() == 0) return false; try { if (service == null) setupService(); service.createOMEXMLMetadata(comment.trim()); return true; } catch (ServiceException se) { } catch (NullPointerException e) { } catch (FormatException e) { } return false; } /* @see loci.formats.IFormatReader#getDomains() */ public String[] getDomains() { FormatTools.assertId(currentId, true, 1); return hasSPW ? new String[] {FormatTools.HCS_DOMAIN} : FormatTools.NON_SPECIAL_DOMAINS; } /* @see loci.formats.IFormatReader#get8BitLookupTable() */ public byte[][] get8BitLookupTable() throws FormatException, IOException { if (info[series][lastPlane] == null || info[series][lastPlane].reader == null || info[series][lastPlane].id == null) { return null; } info[series][lastPlane].reader.setId(info[series][lastPlane].id); return info[series][lastPlane].reader.get8BitLookupTable(); } /* @see loci.formats.IFormatReader#get16BitLookupTable() */ public short[][] get16BitLookupTable() throws FormatException, IOException { if (info[series][lastPlane] == null || info[series][lastPlane].reader == null || info[series][lastPlane].id == null) { return null; } info[series][lastPlane].reader.setId(info[series][lastPlane].id); return info[series][lastPlane].reader.get16BitLookupTable(); } /* * @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int) */ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h); lastPlane = no; int i = info[series][no].ifd; MinimalTiffReader r = (MinimalTiffReader) info[series][no].reader; if (r.getCurrentFile() == null) { r.setId(info[series][no].id); } IFDList ifdList = r.getIFDs(); if (i >= ifdList.size()) { LOGGER.warn("Error untangling IFDs; the OME-TIFF file may be malformed."); return buf; } IFD ifd = ifdList.get(i); RandomAccessInputStream s = new RandomAccessInputStream(info[series][no].id); TiffParser p = new TiffParser(s); p.getSamples(ifd, buf, x, y, w, h); s.close(); return buf; } /* @see loci.formats.IFormatReader#getSeriesUsedFiles(boolean) */ public String[] getSeriesUsedFiles(boolean noPixels) { FormatTools.assertId(currentId, true, 1); if (noPixels) return null; Vector<String> usedFiles = new Vector<String>(); for (int i=0; i<info[series].length; i++) { if (!usedFiles.contains(info[series][i].id)) { usedFiles.add(info[series][i].id); } } return usedFiles.toArray(new String[usedFiles.size()]); } /* @see loci.formats.IFormatReader#fileGroupOption() */ public int fileGroupOption(String id) { return FormatTools.MUST_GROUP; } /* @see loci.formats.IFormatReader#close(boolean) */ public void close(boolean fileOnly) throws IOException { super.close(fileOnly); if (!fileOnly) { info = null; used = null; lastPlane = 0; } } // -- Internal FormatReader API methods -- /* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { // normalize file name super.initFile(normalizeFilename(null, id)); id = currentId; String dir = new File(id).getParent(); // parse and populate OME-XML metadata String fileName = new Location(id).getAbsoluteFile().getAbsolutePath(); RandomAccessInputStream ras = new RandomAccessInputStream(fileName); TiffParser tp = new TiffParser(ras); IFD firstIFD = tp.getFirstIFD(); ras.close(); String xml = firstIFD.getComment(); if (service == null) setupService(); OMEXMLMetadata meta; try { meta = service.createOMEXMLMetadata(xml); } catch (ServiceException se) { throw new FormatException(se); } hasSPW = meta.getPlateCount() > 0; // TODO //Hashtable originalMetadata = meta.getOriginalMetadata(); //if (originalMetadata != null) metadata = originalMetadata; LOGGER.trace(xml); if (meta.getRoot() == null) { throw new FormatException("Could not parse OME-XML from TIFF comment"); } String currentUUID = meta.getUUID(); service.convertMetadata(meta, metadataStore); // determine series count from Image and Pixels elements int seriesCount = meta.getImageCount(); core = new CoreMetadata[seriesCount]; for (int i=0; i<seriesCount; i++) { core[i] = new CoreMetadata(); } info = new OMETiffPlane[seriesCount][]; // compile list of file/UUID mappings Hashtable<String, String> files = new Hashtable<String, String>(); boolean needSearch = false; for (int i=0; i<seriesCount; i++) { int tiffDataCount = meta.getTiffDataCount(i); for (int td=0; td<tiffDataCount; td++) { String uuid = null; try { uuid = meta.getUUIDValue(i, td); } catch (NullPointerException e) { } String filename = null; if (uuid == null) { // no UUID means that TiffData element refers to this file uuid = ""; filename = id; } else { filename = meta.getUUIDFileName(i, td); if (!new Location(dir, filename).exists()) filename = null; if (filename == null) { if (uuid.equals(currentUUID) || currentUUID == null) { // UUID references this file filename = id; } else { // will need to search for this UUID filename = ""; needSearch = true; } } else filename = normalizeFilename(dir, filename); } String existing = files.get(uuid); if (existing == null) files.put(uuid, filename); else if (!existing.equals(filename)) { throw new FormatException("Inconsistent UUID filenames"); } } } // search for missing filenames if (needSearch) { Enumeration en = files.keys(); while (en.hasMoreElements()) { String uuid = (String) en.nextElement(); String filename = files.get(uuid); if (filename.equals("")) { // TODO search... // should scan only other .ome.tif files // to make this work with OME server may be a little tricky? throw new FormatException("Unmatched UUID: " + uuid); } } } // build list of used files Enumeration en = files.keys(); int numUUIDs = files.size(); HashSet fileSet = new HashSet(); // ensure no duplicate filenames for (int i=0; i<numUUIDs; i++) { String uuid = (String) en.nextElement(); String filename = files.get(uuid); fileSet.add(filename); } used = new String[fileSet.size()]; Iterator iter = fileSet.iterator(); for (int i=0; i<used.length; i++) used[i] = (String) iter.next(); // process TiffData elements Hashtable<String, IFormatReader> readers = new Hashtable<String, IFormatReader>(); for (int i=0; i<seriesCount; i++) { int s = i; LOGGER.debug("Image[{}] {", i); LOGGER.debug(" id = {}", meta.getImageID(i)); String order = meta.getPixelsDimensionOrder(i).toString(); PositiveInteger samplesPerPixel = null; if (meta.getChannelCount(i) > 0) { samplesPerPixel = meta.getChannelSamplesPerPixel(i, 0); } int samples = samplesPerPixel == null ? -1 : samplesPerPixel.getValue(); int tiffSamples = firstIFD.getSamplesPerPixel(); if (samples != tiffSamples) { LOGGER.warn("SamplesPerPixel mismatch: OME={}, TIFF={}", samples, tiffSamples); samples = tiffSamples; } int effSizeC = meta.getPixelsSizeC(i).getValue().intValue() / samples; if (effSizeC == 0) effSizeC = 1; if (effSizeC * samples != meta.getPixelsSizeC(i).getValue().intValue()) { effSizeC = meta.getPixelsSizeC(i).getValue().intValue(); } int sizeT = meta.getPixelsSizeT(i).getValue().intValue(); int sizeZ = meta.getPixelsSizeZ(i).getValue().intValue(); int num = effSizeC * sizeT * sizeZ; OMETiffPlane[] planes = new OMETiffPlane[num]; for (int no=0; no<num; no++) planes[no] = new OMETiffPlane(); int tiffDataCount = meta.getTiffDataCount(i); boolean zOneIndexed = false; boolean cOneIndexed = false; boolean tOneIndexed = false; // pre-scan TiffData indices to see if any of them are indexed from 1 for (int td=0; td<tiffDataCount; td++) { NonNegativeInteger firstC = meta.getTiffDataFirstC(i, td); NonNegativeInteger firstT = meta.getTiffDataFirstT(i, td); NonNegativeInteger firstZ = meta.getTiffDataFirstZ(i, td); int c = firstC == null ? 0 : firstC.getValue(); int t = firstT == null ? 0 : firstT.getValue(); int z = firstZ == null ? 0 : firstZ.getValue(); if (c >= effSizeC) cOneIndexed = true; if (z >= sizeZ) zOneIndexed = true; if (t >= sizeT) tOneIndexed = true; } for (int td=0; td<tiffDataCount; td++) { LOGGER.debug(" TiffData[{}] {", td); // extract TiffData parameters String filename = null; String uuid = null; try { filename = meta.getUUIDFileName(i, td); } catch (NullPointerException e) { LOGGER.debug("Ignoring null UUID object when retrieving filename."); } try { uuid = meta.getUUIDValue(i, td); } catch (NullPointerException e) { LOGGER.debug("Ignoring null UUID object when retrieving value."); } NonNegativeInteger tdIFD = meta.getTiffDataIFD(i, td); int ifd = tdIFD == null ? 0 : tdIFD.getValue(); NonNegativeInteger numPlanes = meta.getTiffDataPlaneCount(i, td); NonNegativeInteger firstC = meta.getTiffDataFirstC(i, td); NonNegativeInteger firstT = meta.getTiffDataFirstT(i, td); NonNegativeInteger firstZ = meta.getTiffDataFirstZ(i, td); int c = firstC == null ? 0 : firstC.getValue(); int t = firstT == null ? 0 : firstT.getValue(); int z = firstZ == null ? 0 : firstZ.getValue(); // NB: some writers index FirstC, FirstZ and FirstT from 1 if (cOneIndexed) c--; if (zOneIndexed) z--; if (tOneIndexed) t--; int index = FormatTools.getIndex(order, sizeZ, effSizeC, sizeT, num, z, c, t); int count = numPlanes == null ? 1 : numPlanes.getValue(); if (count == 0) { core[s] = null; break; } // get reader object for this filename if (filename == null) { if (uuid == null) filename = id; else filename = files.get(uuid); } else filename = normalizeFilename(dir, filename); IFormatReader r = readers.get(filename); if (r == null) { r = new MinimalTiffReader(); readers.put(filename, r); } Location file = new Location(filename); if (!file.exists()) { // if this is an absolute file name, try using a relative name // old versions of OMETiffWriter wrote an absolute path to // UUID.FileName, which causes problems if the file is moved to // a different directory filename = filename.substring(filename.lastIndexOf(File.separator) + 1); filename = dir + File.separator + filename; if (!new Location(filename).exists()) { filename = currentId; } } // populate plane index -> IFD mapping for (int q=0; q<count; q++) { int no = index + q; planes[no].reader = r; planes[no].id = filename; planes[no].ifd = ifd + q; planes[no].certain = true; LOGGER.debug(" Plane[{}]: file={}, IFD={}", new Object[] {no, planes[no].id, planes[no].ifd}); } if (numPlanes == null) { // unknown number of planes; fill down for (int no=index+1; no<num; no++) { if (planes[no].certain) break; planes[no].reader = r; planes[no].id = filename; planes[no].ifd = planes[no - 1].ifd + 1; LOGGER.debug(" Plane[{}]: FILLED", no); } } else { // known number of planes; clear anything subsequently filled for (int no=index+count; no<num; no++) { if (planes[no].certain) break; planes[no].reader = null; planes[no].id = null; planes[no].ifd = -1; LOGGER.debug(" Plane[{}]: CLEARED", no); } } LOGGER.debug(" }"); } if (core[s] == null) continue; // verify that all planes are available LOGGER.debug(" --------------------------------"); for (int no=0; no<num; no++) { LOGGER.debug(" Plane[{}]: file={}, IFD={}", new Object[] {no, planes[no].id, planes[no].ifd}); if (planes[no].reader == null) { LOGGER.warn("Image ID '{}': missing plane #{}. " + "Using TiffReader to determine the number of planes.", meta.getImageID(i), no); TiffReader r = new TiffReader(); r.setId(currentId); planes = new OMETiffPlane[r.getImageCount()]; for (int plane=0; plane<planes.length; plane++) { planes[plane] = new OMETiffPlane(); planes[plane].id = currentId; planes[plane].reader = r; planes[plane].ifd = plane; } num = planes.length; r.close(); } } LOGGER.debug(" }"); // populate core metadata info[s] = planes; try { core[s].sizeX = meta.getPixelsSizeX(i).getValue().intValue(); int tiffWidth = (int) firstIFD.getImageWidth(); if (core[s].sizeX != tiffWidth) { LOGGER.warn("SizeX mismatch: OME={}, TIFF={}", core[s].sizeX, tiffWidth); } core[s].sizeY = meta.getPixelsSizeY(i).getValue().intValue(); int tiffHeight = (int) firstIFD.getImageLength(); if (core[s].sizeY != tiffHeight) { LOGGER.warn("SizeY mismatch: OME={}, TIFF={}", core[s].sizeY, tiffHeight); } core[s].sizeZ = meta.getPixelsSizeZ(i).getValue().intValue(); core[s].sizeC = meta.getPixelsSizeC(i).getValue().intValue(); core[s].sizeT = meta.getPixelsSizeT(i).getValue().intValue(); core[s].pixelType = FormatTools.pixelTypeFromString( meta.getPixelsType(i).toString()); int tiffPixelType = firstIFD.getPixelType(); if (core[s].pixelType != tiffPixelType) { LOGGER.warn("PixelType mismatch: OME={}, TIFF={}", core[s].pixelType, tiffPixelType); core[s].pixelType = tiffPixelType; } core[s].imageCount = num; core[s].dimensionOrder = meta.getPixelsDimensionOrder(i).toString(); // hackish workaround for files exported by OMERO that have an // incorrect dimension order + String uuidFileName = ""; + try { + uuidFileName = meta.getUUIDFileName(i, 0); + } + catch (NullPointerException e) { } if (meta.getChannelCount(i) > 0 && meta.getChannelName(i, 0) == null && meta.getTiffDataCount(i) > 0 && - meta.getUUIDFileName(i, 0).indexOf("__omero_export") != -1) + uuidFileName.indexOf("__omero_export") != -1) { int zIndex = core[s].dimensionOrder.indexOf("Z"); int tIndex = core[s].dimensionOrder.indexOf("T"); core[s].dimensionOrder = zIndex < tIndex ? "XYCZT" : "XYCTZ"; } core[s].orderCertain = true; PhotoInterp photo = firstIFD.getPhotometricInterpretation(); core[s].rgb = samples > 1 || photo == PhotoInterp.RGB; if ((samples != core[s].sizeC && (samples % core[s].sizeC) != 0 && (core[s].sizeC % samples) != 0) || core[s].sizeC == 1) { core[s].sizeC *= samples; } if (core[s].sizeZ * core[s].sizeT * core[s].sizeC > core[s].imageCount && !core[s].rgb) { if (core[s].sizeZ == core[s].imageCount) { core[s].sizeT = 1; core[s].sizeC = 1; } else if (core[s].sizeT == core[s].imageCount) { core[s].sizeZ = 1; core[s].sizeC = 1; } else if (core[s].sizeC == core[s].imageCount) { core[s].sizeT = 1; core[s].sizeZ = 1; } } if (meta.getPixelsBinDataCount(i) > 1) { LOGGER.warn("OME-TIFF Pixels element contains BinData elements! " + "Ignoring."); } core[s].littleEndian = firstIFD.isLittleEndian(); core[s].interleaved = false; core[s].indexed = photo == PhotoInterp.RGB_PALETTE && firstIFD.getIFDValue(IFD.COLOR_MAP) != null; if (core[s].indexed) { core[s].rgb = false; } core[s].falseColor = false; core[s].metadataComplete = true; } catch (NullPointerException exc) { throw new FormatException("Incomplete Pixels metadata", exc); } } // remove null CoreMetadata entries Vector<CoreMetadata> series = new Vector<CoreMetadata>(); Vector<OMETiffPlane[]> planeInfo = new Vector<OMETiffPlane[]>(); for (int i=0; i<core.length; i++) { if (core[i] != null) { series.add(core[i]); planeInfo.add(info[i]); } } core = series.toArray(new CoreMetadata[series.size()]); info = planeInfo.toArray(new OMETiffPlane[0][0]); MetadataTools.populatePixels(metadataStore, this, false, false); metadataStore = getMetadataStoreForDisplay(); } // -- OMETiffReader API methods -- /** * Returns a MetadataStore that is populated in such a way as to * produce valid OME-XML. The returned MetadataStore cannot be used * by an IFormatWriter, as it will not contain the required * BinData.BigEndian attributes. */ public MetadataStore getMetadataStoreForDisplay() { MetadataStore store = getMetadataStore(); if (service.isOMEXMLMetadata(store)) { service.removeBinData((OMEXMLMetadata) store); for (int i=0; i<getSeriesCount(); i++) { if (((OMEXMLMetadata) store).getTiffDataCount(i) == 0) { service.addMetadataOnly((OMEXMLMetadata) store, i); } } } return store; } /** * Returns a MetadataStore that is populated in such a way as to be * usable by an IFormatWriter. Any OME-XML generated from this * MetadataStore is <em>very unlikely</em> to be valid, as more than * likely both BinData and TiffData element will be present. */ public MetadataStore getMetadataStoreForConversion() { MetadataStore store = getMetadataStore(); int realSeries = getSeries(); for (int i=0; i<getSeriesCount(); i++) { setSeries(i); store.setPixelsBinDataBigEndian(new Boolean(!isLittleEndian()), i, 0); } setSeries(realSeries); return store; } // -- Helper methods -- private String normalizeFilename(String dir, String name) { File file = new File(dir, name); if (file.exists()) return file.getAbsolutePath(); return new Location(name).getAbsolutePath(); } private void setupService() throws FormatException { try { ServiceFactory factory = new ServiceFactory(); service = factory.getInstance(OMEXMLService.class); } catch (DependencyException de) { throw new MissingLibraryException(NO_OME_XML_MSG, de); } } // -- Helper classes -- /** Structure containing details on where to find a particular image plane. */ private class OMETiffPlane { /** Reader to use for accessing this plane. */ public IFormatReader reader; /** File containing this plane. */ public String id; /** IFD number of this plane. */ public int ifd = -1; /** Certainty flag, for dealing with unspecified NumPlanes. */ public boolean certain = false; } }
false
true
protected void initFile(String id) throws FormatException, IOException { // normalize file name super.initFile(normalizeFilename(null, id)); id = currentId; String dir = new File(id).getParent(); // parse and populate OME-XML metadata String fileName = new Location(id).getAbsoluteFile().getAbsolutePath(); RandomAccessInputStream ras = new RandomAccessInputStream(fileName); TiffParser tp = new TiffParser(ras); IFD firstIFD = tp.getFirstIFD(); ras.close(); String xml = firstIFD.getComment(); if (service == null) setupService(); OMEXMLMetadata meta; try { meta = service.createOMEXMLMetadata(xml); } catch (ServiceException se) { throw new FormatException(se); } hasSPW = meta.getPlateCount() > 0; // TODO //Hashtable originalMetadata = meta.getOriginalMetadata(); //if (originalMetadata != null) metadata = originalMetadata; LOGGER.trace(xml); if (meta.getRoot() == null) { throw new FormatException("Could not parse OME-XML from TIFF comment"); } String currentUUID = meta.getUUID(); service.convertMetadata(meta, metadataStore); // determine series count from Image and Pixels elements int seriesCount = meta.getImageCount(); core = new CoreMetadata[seriesCount]; for (int i=0; i<seriesCount; i++) { core[i] = new CoreMetadata(); } info = new OMETiffPlane[seriesCount][]; // compile list of file/UUID mappings Hashtable<String, String> files = new Hashtable<String, String>(); boolean needSearch = false; for (int i=0; i<seriesCount; i++) { int tiffDataCount = meta.getTiffDataCount(i); for (int td=0; td<tiffDataCount; td++) { String uuid = null; try { uuid = meta.getUUIDValue(i, td); } catch (NullPointerException e) { } String filename = null; if (uuid == null) { // no UUID means that TiffData element refers to this file uuid = ""; filename = id; } else { filename = meta.getUUIDFileName(i, td); if (!new Location(dir, filename).exists()) filename = null; if (filename == null) { if (uuid.equals(currentUUID) || currentUUID == null) { // UUID references this file filename = id; } else { // will need to search for this UUID filename = ""; needSearch = true; } } else filename = normalizeFilename(dir, filename); } String existing = files.get(uuid); if (existing == null) files.put(uuid, filename); else if (!existing.equals(filename)) { throw new FormatException("Inconsistent UUID filenames"); } } } // search for missing filenames if (needSearch) { Enumeration en = files.keys(); while (en.hasMoreElements()) { String uuid = (String) en.nextElement(); String filename = files.get(uuid); if (filename.equals("")) { // TODO search... // should scan only other .ome.tif files // to make this work with OME server may be a little tricky? throw new FormatException("Unmatched UUID: " + uuid); } } } // build list of used files Enumeration en = files.keys(); int numUUIDs = files.size(); HashSet fileSet = new HashSet(); // ensure no duplicate filenames for (int i=0; i<numUUIDs; i++) { String uuid = (String) en.nextElement(); String filename = files.get(uuid); fileSet.add(filename); } used = new String[fileSet.size()]; Iterator iter = fileSet.iterator(); for (int i=0; i<used.length; i++) used[i] = (String) iter.next(); // process TiffData elements Hashtable<String, IFormatReader> readers = new Hashtable<String, IFormatReader>(); for (int i=0; i<seriesCount; i++) { int s = i; LOGGER.debug("Image[{}] {", i); LOGGER.debug(" id = {}", meta.getImageID(i)); String order = meta.getPixelsDimensionOrder(i).toString(); PositiveInteger samplesPerPixel = null; if (meta.getChannelCount(i) > 0) { samplesPerPixel = meta.getChannelSamplesPerPixel(i, 0); } int samples = samplesPerPixel == null ? -1 : samplesPerPixel.getValue(); int tiffSamples = firstIFD.getSamplesPerPixel(); if (samples != tiffSamples) { LOGGER.warn("SamplesPerPixel mismatch: OME={}, TIFF={}", samples, tiffSamples); samples = tiffSamples; } int effSizeC = meta.getPixelsSizeC(i).getValue().intValue() / samples; if (effSizeC == 0) effSizeC = 1; if (effSizeC * samples != meta.getPixelsSizeC(i).getValue().intValue()) { effSizeC = meta.getPixelsSizeC(i).getValue().intValue(); } int sizeT = meta.getPixelsSizeT(i).getValue().intValue(); int sizeZ = meta.getPixelsSizeZ(i).getValue().intValue(); int num = effSizeC * sizeT * sizeZ; OMETiffPlane[] planes = new OMETiffPlane[num]; for (int no=0; no<num; no++) planes[no] = new OMETiffPlane(); int tiffDataCount = meta.getTiffDataCount(i); boolean zOneIndexed = false; boolean cOneIndexed = false; boolean tOneIndexed = false; // pre-scan TiffData indices to see if any of them are indexed from 1 for (int td=0; td<tiffDataCount; td++) { NonNegativeInteger firstC = meta.getTiffDataFirstC(i, td); NonNegativeInteger firstT = meta.getTiffDataFirstT(i, td); NonNegativeInteger firstZ = meta.getTiffDataFirstZ(i, td); int c = firstC == null ? 0 : firstC.getValue(); int t = firstT == null ? 0 : firstT.getValue(); int z = firstZ == null ? 0 : firstZ.getValue(); if (c >= effSizeC) cOneIndexed = true; if (z >= sizeZ) zOneIndexed = true; if (t >= sizeT) tOneIndexed = true; } for (int td=0; td<tiffDataCount; td++) { LOGGER.debug(" TiffData[{}] {", td); // extract TiffData parameters String filename = null; String uuid = null; try { filename = meta.getUUIDFileName(i, td); } catch (NullPointerException e) { LOGGER.debug("Ignoring null UUID object when retrieving filename."); } try { uuid = meta.getUUIDValue(i, td); } catch (NullPointerException e) { LOGGER.debug("Ignoring null UUID object when retrieving value."); } NonNegativeInteger tdIFD = meta.getTiffDataIFD(i, td); int ifd = tdIFD == null ? 0 : tdIFD.getValue(); NonNegativeInteger numPlanes = meta.getTiffDataPlaneCount(i, td); NonNegativeInteger firstC = meta.getTiffDataFirstC(i, td); NonNegativeInteger firstT = meta.getTiffDataFirstT(i, td); NonNegativeInteger firstZ = meta.getTiffDataFirstZ(i, td); int c = firstC == null ? 0 : firstC.getValue(); int t = firstT == null ? 0 : firstT.getValue(); int z = firstZ == null ? 0 : firstZ.getValue(); // NB: some writers index FirstC, FirstZ and FirstT from 1 if (cOneIndexed) c--; if (zOneIndexed) z--; if (tOneIndexed) t--; int index = FormatTools.getIndex(order, sizeZ, effSizeC, sizeT, num, z, c, t); int count = numPlanes == null ? 1 : numPlanes.getValue(); if (count == 0) { core[s] = null; break; } // get reader object for this filename if (filename == null) { if (uuid == null) filename = id; else filename = files.get(uuid); } else filename = normalizeFilename(dir, filename); IFormatReader r = readers.get(filename); if (r == null) { r = new MinimalTiffReader(); readers.put(filename, r); } Location file = new Location(filename); if (!file.exists()) { // if this is an absolute file name, try using a relative name // old versions of OMETiffWriter wrote an absolute path to // UUID.FileName, which causes problems if the file is moved to // a different directory filename = filename.substring(filename.lastIndexOf(File.separator) + 1); filename = dir + File.separator + filename; if (!new Location(filename).exists()) { filename = currentId; } } // populate plane index -> IFD mapping for (int q=0; q<count; q++) { int no = index + q; planes[no].reader = r; planes[no].id = filename; planes[no].ifd = ifd + q; planes[no].certain = true; LOGGER.debug(" Plane[{}]: file={}, IFD={}", new Object[] {no, planes[no].id, planes[no].ifd}); } if (numPlanes == null) { // unknown number of planes; fill down for (int no=index+1; no<num; no++) { if (planes[no].certain) break; planes[no].reader = r; planes[no].id = filename; planes[no].ifd = planes[no - 1].ifd + 1; LOGGER.debug(" Plane[{}]: FILLED", no); } } else { // known number of planes; clear anything subsequently filled for (int no=index+count; no<num; no++) { if (planes[no].certain) break; planes[no].reader = null; planes[no].id = null; planes[no].ifd = -1; LOGGER.debug(" Plane[{}]: CLEARED", no); } } LOGGER.debug(" }"); } if (core[s] == null) continue; // verify that all planes are available LOGGER.debug(" --------------------------------"); for (int no=0; no<num; no++) { LOGGER.debug(" Plane[{}]: file={}, IFD={}", new Object[] {no, planes[no].id, planes[no].ifd}); if (planes[no].reader == null) { LOGGER.warn("Image ID '{}': missing plane #{}. " + "Using TiffReader to determine the number of planes.", meta.getImageID(i), no); TiffReader r = new TiffReader(); r.setId(currentId); planes = new OMETiffPlane[r.getImageCount()]; for (int plane=0; plane<planes.length; plane++) { planes[plane] = new OMETiffPlane(); planes[plane].id = currentId; planes[plane].reader = r; planes[plane].ifd = plane; } num = planes.length; r.close(); } } LOGGER.debug(" }"); // populate core metadata info[s] = planes; try { core[s].sizeX = meta.getPixelsSizeX(i).getValue().intValue(); int tiffWidth = (int) firstIFD.getImageWidth(); if (core[s].sizeX != tiffWidth) { LOGGER.warn("SizeX mismatch: OME={}, TIFF={}", core[s].sizeX, tiffWidth); } core[s].sizeY = meta.getPixelsSizeY(i).getValue().intValue(); int tiffHeight = (int) firstIFD.getImageLength(); if (core[s].sizeY != tiffHeight) { LOGGER.warn("SizeY mismatch: OME={}, TIFF={}", core[s].sizeY, tiffHeight); } core[s].sizeZ = meta.getPixelsSizeZ(i).getValue().intValue(); core[s].sizeC = meta.getPixelsSizeC(i).getValue().intValue(); core[s].sizeT = meta.getPixelsSizeT(i).getValue().intValue(); core[s].pixelType = FormatTools.pixelTypeFromString( meta.getPixelsType(i).toString()); int tiffPixelType = firstIFD.getPixelType(); if (core[s].pixelType != tiffPixelType) { LOGGER.warn("PixelType mismatch: OME={}, TIFF={}", core[s].pixelType, tiffPixelType); core[s].pixelType = tiffPixelType; } core[s].imageCount = num; core[s].dimensionOrder = meta.getPixelsDimensionOrder(i).toString(); // hackish workaround for files exported by OMERO that have an // incorrect dimension order if (meta.getChannelCount(i) > 0 && meta.getChannelName(i, 0) == null && meta.getTiffDataCount(i) > 0 && meta.getUUIDFileName(i, 0).indexOf("__omero_export") != -1) { int zIndex = core[s].dimensionOrder.indexOf("Z"); int tIndex = core[s].dimensionOrder.indexOf("T"); core[s].dimensionOrder = zIndex < tIndex ? "XYCZT" : "XYCTZ"; } core[s].orderCertain = true; PhotoInterp photo = firstIFD.getPhotometricInterpretation(); core[s].rgb = samples > 1 || photo == PhotoInterp.RGB; if ((samples != core[s].sizeC && (samples % core[s].sizeC) != 0 && (core[s].sizeC % samples) != 0) || core[s].sizeC == 1) { core[s].sizeC *= samples; } if (core[s].sizeZ * core[s].sizeT * core[s].sizeC > core[s].imageCount && !core[s].rgb) { if (core[s].sizeZ == core[s].imageCount) { core[s].sizeT = 1; core[s].sizeC = 1; } else if (core[s].sizeT == core[s].imageCount) { core[s].sizeZ = 1; core[s].sizeC = 1; } else if (core[s].sizeC == core[s].imageCount) { core[s].sizeT = 1; core[s].sizeZ = 1; } } if (meta.getPixelsBinDataCount(i) > 1) { LOGGER.warn("OME-TIFF Pixels element contains BinData elements! " + "Ignoring."); } core[s].littleEndian = firstIFD.isLittleEndian(); core[s].interleaved = false; core[s].indexed = photo == PhotoInterp.RGB_PALETTE && firstIFD.getIFDValue(IFD.COLOR_MAP) != null; if (core[s].indexed) { core[s].rgb = false; } core[s].falseColor = false; core[s].metadataComplete = true; } catch (NullPointerException exc) { throw new FormatException("Incomplete Pixels metadata", exc); } } // remove null CoreMetadata entries Vector<CoreMetadata> series = new Vector<CoreMetadata>(); Vector<OMETiffPlane[]> planeInfo = new Vector<OMETiffPlane[]>(); for (int i=0; i<core.length; i++) { if (core[i] != null) { series.add(core[i]); planeInfo.add(info[i]); } } core = series.toArray(new CoreMetadata[series.size()]); info = planeInfo.toArray(new OMETiffPlane[0][0]); MetadataTools.populatePixels(metadataStore, this, false, false); metadataStore = getMetadataStoreForDisplay(); }
protected void initFile(String id) throws FormatException, IOException { // normalize file name super.initFile(normalizeFilename(null, id)); id = currentId; String dir = new File(id).getParent(); // parse and populate OME-XML metadata String fileName = new Location(id).getAbsoluteFile().getAbsolutePath(); RandomAccessInputStream ras = new RandomAccessInputStream(fileName); TiffParser tp = new TiffParser(ras); IFD firstIFD = tp.getFirstIFD(); ras.close(); String xml = firstIFD.getComment(); if (service == null) setupService(); OMEXMLMetadata meta; try { meta = service.createOMEXMLMetadata(xml); } catch (ServiceException se) { throw new FormatException(se); } hasSPW = meta.getPlateCount() > 0; // TODO //Hashtable originalMetadata = meta.getOriginalMetadata(); //if (originalMetadata != null) metadata = originalMetadata; LOGGER.trace(xml); if (meta.getRoot() == null) { throw new FormatException("Could not parse OME-XML from TIFF comment"); } String currentUUID = meta.getUUID(); service.convertMetadata(meta, metadataStore); // determine series count from Image and Pixels elements int seriesCount = meta.getImageCount(); core = new CoreMetadata[seriesCount]; for (int i=0; i<seriesCount; i++) { core[i] = new CoreMetadata(); } info = new OMETiffPlane[seriesCount][]; // compile list of file/UUID mappings Hashtable<String, String> files = new Hashtable<String, String>(); boolean needSearch = false; for (int i=0; i<seriesCount; i++) { int tiffDataCount = meta.getTiffDataCount(i); for (int td=0; td<tiffDataCount; td++) { String uuid = null; try { uuid = meta.getUUIDValue(i, td); } catch (NullPointerException e) { } String filename = null; if (uuid == null) { // no UUID means that TiffData element refers to this file uuid = ""; filename = id; } else { filename = meta.getUUIDFileName(i, td); if (!new Location(dir, filename).exists()) filename = null; if (filename == null) { if (uuid.equals(currentUUID) || currentUUID == null) { // UUID references this file filename = id; } else { // will need to search for this UUID filename = ""; needSearch = true; } } else filename = normalizeFilename(dir, filename); } String existing = files.get(uuid); if (existing == null) files.put(uuid, filename); else if (!existing.equals(filename)) { throw new FormatException("Inconsistent UUID filenames"); } } } // search for missing filenames if (needSearch) { Enumeration en = files.keys(); while (en.hasMoreElements()) { String uuid = (String) en.nextElement(); String filename = files.get(uuid); if (filename.equals("")) { // TODO search... // should scan only other .ome.tif files // to make this work with OME server may be a little tricky? throw new FormatException("Unmatched UUID: " + uuid); } } } // build list of used files Enumeration en = files.keys(); int numUUIDs = files.size(); HashSet fileSet = new HashSet(); // ensure no duplicate filenames for (int i=0; i<numUUIDs; i++) { String uuid = (String) en.nextElement(); String filename = files.get(uuid); fileSet.add(filename); } used = new String[fileSet.size()]; Iterator iter = fileSet.iterator(); for (int i=0; i<used.length; i++) used[i] = (String) iter.next(); // process TiffData elements Hashtable<String, IFormatReader> readers = new Hashtable<String, IFormatReader>(); for (int i=0; i<seriesCount; i++) { int s = i; LOGGER.debug("Image[{}] {", i); LOGGER.debug(" id = {}", meta.getImageID(i)); String order = meta.getPixelsDimensionOrder(i).toString(); PositiveInteger samplesPerPixel = null; if (meta.getChannelCount(i) > 0) { samplesPerPixel = meta.getChannelSamplesPerPixel(i, 0); } int samples = samplesPerPixel == null ? -1 : samplesPerPixel.getValue(); int tiffSamples = firstIFD.getSamplesPerPixel(); if (samples != tiffSamples) { LOGGER.warn("SamplesPerPixel mismatch: OME={}, TIFF={}", samples, tiffSamples); samples = tiffSamples; } int effSizeC = meta.getPixelsSizeC(i).getValue().intValue() / samples; if (effSizeC == 0) effSizeC = 1; if (effSizeC * samples != meta.getPixelsSizeC(i).getValue().intValue()) { effSizeC = meta.getPixelsSizeC(i).getValue().intValue(); } int sizeT = meta.getPixelsSizeT(i).getValue().intValue(); int sizeZ = meta.getPixelsSizeZ(i).getValue().intValue(); int num = effSizeC * sizeT * sizeZ; OMETiffPlane[] planes = new OMETiffPlane[num]; for (int no=0; no<num; no++) planes[no] = new OMETiffPlane(); int tiffDataCount = meta.getTiffDataCount(i); boolean zOneIndexed = false; boolean cOneIndexed = false; boolean tOneIndexed = false; // pre-scan TiffData indices to see if any of them are indexed from 1 for (int td=0; td<tiffDataCount; td++) { NonNegativeInteger firstC = meta.getTiffDataFirstC(i, td); NonNegativeInteger firstT = meta.getTiffDataFirstT(i, td); NonNegativeInteger firstZ = meta.getTiffDataFirstZ(i, td); int c = firstC == null ? 0 : firstC.getValue(); int t = firstT == null ? 0 : firstT.getValue(); int z = firstZ == null ? 0 : firstZ.getValue(); if (c >= effSizeC) cOneIndexed = true; if (z >= sizeZ) zOneIndexed = true; if (t >= sizeT) tOneIndexed = true; } for (int td=0; td<tiffDataCount; td++) { LOGGER.debug(" TiffData[{}] {", td); // extract TiffData parameters String filename = null; String uuid = null; try { filename = meta.getUUIDFileName(i, td); } catch (NullPointerException e) { LOGGER.debug("Ignoring null UUID object when retrieving filename."); } try { uuid = meta.getUUIDValue(i, td); } catch (NullPointerException e) { LOGGER.debug("Ignoring null UUID object when retrieving value."); } NonNegativeInteger tdIFD = meta.getTiffDataIFD(i, td); int ifd = tdIFD == null ? 0 : tdIFD.getValue(); NonNegativeInteger numPlanes = meta.getTiffDataPlaneCount(i, td); NonNegativeInteger firstC = meta.getTiffDataFirstC(i, td); NonNegativeInteger firstT = meta.getTiffDataFirstT(i, td); NonNegativeInteger firstZ = meta.getTiffDataFirstZ(i, td); int c = firstC == null ? 0 : firstC.getValue(); int t = firstT == null ? 0 : firstT.getValue(); int z = firstZ == null ? 0 : firstZ.getValue(); // NB: some writers index FirstC, FirstZ and FirstT from 1 if (cOneIndexed) c--; if (zOneIndexed) z--; if (tOneIndexed) t--; int index = FormatTools.getIndex(order, sizeZ, effSizeC, sizeT, num, z, c, t); int count = numPlanes == null ? 1 : numPlanes.getValue(); if (count == 0) { core[s] = null; break; } // get reader object for this filename if (filename == null) { if (uuid == null) filename = id; else filename = files.get(uuid); } else filename = normalizeFilename(dir, filename); IFormatReader r = readers.get(filename); if (r == null) { r = new MinimalTiffReader(); readers.put(filename, r); } Location file = new Location(filename); if (!file.exists()) { // if this is an absolute file name, try using a relative name // old versions of OMETiffWriter wrote an absolute path to // UUID.FileName, which causes problems if the file is moved to // a different directory filename = filename.substring(filename.lastIndexOf(File.separator) + 1); filename = dir + File.separator + filename; if (!new Location(filename).exists()) { filename = currentId; } } // populate plane index -> IFD mapping for (int q=0; q<count; q++) { int no = index + q; planes[no].reader = r; planes[no].id = filename; planes[no].ifd = ifd + q; planes[no].certain = true; LOGGER.debug(" Plane[{}]: file={}, IFD={}", new Object[] {no, planes[no].id, planes[no].ifd}); } if (numPlanes == null) { // unknown number of planes; fill down for (int no=index+1; no<num; no++) { if (planes[no].certain) break; planes[no].reader = r; planes[no].id = filename; planes[no].ifd = planes[no - 1].ifd + 1; LOGGER.debug(" Plane[{}]: FILLED", no); } } else { // known number of planes; clear anything subsequently filled for (int no=index+count; no<num; no++) { if (planes[no].certain) break; planes[no].reader = null; planes[no].id = null; planes[no].ifd = -1; LOGGER.debug(" Plane[{}]: CLEARED", no); } } LOGGER.debug(" }"); } if (core[s] == null) continue; // verify that all planes are available LOGGER.debug(" --------------------------------"); for (int no=0; no<num; no++) { LOGGER.debug(" Plane[{}]: file={}, IFD={}", new Object[] {no, planes[no].id, planes[no].ifd}); if (planes[no].reader == null) { LOGGER.warn("Image ID '{}': missing plane #{}. " + "Using TiffReader to determine the number of planes.", meta.getImageID(i), no); TiffReader r = new TiffReader(); r.setId(currentId); planes = new OMETiffPlane[r.getImageCount()]; for (int plane=0; plane<planes.length; plane++) { planes[plane] = new OMETiffPlane(); planes[plane].id = currentId; planes[plane].reader = r; planes[plane].ifd = plane; } num = planes.length; r.close(); } } LOGGER.debug(" }"); // populate core metadata info[s] = planes; try { core[s].sizeX = meta.getPixelsSizeX(i).getValue().intValue(); int tiffWidth = (int) firstIFD.getImageWidth(); if (core[s].sizeX != tiffWidth) { LOGGER.warn("SizeX mismatch: OME={}, TIFF={}", core[s].sizeX, tiffWidth); } core[s].sizeY = meta.getPixelsSizeY(i).getValue().intValue(); int tiffHeight = (int) firstIFD.getImageLength(); if (core[s].sizeY != tiffHeight) { LOGGER.warn("SizeY mismatch: OME={}, TIFF={}", core[s].sizeY, tiffHeight); } core[s].sizeZ = meta.getPixelsSizeZ(i).getValue().intValue(); core[s].sizeC = meta.getPixelsSizeC(i).getValue().intValue(); core[s].sizeT = meta.getPixelsSizeT(i).getValue().intValue(); core[s].pixelType = FormatTools.pixelTypeFromString( meta.getPixelsType(i).toString()); int tiffPixelType = firstIFD.getPixelType(); if (core[s].pixelType != tiffPixelType) { LOGGER.warn("PixelType mismatch: OME={}, TIFF={}", core[s].pixelType, tiffPixelType); core[s].pixelType = tiffPixelType; } core[s].imageCount = num; core[s].dimensionOrder = meta.getPixelsDimensionOrder(i).toString(); // hackish workaround for files exported by OMERO that have an // incorrect dimension order String uuidFileName = ""; try { uuidFileName = meta.getUUIDFileName(i, 0); } catch (NullPointerException e) { } if (meta.getChannelCount(i) > 0 && meta.getChannelName(i, 0) == null && meta.getTiffDataCount(i) > 0 && uuidFileName.indexOf("__omero_export") != -1) { int zIndex = core[s].dimensionOrder.indexOf("Z"); int tIndex = core[s].dimensionOrder.indexOf("T"); core[s].dimensionOrder = zIndex < tIndex ? "XYCZT" : "XYCTZ"; } core[s].orderCertain = true; PhotoInterp photo = firstIFD.getPhotometricInterpretation(); core[s].rgb = samples > 1 || photo == PhotoInterp.RGB; if ((samples != core[s].sizeC && (samples % core[s].sizeC) != 0 && (core[s].sizeC % samples) != 0) || core[s].sizeC == 1) { core[s].sizeC *= samples; } if (core[s].sizeZ * core[s].sizeT * core[s].sizeC > core[s].imageCount && !core[s].rgb) { if (core[s].sizeZ == core[s].imageCount) { core[s].sizeT = 1; core[s].sizeC = 1; } else if (core[s].sizeT == core[s].imageCount) { core[s].sizeZ = 1; core[s].sizeC = 1; } else if (core[s].sizeC == core[s].imageCount) { core[s].sizeT = 1; core[s].sizeZ = 1; } } if (meta.getPixelsBinDataCount(i) > 1) { LOGGER.warn("OME-TIFF Pixels element contains BinData elements! " + "Ignoring."); } core[s].littleEndian = firstIFD.isLittleEndian(); core[s].interleaved = false; core[s].indexed = photo == PhotoInterp.RGB_PALETTE && firstIFD.getIFDValue(IFD.COLOR_MAP) != null; if (core[s].indexed) { core[s].rgb = false; } core[s].falseColor = false; core[s].metadataComplete = true; } catch (NullPointerException exc) { throw new FormatException("Incomplete Pixels metadata", exc); } } // remove null CoreMetadata entries Vector<CoreMetadata> series = new Vector<CoreMetadata>(); Vector<OMETiffPlane[]> planeInfo = new Vector<OMETiffPlane[]>(); for (int i=0; i<core.length; i++) { if (core[i] != null) { series.add(core[i]); planeInfo.add(info[i]); } } core = series.toArray(new CoreMetadata[series.size()]); info = planeInfo.toArray(new OMETiffPlane[0][0]); MetadataTools.populatePixels(metadataStore, this, false, false); metadataStore = getMetadataStoreForDisplay(); }
diff --git a/server/src/main/java/ru/yandex/hackaton/server/geocoder/MosOpenGeocoder.java b/server/src/main/java/ru/yandex/hackaton/server/geocoder/MosOpenGeocoder.java index 10d5dd8..1e097c9 100644 --- a/server/src/main/java/ru/yandex/hackaton/server/geocoder/MosOpenGeocoder.java +++ b/server/src/main/java/ru/yandex/hackaton/server/geocoder/MosOpenGeocoder.java @@ -1,54 +1,54 @@ package ru.yandex.hackaton.server.geocoder; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import javax.inject.Singleton; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import ru.yandex.hackaton.server.geocoder.data.DistrictInfo; import ru.yandex.hackaton.server.geocoder.geo.Line; import ru.yandex.hackaton.server.geocoder.geo.Point; /** * @author Sergey Polovko */ @Singleton public class MosOpenGeocoder { private final DataHost<Line> dataHost = new DataHost<Line>("mosopen.ru") { @Override protected Line parseResponse(InputStream content, Charset charset) throws IOException { return parseDistrictInfo(content, charset); } @Override protected Line emptyResponse(Charset charset) { return null; } }; public DistrictInfo geocode(String districtName) { System.out.println(districtName); String translitName = TransLiterator.translitRustoEng(districtName); Line borders = dataHost.get( "/public/ymapsml.php", "p", String.format("region/%s/map_xml", translitName)); return new DistrictInfo(districtName, borders); } private Line parseDistrictInfo(InputStream xml, Charset charset) throws IOException { Document document = Jsoup.parse(xml, charset.name(), ""); List<Point> points = new ArrayList<>(); for (Element pos : document.getElementsByTag("gml:pos")) { - points.add(Point.parseWkt(pos.text())); + points.add(Point.parseGml(pos.text())); } Line borders = new Line(points); return borders; } }
true
true
private Line parseDistrictInfo(InputStream xml, Charset charset) throws IOException { Document document = Jsoup.parse(xml, charset.name(), ""); List<Point> points = new ArrayList<>(); for (Element pos : document.getElementsByTag("gml:pos")) { points.add(Point.parseWkt(pos.text())); } Line borders = new Line(points); return borders; }
private Line parseDistrictInfo(InputStream xml, Charset charset) throws IOException { Document document = Jsoup.parse(xml, charset.name(), ""); List<Point> points = new ArrayList<>(); for (Element pos : document.getElementsByTag("gml:pos")) { points.add(Point.parseGml(pos.text())); } Line borders = new Line(points); return borders; }
diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/api/Type.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/api/Type.java index facab8417c..f032dadeb1 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/api/Type.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/api/Type.java @@ -1,171 +1,171 @@ package org.apache.jackrabbit.oak.api; import java.math.BigDecimal; import javax.jcr.PropertyType; import com.google.common.base.Objects; /** * Instances of this class map Java types to {@link PropertyType property types}. * Passing an instance of this class to {@link PropertyState#getValue(Type)} determines * the return type of that method. * @param <T> */ public final class Type<T> { /** Map {@code String} to {@link PropertyType#STRING} */ public static final Type<String> STRING = create(PropertyType.STRING, false); /** Map {@code Blob} to {@link PropertyType#BINARY} */ public static final Type<Blob> BINARY = create(PropertyType.BINARY, false); /** Map {@code Long} to {@link PropertyType#LONG} */ public static final Type<Long> LONG = create(PropertyType.LONG, false); /** Map {@code Double} to {@link PropertyType#DOUBLE} */ public static final Type<Double> DOUBLE = create(PropertyType.DOUBLE, false); /** Map {@code String} to {@link PropertyType#DATE} */ public static final Type<String> DATE = create(PropertyType.DATE, false); /** Map {@code Boolean} to {@link PropertyType#BOOLEAN} */ public static final Type<Boolean> BOOLEAN = create(PropertyType.BOOLEAN, false); /** Map {@code String} to {@link PropertyType#STRING} */ public static final Type<String> NAME = create(PropertyType.NAME, false); /** Map {@code String} to {@link PropertyType#PATH} */ public static final Type<String> PATH = create(PropertyType.PATH, false); /** Map {@code String} to {@link PropertyType#REFERENCE} */ public static final Type<String> REFERENCE = create(PropertyType.REFERENCE, false); /** Map {@code String} to {@link PropertyType#WEAKREFERENCE} */ public static final Type<String> WEAKREFERENCE = create(PropertyType.WEAKREFERENCE, false); /** Map {@code String} to {@link PropertyType#URI} */ public static final Type<String> URI = create(PropertyType.URI, false); /** Map {@code BigDecimal} to {@link PropertyType#DECIMAL} */ public static final Type<BigDecimal> DECIMAL = create(PropertyType.DECIMAL, false); /** Map {@code Iterable<String>} to array of {@link PropertyType#STRING} */ public static final Type<Iterable<String>> STRINGS = create(PropertyType.STRING, true); /** Map {@code Iterable<Blob} to array of {@link PropertyType#BINARY} */ public static final Type<Iterable<Blob>> BINARIES = create(PropertyType.BINARY, true); /** Map {@code Iterable<Long>} to array of {@link PropertyType#LONG} */ public static final Type<Iterable<Long>> LONGS = create(PropertyType.LONG, true); /** Map {@code Iterable<Double>} to array of {@link PropertyType#DOUBLE} */ public static final Type<Iterable<Double>> DOUBLES = create(PropertyType.DOUBLE, true); /** Map {@code Iterable<String>} to array of {@link PropertyType#DATE} */ public static final Type<Iterable<String>> DATES = create(PropertyType.DATE, true); /** Map {@code Iterable<Boolean>} to array of {@link PropertyType#BOOLEAN} */ public static final Type<Iterable<Boolean>> BOOLEANS = create(PropertyType.BOOLEAN, true); /** Map {@code Iterable<String>} to array of {@link PropertyType#NAME} */ public static final Type<Iterable<String>> NAMES = create(PropertyType.NAME, true); /** Map {@code Iterable<String>} to array of {@link PropertyType#PATH} */ public static final Type<Iterable<String>> PATHS = create(PropertyType.PATH, true); /** Map {@code Iterable<String>} to array of {@link PropertyType#REFERENCE} */ public static final Type<Iterable<String>> REFERENCES = create(PropertyType.REFERENCE, true); /** Map {@code Iterable<String>} to array of {@link PropertyType#WEAKREFERENCE} */ public static final Type<Iterable<String>> WEAKREFERENCES = create(PropertyType.WEAKREFERENCE, true); /** Map {@code Iterable<String>} to array of {@link PropertyType#URI} */ public static final Type<Iterable<String>> URIS = create(PropertyType.URI, true); /** Map {@code Iterable<BigDecimal>} to array of {@link PropertyType#DECIMAL} */ public static final Type<Iterable<BigDecimal>> DECIMALS = create(PropertyType.DECIMAL, true); private final int tag; private final boolean array; private Type(int tag, boolean array){ this.tag = tag; this.array = array; } private static <T> Type<T> create(int tag, boolean array) { return new Type<T>(tag, array); } /** * Corresponding type tag as defined in {@link PropertyType}. * @return type tag */ public int tag() { return tag; } /** * Determine whether this is an array type * @return {@code true} if and only if this is an array type */ public boolean isArray() { return array; } /** * Corresponding {@code Type} for a given type tag and array flag. * @param tag type tag as defined in {@link PropertyType}. * @param array whether this is an array or not * @return {@code Type} instance * @throws IllegalArgumentException if tag is not valid as per definition in {@link PropertyType}. */ public static Type<?> fromTag(int tag, boolean array) { switch (tag) { case PropertyType.STRING: return array ? STRINGS : STRING; - case PropertyType.BINARY: return array ? BINARY : BINARIES; - case PropertyType.LONG: return array ? LONG : LONGS; - case PropertyType.DOUBLE: return array ? DOUBLE : DOUBLES; - case PropertyType.DATE: return array ? DATE: DATES; - case PropertyType.BOOLEAN: return array ? BOOLEAN: BOOLEANS; - case PropertyType.NAME: return array ? NAME : NAMES; - case PropertyType.PATH: return array ? PATH: PATHS; - case PropertyType.REFERENCE: return array ? REFERENCE : REFERENCES; - case PropertyType.WEAKREFERENCE: return array ? WEAKREFERENCE : WEAKREFERENCES; - case PropertyType.URI: return array ? URI: URIS; - case PropertyType.DECIMAL: return array ? DECIMAL : DECIMALS; + case PropertyType.BINARY: return array ? BINARIES : BINARY; + case PropertyType.LONG: return array ? LONGS : LONG; + case PropertyType.DOUBLE: return array ? DOUBLES : DOUBLE; + case PropertyType.DATE: return array ? DATES: DATE; + case PropertyType.BOOLEAN: return array ? BOOLEANS: BOOLEAN; + case PropertyType.NAME: return array ? NAMES : NAME; + case PropertyType.PATH: return array ? PATHS: PATH; + case PropertyType.REFERENCE: return array ? REFERENCES : REFERENCE; + case PropertyType.WEAKREFERENCE: return array ? WEAKREFERENCES : WEAKREFERENCE; + case PropertyType.URI: return array ? URIS: URI; + case PropertyType.DECIMAL: return array ? DECIMALS : DECIMAL; default: throw new IllegalArgumentException("Invalid type tag: " + tag); } } /** * Determine the base type of array types * @return base type * @throws IllegalStateException if {@code isArray} is false. */ public Type<?> getBaseType() { if (!isArray()) { throw new IllegalStateException("Not an array: " + this); } return fromTag(tag, false); } @Override public String toString() { return isArray() ? "[]" + PropertyType.nameFromValue(getBaseType().tag) : PropertyType.nameFromValue(tag); } @Override public int hashCode() { return Objects.hashCode(tag, array); } @Override public boolean equals(Object other) { return this == other; } }
true
true
public static Type<?> fromTag(int tag, boolean array) { switch (tag) { case PropertyType.STRING: return array ? STRINGS : STRING; case PropertyType.BINARY: return array ? BINARY : BINARIES; case PropertyType.LONG: return array ? LONG : LONGS; case PropertyType.DOUBLE: return array ? DOUBLE : DOUBLES; case PropertyType.DATE: return array ? DATE: DATES; case PropertyType.BOOLEAN: return array ? BOOLEAN: BOOLEANS; case PropertyType.NAME: return array ? NAME : NAMES; case PropertyType.PATH: return array ? PATH: PATHS; case PropertyType.REFERENCE: return array ? REFERENCE : REFERENCES; case PropertyType.WEAKREFERENCE: return array ? WEAKREFERENCE : WEAKREFERENCES; case PropertyType.URI: return array ? URI: URIS; case PropertyType.DECIMAL: return array ? DECIMAL : DECIMALS; default: throw new IllegalArgumentException("Invalid type tag: " + tag); } }
public static Type<?> fromTag(int tag, boolean array) { switch (tag) { case PropertyType.STRING: return array ? STRINGS : STRING; case PropertyType.BINARY: return array ? BINARIES : BINARY; case PropertyType.LONG: return array ? LONGS : LONG; case PropertyType.DOUBLE: return array ? DOUBLES : DOUBLE; case PropertyType.DATE: return array ? DATES: DATE; case PropertyType.BOOLEAN: return array ? BOOLEANS: BOOLEAN; case PropertyType.NAME: return array ? NAMES : NAME; case PropertyType.PATH: return array ? PATHS: PATH; case PropertyType.REFERENCE: return array ? REFERENCES : REFERENCE; case PropertyType.WEAKREFERENCE: return array ? WEAKREFERENCES : WEAKREFERENCE; case PropertyType.URI: return array ? URIS: URI; case PropertyType.DECIMAL: return array ? DECIMALS : DECIMAL; default: throw new IllegalArgumentException("Invalid type tag: " + tag); } }
diff --git a/target_explorer/plugins/org.eclipse.tcf.te.ui/src/org/eclipse/tcf/te/ui/async/UICallbackInvocationDelegate.java b/target_explorer/plugins/org.eclipse.tcf.te.ui/src/org/eclipse/tcf/te/ui/async/UICallbackInvocationDelegate.java index 0703d0455..662fc33a5 100644 --- a/target_explorer/plugins/org.eclipse.tcf.te.ui/src/org/eclipse/tcf/te/ui/async/UICallbackInvocationDelegate.java +++ b/target_explorer/plugins/org.eclipse.tcf.te.ui/src/org/eclipse/tcf/te/ui/async/UICallbackInvocationDelegate.java @@ -1,33 +1,38 @@ /******************************************************************************* * Copyright (c) 2012 Wind River Systems, Inc. and others. 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 * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ package org.eclipse.tcf.te.ui.async; import org.eclipse.core.runtime.Assert; import org.eclipse.tcf.te.core.async.AsyncCallbackCollector; import org.eclipse.ui.PlatformUI; /** * Asynchronous callback collector callback invocation delegate implementation. * <p> * The delegate invokes callbacks within the UI thread. */ public class UICallbackInvocationDelegate implements AsyncCallbackCollector.ICallbackInvocationDelegate { /* (non-Javadoc) * @see org.eclipse.tcf.te.core.async.AsyncCallbackCollector.ICallbackInvocationDelegate#invoke(java.lang.Runnable) */ @Override public void invoke(Runnable runnable) { Assert.isNotNull(runnable); if (PlatformUI.getWorkbench() != null && PlatformUI.getWorkbench().getDisplay() != null) { - PlatformUI.getWorkbench().getDisplay().asyncExec(runnable); + try { + PlatformUI.getWorkbench().getDisplay().asyncExec(runnable); + } + catch (Exception e) { + // if display is disposed, silently ignore. + } } } }
true
true
public void invoke(Runnable runnable) { Assert.isNotNull(runnable); if (PlatformUI.getWorkbench() != null && PlatformUI.getWorkbench().getDisplay() != null) { PlatformUI.getWorkbench().getDisplay().asyncExec(runnable); } }
public void invoke(Runnable runnable) { Assert.isNotNull(runnable); if (PlatformUI.getWorkbench() != null && PlatformUI.getWorkbench().getDisplay() != null) { try { PlatformUI.getWorkbench().getDisplay().asyncExec(runnable); } catch (Exception e) { // if display is disposed, silently ignore. } } }
diff --git a/cst/plugins/eu.esdihumboldt.cst/src/eu/esdihumboldt/cst/extension/hooks/HooksUtil.java b/cst/plugins/eu.esdihumboldt.cst/src/eu/esdihumboldt/cst/extension/hooks/HooksUtil.java index 5d77e27b7..32116bce8 100644 --- a/cst/plugins/eu.esdihumboldt.cst/src/eu/esdihumboldt/cst/extension/hooks/HooksUtil.java +++ b/cst/plugins/eu.esdihumboldt.cst/src/eu/esdihumboldt/cst/extension/hooks/HooksUtil.java @@ -1,61 +1,65 @@ /* * Copyright (c) 2012 Data Harmonisation Panel * * All rights reserved. This program and the accompanying materials are made * available 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. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution. If not, see <http://www.gnu.org/licenses/>. * * Contributors: * HUMBOLDT EU Integrated Project #030962 * Data Harmonisation Panel <http://www.dhpanel.eu> */ package eu.esdihumboldt.cst.extension.hooks; import de.cs3d.util.logging.ALogger; import de.cs3d.util.logging.ALoggerFactory; import eu.esdihumboldt.cst.extension.hooks.TransformationTreeHook.TreeState; import eu.esdihumboldt.hale.common.align.model.transformation.tree.TransformationTree; import eu.esdihumboldt.hale.common.instance.model.MutableInstance; /** * Hooks utility methods. * * @author Simon Templer */ public class HooksUtil { private static final ALogger log = ALoggerFactory.getLogger(HooksUtil.class); /** * Execute transformation tree hooks according to the given state. * * @param hooks the hooks, may be <code>null</code> * @param state the tree state * @param tree the transformation tree * @param target the target instance */ public static void executeTreeHooks(TransformationTreeHooks hooks, TreeState state, TransformationTree tree, MutableInstance target) { if (hooks != null) { - for (TransformationTreeHook hook : hooks.getActiveObjects()) { - TransformationTreeHookFactory def = hooks.getDefinition(hook); + try { + for (TransformationTreeHook hook : hooks.getActiveObjects()) { + TransformationTreeHookFactory def = hooks.getDefinition(hook); - if (state == def.getTreeState()) { - try { - hook.processTransformationTree(tree, state, target); - } catch (Exception e) { - log.error( - "Error processing transformation tree hook " + def.getDisplayName(), - e); + if (state == def.getTreeState()) { + try { + hook.processTransformationTree(tree, state, target); + } catch (Exception e) { + log.error( + "Error processing transformation tree hook " + + def.getDisplayName(), e); + } } } + } catch (Exception e) { + log.error("Error trying to execute transformation tree hooks", e); } } } }
false
true
public static void executeTreeHooks(TransformationTreeHooks hooks, TreeState state, TransformationTree tree, MutableInstance target) { if (hooks != null) { for (TransformationTreeHook hook : hooks.getActiveObjects()) { TransformationTreeHookFactory def = hooks.getDefinition(hook); if (state == def.getTreeState()) { try { hook.processTransformationTree(tree, state, target); } catch (Exception e) { log.error( "Error processing transformation tree hook " + def.getDisplayName(), e); } } } } }
public static void executeTreeHooks(TransformationTreeHooks hooks, TreeState state, TransformationTree tree, MutableInstance target) { if (hooks != null) { try { for (TransformationTreeHook hook : hooks.getActiveObjects()) { TransformationTreeHookFactory def = hooks.getDefinition(hook); if (state == def.getTreeState()) { try { hook.processTransformationTree(tree, state, target); } catch (Exception e) { log.error( "Error processing transformation tree hook " + def.getDisplayName(), e); } } } } catch (Exception e) { log.error("Error trying to execute transformation tree hooks", e); } } }
diff --git a/javasvn/src/org/tmatesoft/svn/core/internal/wc/SVNCommitUtil.java b/javasvn/src/org/tmatesoft/svn/core/internal/wc/SVNCommitUtil.java index c8ca3718a..40ad4407e 100644 --- a/javasvn/src/org/tmatesoft/svn/core/internal/wc/SVNCommitUtil.java +++ b/javasvn/src/org/tmatesoft/svn/core/internal/wc/SVNCommitUtil.java @@ -1,746 +1,746 @@ /* * ==================================================================== * Copyright (c) 2004 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which you should * have received as part of this distribution. The terms are also available at * http://tmate.org/svn/license.html. If newer versions of this license are * posted there, you may use a newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.wc; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNNodeKind; import org.tmatesoft.svn.core.SVNProperty; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.io.ISVNEditor; import org.tmatesoft.svn.core.wc.SVNCommitItem; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc.SVNStatus; import org.tmatesoft.svn.core.wc.SVNStatusClient; import org.tmatesoft.svn.core.wc.SVNStatusType; import org.tmatesoft.svn.core.wc.SVNWCUtil; /** * @version 1.0 * @author TMate Software Ltd. */ public class SVNCommitUtil { public static void driveCommitEditor(ISVNCommitPathHandler handler, Collection paths, ISVNEditor editor, long revision) throws SVNException { if (paths == null || paths.isEmpty() || handler == null || editor == null) { return; } String[] pathsArray = (String[]) paths.toArray(new String[paths.size()]); Arrays.sort(pathsArray, SVNPathUtil.PATH_COMPARATOR); int index = 0; String lastPath = null; if ("".equals(pathsArray[index])) { handler.handleCommitPath("", editor); lastPath = pathsArray[index]; index++; } else { editor.openRoot(revision); } for (; index < pathsArray.length; index++) { String commitPath = pathsArray[index]; String commonAncestor = lastPath == null || "".equals(lastPath) ? "" : SVNPathUtil.getCommonPathAncestor(commitPath, lastPath); if (lastPath != null) { while (!lastPath.equals(commonAncestor)) { editor.closeDir(); if (lastPath.lastIndexOf('/') >= 0) { lastPath = lastPath.substring(0, lastPath.lastIndexOf('/')); } else { lastPath = ""; } } } String relativeCommitPath = commitPath.substring(commonAncestor.length()); if (relativeCommitPath.startsWith("/")) { relativeCommitPath = relativeCommitPath.substring(1); } for (StringTokenizer tokens = new StringTokenizer( relativeCommitPath, "/"); tokens.hasMoreTokens();) { String token = tokens.nextToken(); commonAncestor = "".equals(commonAncestor) ? token : commonAncestor + "/" + token; if (!commonAncestor.equals(commitPath)) { editor.openDir(commonAncestor, revision); } else { break; } } boolean closeDir = handler.handleCommitPath(commitPath, editor); if (closeDir) { lastPath = commitPath; } else { lastPath = SVNPathUtil.removeTail(commitPath); } } while (lastPath != null && !"".equals(lastPath)) { editor.closeDir(); lastPath = lastPath.lastIndexOf('/') >= 0 ? lastPath.substring(0, lastPath.lastIndexOf('/')) : ""; } } public static SVNWCAccess createCommitWCAccess(File[] paths, boolean recursive, boolean force, Collection relativePaths, SVNStatusClient statusClient) throws SVNException { File wcRoot = null; for (int i = 0; i < paths.length; i++) { File path = paths[i]; File newWCRoot = SVNWCUtil.getWorkingCopyRoot(path, true); if (wcRoot != null && !wcRoot.equals(newWCRoot)) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "Commit targets should belong to the same working copy"); SVNErrorManager.error(err); } wcRoot = newWCRoot; } String[] validatedPaths = new String[paths.length]; for (int i = 0; i < paths.length; i++) { File file = paths[i]; validatedPaths[i] = SVNPathUtil.validateFilePath(file.getAbsolutePath()); } String rootPath = SVNPathUtil.condencePaths(validatedPaths, relativePaths, recursive); if (rootPath == null) { return null; } File baseDir = new File(rootPath); Collection dirsToLock = new TreeSet(); // relative paths to lock. Collection dirsToLockRecursively = new TreeSet(); boolean lockAll = false; if (relativePaths.isEmpty()) { String target = getTargetName(baseDir); if (!"".equals(target)) { // we will have to lock target as well, not only base dir. SVNFileType targetType = SVNFileType.getType(new File(rootPath)); relativePaths.add(target); if (targetType == SVNFileType.DIRECTORY) { // lock recursively if forced and copied... if (recursive || (force && isRecursiveCommitForced(baseDir))) { // dir is copied, include children dirsToLockRecursively.add(target); } else { dirsToLock.add(target); } } baseDir = baseDir.getParentFile(); } else { lockAll = true; } } else { baseDir = adjustRelativePaths(baseDir, relativePaths); // there are multiple paths. for (Iterator targets = relativePaths.iterator(); targets.hasNext();) { String targetPath = (String) targets.next(); File targetFile = new File(baseDir, targetPath); String target = getTargetName(targetFile); if (!"".equals(target)) { SVNFileType targetType = SVNFileType.getType(targetFile); if (targetType == SVNFileType.DIRECTORY) { if (recursive || (force && isRecursiveCommitForced(targetFile))) { dirsToLockRecursively.add(targetPath); } else { dirsToLock.add(targetPath); } } } // now lock all dirs from anchor to base dir (non-recursive). targetFile = targetFile.getParentFile(); targetPath = SVNPathUtil.removeTail(targetPath); while (targetFile != null && !baseDir.equals(targetFile) && !"".equals(targetPath) && !dirsToLock.contains(targetPath)) { dirsToLock.add(targetPath); targetFile = targetFile.getParentFile(); targetPath = SVNPathUtil.removeTail(targetPath); } } } SVNDirectory anchor = new SVNDirectory(null, "", baseDir); SVNWCAccess baseAccess = new SVNWCAccess(anchor, anchor, ""); if (!recursive && !force) { for (Iterator targets = relativePaths.iterator(); targets.hasNext();) { String targetPath = (String) targets.next(); File targetFile = new File(baseDir, targetPath); if (SVNFileType.getType(targetFile) == SVNFileType.DIRECTORY) { SVNStatus status = statusClient.doStatus(targetFile, false); if (status != null && (status.getContentsStatus() == SVNStatusType.STATUS_DELETED || status.getContentsStatus() == SVNStatusType.STATUS_REPLACED)) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "Cannot non-recursively commit a directory deletion"); SVNErrorManager.error(err); } } } } try { if (lockAll) { baseAccess.open(true, recursive); } else { baseAccess.open(true, false); removeRedundantPaths(dirsToLockRecursively, dirsToLock); for (Iterator nonRecusivePaths = dirsToLock.iterator(); nonRecusivePaths.hasNext();) { String path = (String) nonRecusivePaths.next(); File pathFile = new File(baseDir, path); baseAccess.addDirectory(path, pathFile, false, true); } for (Iterator recusivePaths = dirsToLockRecursively.iterator(); recusivePaths.hasNext();) { String path = (String) recusivePaths.next(); File pathFile = new File(baseDir, path); baseAccess.addDirectory(path, pathFile, true, true); } } // if commit is non-recursive and forced, remove those child dirs // that were not explicitly added but are explicitly copied. ufff. if (!recursive && force) { SVNDirectory[] lockedDirs = baseAccess.getAllDirectories(); for (int i = 0; i < lockedDirs.length; i++) { SVNDirectory dir = lockedDirs[i]; SVNEntry rootEntry = dir.getEntries().getEntry("", true); if (rootEntry.getCopyFromURL() != null) { File dirRoot = dir.getRoot(); boolean keep = false; for (int j = 0; j < paths.length; j++) { if (dirRoot.equals(paths[j])) { keep = true; break; } } if (!keep) { baseAccess.removeDirectory(dir.getPath(), true); } } } } } catch (SVNException e) { baseAccess.close(true); throw e; } return baseAccess; } public static SVNWCAccess[] createCommitWCAccess2(File[] paths, boolean recursive, boolean force, Map relativePathsMap, SVNStatusClient statusClient) throws SVNException { Map rootsMap = new HashMap(); // wc root file -> paths to be committed (paths). for (int i = 0; i < paths.length; i++) { File path = paths[i]; File wcRoot = SVNWCUtil.getWorkingCopyRoot(path, true); if (!rootsMap.containsKey(wcRoot)) { rootsMap.put(wcRoot, new ArrayList()); } Collection wcPaths = (Collection) rootsMap.get(wcRoot); wcPaths.add(path); } Collection result = new ArrayList(); try { for (Iterator roots = rootsMap.keySet().iterator(); roots.hasNext();) { File root = (File) roots.next(); Collection filesList = (Collection) rootsMap.get(root); File[] filesArray = (File[]) filesList.toArray(new File[filesList.size()]); Collection relativePaths = new TreeSet(); SVNWCAccess wcAccess = createCommitWCAccess(filesArray, recursive, force, relativePaths, statusClient); relativePathsMap.put(wcAccess, relativePaths); result.add(wcAccess); } } catch (SVNException e) { for (Iterator wcAccesses = result.iterator(); wcAccesses.hasNext();) { SVNWCAccess wcAccess = (SVNWCAccess) wcAccesses.next(); wcAccess.close(true); } throw e; } return (SVNWCAccess[]) result.toArray(new SVNWCAccess[result.size()]); } public static SVNCommitItem[] harvestCommitables(SVNWCAccess baseAccess, Collection paths, Map lockTokens, boolean justLocked, boolean recursive, boolean force) throws SVNException { Map commitables = new TreeMap(); Collection danglers = new HashSet(); Iterator targets = paths.iterator(); boolean isRecursionForced = false; do { String target = targets.hasNext() ? (String) targets.next() : ""; // get entry for target File targetFile = new File(baseAccess.getAnchor().getRoot(), target); String targetName = "".equals(target) ? "" : SVNPathUtil.tail(target); String parentPath = SVNPathUtil.removeTail(target); SVNDirectory dir = baseAccess.getDirectory(parentPath); SVNEntry entry = dir == null ? null : dir.getEntries().getEntry( targetName, false); String url = null; if (entry == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ENTRY_NOT_FOUND, "''{0}'' is not under version control", targetFile); SVNErrorManager.error(err); } else if (entry.getURL() == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ENTRY_MISSING_URL, "''{0}'' has no URL", targetFile); SVNErrorManager.error(err); } else { url = entry.getURL(); } if (entry != null && (entry.isScheduledForAddition() || entry .isScheduledForReplacement())) { // get parent (for file or dir-> get ""), otherwise open parent // dir and get "". SVNEntry parentEntry; if (!"".equals(targetName)) { parentEntry = dir.getEntries().getEntry("", false); } else { File parentFile = targetFile.getParentFile(); SVNWCAccess parentAccess = SVNWCAccess.create(parentFile); parentEntry = parentAccess.getTarget().getEntries() .getEntry("", false); } if (parentEntry == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_CORRUPT, "''{0}'' is scheduled for addition within unversioned parent", targetFile); SVNErrorManager.error(err); } else if (parentEntry.isScheduledForAddition() || parentEntry.isScheduledForReplacement()) { danglers.add(targetFile.getParentFile()); } } boolean recurse = recursive; if (entry != null && entry.isCopied() && entry.getSchedule() == null) { // if commit is forced => we could collect this entry, assuming // that its parent is already included into commit // it will be later removed from commit anyway. if (!force) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ILLEGAL_TARGET, "Entry for ''{0}''" + " is marked as 'copied' but is not itself scheduled\n" + "for addition. Perhaps you're committing a target that is\n" + "inside an unversioned (or not-yet-versioned) directory?", targetFile); SVNErrorManager.error(err); } else { // just do not process this item as in case of recursive // commit. continue; } } else if (entry != null && entry.isCopied() && entry.isScheduledForAddition()) { if (force) { isRecursionForced = !recursive; recurse = true; } } else if (entry != null && entry.isScheduledForDeletion()) { if (force && !recursive) { // if parent is also deleted -> skip this entry SVNEntry parentEntry; if (!"".equals(targetName)) { parentEntry = dir.getEntries().getEntry("", false); } else { File parentFile = targetFile.getParentFile(); SVNWCAccess parentAccess = SVNWCAccess.create(parentFile); parentEntry = parentAccess.getTarget().getEntries() .getEntry("", false); } if (parentEntry != null && parentEntry.isScheduledForDeletion() && paths.contains(parentPath)) { continue; } // this recursion is not considered as "forced", all children should be // deleted anyway. recurse = true; } } harvestCommitables(commitables, dir, targetFile, null, entry, url, null, false, false, justLocked, lockTokens, recurse, isRecursionForced); } while (targets.hasNext()); for (Iterator ds = danglers.iterator(); ds.hasNext();) { File file = (File) ds.next(); if (!commitables.containsKey(file)) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ILLEGAL_TARGET, "''{0}'' is not under version control\n" + "and is not part of the commit, \n" + "yet its child is part of the commit", file); SVNErrorManager.error(err); } } if (isRecursionForced) { // if commit is non-recursive and forced and there are elements included into commit // that not only 'copied' but also has local mods (modified or deleted), remove those items? // or not? for (Iterator items = commitables.values().iterator(); items.hasNext();) { SVNCommitItem item = (SVNCommitItem) items.next(); if (item.isDeleted()) { // to detect deleted copied items. File file = item.getFile(); if (item.getKind() == SVNNodeKind.DIR) { if (!file.exists()) { continue; } } else { String path = SVNPathUtil.removeTail(item.getPath()); String name = SVNPathUtil.tail(item.getPath()); SVNDirectory dir = baseAccess.getDirectory(path); if (!dir.getBaseFile(name, false).exists()) { continue; } } } if (item.isContentsModified() || item.isDeleted() || item.isPropertiesModified()) { // if item was not explicitly included into commit, then just make it 'added' // but do not remove that are marked as 'deleted' String itemPath = item.getPath(); if (!paths.contains(itemPath)) { items.remove(); } } } } return (SVNCommitItem[]) commitables.values().toArray(new SVNCommitItem[commitables.values().size()]); } public static String translateCommitables(SVNCommitItem[] items, Map decodedPaths) throws SVNException { Map itemsMap = new TreeMap(); for (int i = 0; i < items.length; i++) { SVNCommitItem item = items[i]; if (itemsMap.containsKey(item.getURL().toString())) { SVNCommitItem oldItem = (SVNCommitItem) itemsMap.get(item.getURL().toString()); SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CLIENT_DUPLICATE_COMMIT_URL, "Cannot commit both ''{0}'' and ''{1}'' as they refer to the same URL", new Object[] {item.getFile(), oldItem.getFile()}); SVNErrorManager.error(err); } itemsMap.put(item.getURL().toString(), item); } Iterator urls = itemsMap.keySet().iterator(); String baseURL = (String) urls.next(); while (urls.hasNext()) { String url = (String) urls.next(); baseURL = SVNPathUtil.getCommonURLAncestor(baseURL, url); } if (itemsMap.containsKey(baseURL)) { SVNCommitItem root = (SVNCommitItem) itemsMap.get(baseURL); if (root.getKind() != SVNNodeKind.DIR) { baseURL = SVNPathUtil.removeTail(baseURL); } else if (root.getKind() == SVNNodeKind.DIR && (root.isAdded() || root.isDeleted() || root.isCopied() || root .isLocked())) { baseURL = SVNPathUtil.removeTail(baseURL); } } urls = itemsMap.keySet().iterator(); while (urls.hasNext()) { String url = (String) urls.next(); SVNCommitItem item = (SVNCommitItem) itemsMap.get(url); String realPath = url.equals(baseURL) ? "" : url.substring(baseURL.length() + 1); decodedPaths.put(SVNEncodingUtil.uriDecode(realPath), item); } return baseURL; } public static Map translateLockTokens(Map lockTokens, String baseURL) { Map translatedLocks = new TreeMap(); for (Iterator urls = lockTokens.keySet().iterator(); urls.hasNext();) { String url = (String) urls.next(); String token = (String) lockTokens.get(url); url = url.equals(baseURL) ? "" : url.substring(baseURL.length() + 1); translatedLocks.put(SVNEncodingUtil.uriDecode(url), token); } lockTokens.clear(); lockTokens.putAll(translatedLocks); return lockTokens; } public static void harvestCommitables(Map commitables, SVNDirectory dir, File path, SVNEntry parentEntry, SVNEntry entry, String url, String copyFromURL, boolean copyMode, boolean addsOnly, boolean justLocked, Map lockTokens, boolean recursive, boolean forcedRecursion) throws SVNException { if (commitables.containsKey(path)) { return; } if (dir != null && dir.getWCAccess() != null) { dir.getWCAccess().checkCancelled(); } long cfRevision = entry.getCopyFromRevision(); String cfURL = null; if (entry.getKind() != SVNNodeKind.DIR && entry.getKind() != SVNNodeKind.FILE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.NODE_UNKNOWN_KIND, "Unknwon entry kind for ''{0}''", path); SVNErrorManager.error(err); } SVNFileType fileType = SVNFileType.getType(path); if (fileType == SVNFileType.UNKNOWN) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.NODE_UNKNOWN_KIND, "Unknwon entry kind for ''{0}''", path); SVNErrorManager.error(err); } boolean specialFile = fileType == SVNFileType.SYMLINK; if (specialFile != (dir.getProperties(entry.getName(), false) .getPropertyValue(SVNProperty.SPECIAL) != null) && fileType != SVNFileType.NONE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.NODE_UNEXPECTED_KIND, "Entry ''{0}'' has unexpectedly changed special status", path); SVNErrorManager.error(err); } boolean propConflicts; boolean textConflicts = false; SVNEntries entries = null; if (entry.getKind() == SVNNodeKind.DIR) { SVNDirectory childDir = dir.getChildDirectory(entry.getName()); if (childDir != null && childDir.getEntries() != null) { entries = childDir.getEntries(); if (entries.getEntry("", false) != null) { entry = entries.getEntry("", false); dir = childDir; } propConflicts = entry.getPropRejectFile() != null; } else { propConflicts = entry.getPropRejectFile() != null; } } else { propConflicts = entry.getPropRejectFile() != null; textConflicts = entry.getConflictOld() != null || entry.getConflictNew() != null || entry.getConflictWorking() != null; } if (propConflicts || textConflicts) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_FOUND_CONFLICT, "Aborting commit: ''{0}'' remains in conflict", path); SVNErrorManager.error(err); } if (entry.getURL() != null && !copyMode) { url = entry.getURL(); } boolean commitDeletion = !addsOnly && ((entry.isDeleted() && entry.getSchedule() == null) || entry.isScheduledForDeletion() || entry.isScheduledForReplacement()); boolean commitAddition = false; boolean commitCopy = false; if (entry.isScheduledForAddition() || entry.isScheduledForReplacement()) { commitAddition = true; if (entry.getCopyFromURL() != null) { cfURL = entry.getCopyFromURL(); addsOnly = false; commitCopy = true; } else { addsOnly = true; } } if ((entry.isCopied() || copyMode) && !entry.isDeleted() && entry.getSchedule() == null) { long parentRevision = entry.getRevision() - 1; if (!SVNWCUtil.isWorkingCopyRoot(path, true)) { if (parentEntry != null) { parentRevision = parentEntry.getRevision(); } } else if (!copyMode) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_CORRUPT, "Did not expect ''{0}'' to be a working copy root", path); SVNErrorManager.error(err); } if (parentRevision != entry.getRevision()) { commitAddition = true; commitCopy = true; addsOnly = false; cfRevision = entry.getRevision(); if (copyMode) { cfURL = entry.getURL(); } else if (copyFromURL != null) { cfURL = copyFromURL; } else { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.BAD_URL, "Commit item ''{0}'' has copy flag but no copyfrom URL", path); SVNErrorManager.error(err); } } } boolean textModified = false; boolean propsModified = false; boolean commitLock; if (commitAddition) { SVNProperties props = dir.getProperties(entry.getName(), false); SVNProperties baseProps = dir.getBaseProperties(entry.getName(), false); Map propDiff = baseProps.compareTo(props); boolean eolChanged = textModified = propDiff != null && propDiff.containsKey(SVNProperty.EOL_STYLE); if (entry.getKind() == SVNNodeKind.FILE) { if (commitCopy) { textModified = propDiff != null && propDiff.containsKey(SVNProperty.EOL_STYLE); if (!textModified) { textModified = dir.hasTextModifications(entry.getName(), eolChanged); } } else { textModified = true; } } propsModified = propDiff != null && !propDiff.isEmpty(); } else if (!commitDeletion) { SVNProperties props = dir.getProperties(entry.getName(), false); SVNProperties baseProps = dir.getBaseProperties(entry.getName(), false); Map propDiff = baseProps.compareTo(props); boolean eolChanged = textModified = propDiff != null && propDiff.containsKey(SVNProperty.EOL_STYLE); propsModified = propDiff != null && !propDiff.isEmpty(); if (entry.getKind() == SVNNodeKind.FILE) { textModified = dir.hasTextModifications(entry.getName(), eolChanged); } } commitLock = entry.getLockToken() != null && (justLocked || textModified || propsModified || commitDeletion || commitAddition || commitCopy); if (commitAddition || commitDeletion || textModified || propsModified || commitCopy || commitLock) { SVNCommitItem item = new SVNCommitItem(path, SVNURL.parseURIEncoded(url), cfURL != null ? SVNURL.parseURIEncoded(cfURL) : null, entry.getKind(), cfURL != null ? SVNRevision.create(cfRevision) : SVNRevision.create(entry.getRevision()), commitAddition, commitDeletion, propsModified, textModified, commitCopy, commitLock); String itemPath = dir.getPath(); if ("".equals(itemPath)) { itemPath += entry.getName(); } else if (!"".equals(entry.getName())) { itemPath += "/" + entry.getName(); } item.setPath(itemPath); commitables.put(path, item); if (lockTokens != null && entry.getLockToken() != null) { lockTokens.put(url, entry.getLockToken()); } } if (entries != null && recursive && (commitAddition || !commitDeletion)) { // recurse. for (Iterator ents = entries.entries(copyMode); ents.hasNext();) { SVNEntry currentEntry = (SVNEntry) ents.next(); if ("".equals(currentEntry.getName())) { continue; } // if recursion is forced and entry is explicitly copied, skip it. - if (currentEntry.isCopied() && currentEntry.getCopyFromURL() != null) { + if (forcedRecursion && currentEntry.isCopied() && currentEntry.getCopyFromURL() != null) { continue; } String currentCFURL = cfURL != null ? cfURL : copyFromURL; if (currentCFURL != null) { currentCFURL = SVNPathUtil.append(currentCFURL, SVNEncodingUtil.uriEncode(currentEntry.getName())); } String currentURL = currentEntry.getURL(); if (copyMode || entry.getURL() == null) { currentURL = SVNPathUtil.append(url, SVNEncodingUtil.uriEncode(currentEntry.getName())); } File currentFile = dir.getFile(currentEntry.getName()); SVNDirectory childDir; if (currentEntry.getKind() == SVNNodeKind.DIR) { childDir = dir.getChildDirectory(currentEntry.getName()); if (childDir == null) { SVNFileType currentType = SVNFileType.getType(currentFile); if (currentType == SVNFileType.NONE && currentEntry.isScheduledForDeletion()) { SVNCommitItem item = new SVNCommitItem(currentFile, SVNURL.parseURIEncoded(currentURL), null, currentEntry.getKind(), SVNRevision.UNDEFINED, false, true, false, false, false, false); item.setPath(SVNPathUtil.append(dir.getPath(), currentEntry.getName())); commitables.put(currentFile, item); continue; } SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_LOCKED, "Working copy ''{0}'' is missing or not locked", currentFile); SVNErrorManager.error(err); } } harvestCommitables(commitables, dir, currentFile, entry, currentEntry, currentURL, currentCFURL, copyMode, addsOnly, justLocked, lockTokens, true, forcedRecursion); } } if (lockTokens != null && entry.getKind() == SVNNodeKind.DIR && commitDeletion) { // harvest lock tokens for deleted items. collectLocks(dir, lockTokens); } } private static void collectLocks(SVNDirectory dir, Map lockTokens) throws SVNException { SVNEntries entries = dir.getEntries(); if (entries == null) { return; } for (Iterator ents = entries.entries(false); ents.hasNext();) { SVNEntry entry = (SVNEntry) ents.next(); if (entry.getURL() != null && entry.getLockToken() != null) { lockTokens.put(entry.getURL(), entry.getLockToken()); } if (!"".equals(entry.getName()) && entry.isDirectory()) { SVNDirectory child = dir.getChildDirectory(entry.getName()); if (child != null) { collectLocks(child, lockTokens); } } } entries.close(); } private static void removeRedundantPaths(Collection dirsToLockRecursively, Collection dirsToLock) { for (Iterator paths = dirsToLock.iterator(); paths.hasNext();) { String path = (String) paths.next(); if (dirsToLockRecursively.contains(path)) { paths.remove(); } else { for (Iterator recPaths = dirsToLockRecursively.iterator(); recPaths .hasNext();) { String existingPath = (String) recPaths.next(); if (path.startsWith(existingPath + "/")) { paths.remove(); break; } } } } } private static File adjustRelativePaths(File rootFile, Collection relativePaths) throws SVNException { if (relativePaths.contains("")) { String targetName = getTargetName(rootFile); if (!"".equals(targetName) && rootFile.getParentFile() != null) { // there is a versioned parent. rootFile = rootFile.getParentFile(); Collection result = new TreeSet(); for (Iterator paths = relativePaths.iterator(); paths.hasNext();) { String path = (String) paths.next(); path = "".equals(path) ? targetName : SVNPathUtil.append(targetName, path); result.add(path); } relativePaths.clear(); relativePaths.addAll(result); } } return rootFile; } private static String getTargetName(File file) throws SVNException { SVNWCAccess wcAccess = SVNWCAccess.create(file); return wcAccess.getTargetName(); } private static boolean isRecursiveCommitForced(File directory) throws SVNException { SVNWCAccess wcAccess = SVNWCAccess.create(directory); SVNEntry targetEntry = wcAccess.getTargetEntry(); if (targetEntry != null) { return targetEntry.isCopied() || targetEntry.isScheduledForDeletion() || targetEntry.isScheduledForReplacement(); } return false; } }
true
true
public static void harvestCommitables(Map commitables, SVNDirectory dir, File path, SVNEntry parentEntry, SVNEntry entry, String url, String copyFromURL, boolean copyMode, boolean addsOnly, boolean justLocked, Map lockTokens, boolean recursive, boolean forcedRecursion) throws SVNException { if (commitables.containsKey(path)) { return; } if (dir != null && dir.getWCAccess() != null) { dir.getWCAccess().checkCancelled(); } long cfRevision = entry.getCopyFromRevision(); String cfURL = null; if (entry.getKind() != SVNNodeKind.DIR && entry.getKind() != SVNNodeKind.FILE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.NODE_UNKNOWN_KIND, "Unknwon entry kind for ''{0}''", path); SVNErrorManager.error(err); } SVNFileType fileType = SVNFileType.getType(path); if (fileType == SVNFileType.UNKNOWN) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.NODE_UNKNOWN_KIND, "Unknwon entry kind for ''{0}''", path); SVNErrorManager.error(err); } boolean specialFile = fileType == SVNFileType.SYMLINK; if (specialFile != (dir.getProperties(entry.getName(), false) .getPropertyValue(SVNProperty.SPECIAL) != null) && fileType != SVNFileType.NONE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.NODE_UNEXPECTED_KIND, "Entry ''{0}'' has unexpectedly changed special status", path); SVNErrorManager.error(err); } boolean propConflicts; boolean textConflicts = false; SVNEntries entries = null; if (entry.getKind() == SVNNodeKind.DIR) { SVNDirectory childDir = dir.getChildDirectory(entry.getName()); if (childDir != null && childDir.getEntries() != null) { entries = childDir.getEntries(); if (entries.getEntry("", false) != null) { entry = entries.getEntry("", false); dir = childDir; } propConflicts = entry.getPropRejectFile() != null; } else { propConflicts = entry.getPropRejectFile() != null; } } else { propConflicts = entry.getPropRejectFile() != null; textConflicts = entry.getConflictOld() != null || entry.getConflictNew() != null || entry.getConflictWorking() != null; } if (propConflicts || textConflicts) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_FOUND_CONFLICT, "Aborting commit: ''{0}'' remains in conflict", path); SVNErrorManager.error(err); } if (entry.getURL() != null && !copyMode) { url = entry.getURL(); } boolean commitDeletion = !addsOnly && ((entry.isDeleted() && entry.getSchedule() == null) || entry.isScheduledForDeletion() || entry.isScheduledForReplacement()); boolean commitAddition = false; boolean commitCopy = false; if (entry.isScheduledForAddition() || entry.isScheduledForReplacement()) { commitAddition = true; if (entry.getCopyFromURL() != null) { cfURL = entry.getCopyFromURL(); addsOnly = false; commitCopy = true; } else { addsOnly = true; } } if ((entry.isCopied() || copyMode) && !entry.isDeleted() && entry.getSchedule() == null) { long parentRevision = entry.getRevision() - 1; if (!SVNWCUtil.isWorkingCopyRoot(path, true)) { if (parentEntry != null) { parentRevision = parentEntry.getRevision(); } } else if (!copyMode) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_CORRUPT, "Did not expect ''{0}'' to be a working copy root", path); SVNErrorManager.error(err); } if (parentRevision != entry.getRevision()) { commitAddition = true; commitCopy = true; addsOnly = false; cfRevision = entry.getRevision(); if (copyMode) { cfURL = entry.getURL(); } else if (copyFromURL != null) { cfURL = copyFromURL; } else { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.BAD_URL, "Commit item ''{0}'' has copy flag but no copyfrom URL", path); SVNErrorManager.error(err); } } } boolean textModified = false; boolean propsModified = false; boolean commitLock; if (commitAddition) { SVNProperties props = dir.getProperties(entry.getName(), false); SVNProperties baseProps = dir.getBaseProperties(entry.getName(), false); Map propDiff = baseProps.compareTo(props); boolean eolChanged = textModified = propDiff != null && propDiff.containsKey(SVNProperty.EOL_STYLE); if (entry.getKind() == SVNNodeKind.FILE) { if (commitCopy) { textModified = propDiff != null && propDiff.containsKey(SVNProperty.EOL_STYLE); if (!textModified) { textModified = dir.hasTextModifications(entry.getName(), eolChanged); } } else { textModified = true; } } propsModified = propDiff != null && !propDiff.isEmpty(); } else if (!commitDeletion) { SVNProperties props = dir.getProperties(entry.getName(), false); SVNProperties baseProps = dir.getBaseProperties(entry.getName(), false); Map propDiff = baseProps.compareTo(props); boolean eolChanged = textModified = propDiff != null && propDiff.containsKey(SVNProperty.EOL_STYLE); propsModified = propDiff != null && !propDiff.isEmpty(); if (entry.getKind() == SVNNodeKind.FILE) { textModified = dir.hasTextModifications(entry.getName(), eolChanged); } } commitLock = entry.getLockToken() != null && (justLocked || textModified || propsModified || commitDeletion || commitAddition || commitCopy); if (commitAddition || commitDeletion || textModified || propsModified || commitCopy || commitLock) { SVNCommitItem item = new SVNCommitItem(path, SVNURL.parseURIEncoded(url), cfURL != null ? SVNURL.parseURIEncoded(cfURL) : null, entry.getKind(), cfURL != null ? SVNRevision.create(cfRevision) : SVNRevision.create(entry.getRevision()), commitAddition, commitDeletion, propsModified, textModified, commitCopy, commitLock); String itemPath = dir.getPath(); if ("".equals(itemPath)) { itemPath += entry.getName(); } else if (!"".equals(entry.getName())) { itemPath += "/" + entry.getName(); } item.setPath(itemPath); commitables.put(path, item); if (lockTokens != null && entry.getLockToken() != null) { lockTokens.put(url, entry.getLockToken()); } } if (entries != null && recursive && (commitAddition || !commitDeletion)) { // recurse. for (Iterator ents = entries.entries(copyMode); ents.hasNext();) { SVNEntry currentEntry = (SVNEntry) ents.next(); if ("".equals(currentEntry.getName())) { continue; } // if recursion is forced and entry is explicitly copied, skip it. if (currentEntry.isCopied() && currentEntry.getCopyFromURL() != null) { continue; } String currentCFURL = cfURL != null ? cfURL : copyFromURL; if (currentCFURL != null) { currentCFURL = SVNPathUtil.append(currentCFURL, SVNEncodingUtil.uriEncode(currentEntry.getName())); } String currentURL = currentEntry.getURL(); if (copyMode || entry.getURL() == null) { currentURL = SVNPathUtil.append(url, SVNEncodingUtil.uriEncode(currentEntry.getName())); } File currentFile = dir.getFile(currentEntry.getName()); SVNDirectory childDir; if (currentEntry.getKind() == SVNNodeKind.DIR) { childDir = dir.getChildDirectory(currentEntry.getName()); if (childDir == null) { SVNFileType currentType = SVNFileType.getType(currentFile); if (currentType == SVNFileType.NONE && currentEntry.isScheduledForDeletion()) { SVNCommitItem item = new SVNCommitItem(currentFile, SVNURL.parseURIEncoded(currentURL), null, currentEntry.getKind(), SVNRevision.UNDEFINED, false, true, false, false, false, false); item.setPath(SVNPathUtil.append(dir.getPath(), currentEntry.getName())); commitables.put(currentFile, item); continue; } SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_LOCKED, "Working copy ''{0}'' is missing or not locked", currentFile); SVNErrorManager.error(err); } } harvestCommitables(commitables, dir, currentFile, entry, currentEntry, currentURL, currentCFURL, copyMode, addsOnly, justLocked, lockTokens, true, forcedRecursion); } } if (lockTokens != null && entry.getKind() == SVNNodeKind.DIR && commitDeletion) { // harvest lock tokens for deleted items. collectLocks(dir, lockTokens); } }
public static void harvestCommitables(Map commitables, SVNDirectory dir, File path, SVNEntry parentEntry, SVNEntry entry, String url, String copyFromURL, boolean copyMode, boolean addsOnly, boolean justLocked, Map lockTokens, boolean recursive, boolean forcedRecursion) throws SVNException { if (commitables.containsKey(path)) { return; } if (dir != null && dir.getWCAccess() != null) { dir.getWCAccess().checkCancelled(); } long cfRevision = entry.getCopyFromRevision(); String cfURL = null; if (entry.getKind() != SVNNodeKind.DIR && entry.getKind() != SVNNodeKind.FILE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.NODE_UNKNOWN_KIND, "Unknwon entry kind for ''{0}''", path); SVNErrorManager.error(err); } SVNFileType fileType = SVNFileType.getType(path); if (fileType == SVNFileType.UNKNOWN) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.NODE_UNKNOWN_KIND, "Unknwon entry kind for ''{0}''", path); SVNErrorManager.error(err); } boolean specialFile = fileType == SVNFileType.SYMLINK; if (specialFile != (dir.getProperties(entry.getName(), false) .getPropertyValue(SVNProperty.SPECIAL) != null) && fileType != SVNFileType.NONE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.NODE_UNEXPECTED_KIND, "Entry ''{0}'' has unexpectedly changed special status", path); SVNErrorManager.error(err); } boolean propConflicts; boolean textConflicts = false; SVNEntries entries = null; if (entry.getKind() == SVNNodeKind.DIR) { SVNDirectory childDir = dir.getChildDirectory(entry.getName()); if (childDir != null && childDir.getEntries() != null) { entries = childDir.getEntries(); if (entries.getEntry("", false) != null) { entry = entries.getEntry("", false); dir = childDir; } propConflicts = entry.getPropRejectFile() != null; } else { propConflicts = entry.getPropRejectFile() != null; } } else { propConflicts = entry.getPropRejectFile() != null; textConflicts = entry.getConflictOld() != null || entry.getConflictNew() != null || entry.getConflictWorking() != null; } if (propConflicts || textConflicts) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_FOUND_CONFLICT, "Aborting commit: ''{0}'' remains in conflict", path); SVNErrorManager.error(err); } if (entry.getURL() != null && !copyMode) { url = entry.getURL(); } boolean commitDeletion = !addsOnly && ((entry.isDeleted() && entry.getSchedule() == null) || entry.isScheduledForDeletion() || entry.isScheduledForReplacement()); boolean commitAddition = false; boolean commitCopy = false; if (entry.isScheduledForAddition() || entry.isScheduledForReplacement()) { commitAddition = true; if (entry.getCopyFromURL() != null) { cfURL = entry.getCopyFromURL(); addsOnly = false; commitCopy = true; } else { addsOnly = true; } } if ((entry.isCopied() || copyMode) && !entry.isDeleted() && entry.getSchedule() == null) { long parentRevision = entry.getRevision() - 1; if (!SVNWCUtil.isWorkingCopyRoot(path, true)) { if (parentEntry != null) { parentRevision = parentEntry.getRevision(); } } else if (!copyMode) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_CORRUPT, "Did not expect ''{0}'' to be a working copy root", path); SVNErrorManager.error(err); } if (parentRevision != entry.getRevision()) { commitAddition = true; commitCopy = true; addsOnly = false; cfRevision = entry.getRevision(); if (copyMode) { cfURL = entry.getURL(); } else if (copyFromURL != null) { cfURL = copyFromURL; } else { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.BAD_URL, "Commit item ''{0}'' has copy flag but no copyfrom URL", path); SVNErrorManager.error(err); } } } boolean textModified = false; boolean propsModified = false; boolean commitLock; if (commitAddition) { SVNProperties props = dir.getProperties(entry.getName(), false); SVNProperties baseProps = dir.getBaseProperties(entry.getName(), false); Map propDiff = baseProps.compareTo(props); boolean eolChanged = textModified = propDiff != null && propDiff.containsKey(SVNProperty.EOL_STYLE); if (entry.getKind() == SVNNodeKind.FILE) { if (commitCopy) { textModified = propDiff != null && propDiff.containsKey(SVNProperty.EOL_STYLE); if (!textModified) { textModified = dir.hasTextModifications(entry.getName(), eolChanged); } } else { textModified = true; } } propsModified = propDiff != null && !propDiff.isEmpty(); } else if (!commitDeletion) { SVNProperties props = dir.getProperties(entry.getName(), false); SVNProperties baseProps = dir.getBaseProperties(entry.getName(), false); Map propDiff = baseProps.compareTo(props); boolean eolChanged = textModified = propDiff != null && propDiff.containsKey(SVNProperty.EOL_STYLE); propsModified = propDiff != null && !propDiff.isEmpty(); if (entry.getKind() == SVNNodeKind.FILE) { textModified = dir.hasTextModifications(entry.getName(), eolChanged); } } commitLock = entry.getLockToken() != null && (justLocked || textModified || propsModified || commitDeletion || commitAddition || commitCopy); if (commitAddition || commitDeletion || textModified || propsModified || commitCopy || commitLock) { SVNCommitItem item = new SVNCommitItem(path, SVNURL.parseURIEncoded(url), cfURL != null ? SVNURL.parseURIEncoded(cfURL) : null, entry.getKind(), cfURL != null ? SVNRevision.create(cfRevision) : SVNRevision.create(entry.getRevision()), commitAddition, commitDeletion, propsModified, textModified, commitCopy, commitLock); String itemPath = dir.getPath(); if ("".equals(itemPath)) { itemPath += entry.getName(); } else if (!"".equals(entry.getName())) { itemPath += "/" + entry.getName(); } item.setPath(itemPath); commitables.put(path, item); if (lockTokens != null && entry.getLockToken() != null) { lockTokens.put(url, entry.getLockToken()); } } if (entries != null && recursive && (commitAddition || !commitDeletion)) { // recurse. for (Iterator ents = entries.entries(copyMode); ents.hasNext();) { SVNEntry currentEntry = (SVNEntry) ents.next(); if ("".equals(currentEntry.getName())) { continue; } // if recursion is forced and entry is explicitly copied, skip it. if (forcedRecursion && currentEntry.isCopied() && currentEntry.getCopyFromURL() != null) { continue; } String currentCFURL = cfURL != null ? cfURL : copyFromURL; if (currentCFURL != null) { currentCFURL = SVNPathUtil.append(currentCFURL, SVNEncodingUtil.uriEncode(currentEntry.getName())); } String currentURL = currentEntry.getURL(); if (copyMode || entry.getURL() == null) { currentURL = SVNPathUtil.append(url, SVNEncodingUtil.uriEncode(currentEntry.getName())); } File currentFile = dir.getFile(currentEntry.getName()); SVNDirectory childDir; if (currentEntry.getKind() == SVNNodeKind.DIR) { childDir = dir.getChildDirectory(currentEntry.getName()); if (childDir == null) { SVNFileType currentType = SVNFileType.getType(currentFile); if (currentType == SVNFileType.NONE && currentEntry.isScheduledForDeletion()) { SVNCommitItem item = new SVNCommitItem(currentFile, SVNURL.parseURIEncoded(currentURL), null, currentEntry.getKind(), SVNRevision.UNDEFINED, false, true, false, false, false, false); item.setPath(SVNPathUtil.append(dir.getPath(), currentEntry.getName())); commitables.put(currentFile, item); continue; } SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_LOCKED, "Working copy ''{0}'' is missing or not locked", currentFile); SVNErrorManager.error(err); } } harvestCommitables(commitables, dir, currentFile, entry, currentEntry, currentURL, currentCFURL, copyMode, addsOnly, justLocked, lockTokens, true, forcedRecursion); } } if (lockTokens != null && entry.getKind() == SVNNodeKind.DIR && commitDeletion) { // harvest lock tokens for deleted items. collectLocks(dir, lockTokens); } }
diff --git a/zad3/src/main/BidMessageListenerImpl.java b/zad3/src/main/BidMessageListenerImpl.java index 25f0721..21efce6 100644 --- a/zad3/src/main/BidMessageListenerImpl.java +++ b/zad3/src/main/BidMessageListenerImpl.java @@ -1,52 +1,52 @@ package main; import java.io.ObjectInputStream; import java.util.Calendar; import interfaces.Publisher; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.ObjectMessage; public class BidMessageListenerImpl implements MessageListener { Publisher publisher; public BidMessageListenerImpl(Publisher publisher) { super(); this.publisher = publisher; } @Override public void onMessage(Message arg0) { Auction auction = null; ObjectMessage message = (ObjectMessage) arg0; try { auction = (Auction) message.getObject(); } catch (JMSException e) { e.printStackTrace(); } if (publisher.getAuctions().contains(auction)) { - synchronized(auction){ + synchronized(publisher.getAuctions()){ for (Auction setAuction : publisher.getAuctions()) { if (setAuction.equals(auction)) { if (setAuction.getPrice() < auction.getPrice() && setAuction.getEndTime().compareTo(Calendar.getInstance().getTime()) > 0) { setAuction.setPrice(auction.getPrice()); System.out.println("New highest bid in Your auction !:\n" + setAuction.printDescription()); publisher.newHighestBid(setAuction); }else{ // System.out.println("Received bid was too low or the auction is finished."); } break; } } } } } }
true
true
public void onMessage(Message arg0) { Auction auction = null; ObjectMessage message = (ObjectMessage) arg0; try { auction = (Auction) message.getObject(); } catch (JMSException e) { e.printStackTrace(); } if (publisher.getAuctions().contains(auction)) { synchronized(auction){ for (Auction setAuction : publisher.getAuctions()) { if (setAuction.equals(auction)) { if (setAuction.getPrice() < auction.getPrice() && setAuction.getEndTime().compareTo(Calendar.getInstance().getTime()) > 0) { setAuction.setPrice(auction.getPrice()); System.out.println("New highest bid in Your auction !:\n" + setAuction.printDescription()); publisher.newHighestBid(setAuction); }else{ // System.out.println("Received bid was too low or the auction is finished."); } break; } } } } }
public void onMessage(Message arg0) { Auction auction = null; ObjectMessage message = (ObjectMessage) arg0; try { auction = (Auction) message.getObject(); } catch (JMSException e) { e.printStackTrace(); } if (publisher.getAuctions().contains(auction)) { synchronized(publisher.getAuctions()){ for (Auction setAuction : publisher.getAuctions()) { if (setAuction.equals(auction)) { if (setAuction.getPrice() < auction.getPrice() && setAuction.getEndTime().compareTo(Calendar.getInstance().getTime()) > 0) { setAuction.setPrice(auction.getPrice()); System.out.println("New highest bid in Your auction !:\n" + setAuction.printDescription()); publisher.newHighestBid(setAuction); }else{ // System.out.println("Received bid was too low or the auction is finished."); } break; } } } } }
diff --git a/src/edu/cmu/ark/tool/QuestionAnswererTool.java b/src/edu/cmu/ark/tool/QuestionAnswererTool.java index 4d6cb4b..ae67e28 100644 --- a/src/edu/cmu/ark/tool/QuestionAnswererTool.java +++ b/src/edu/cmu/ark/tool/QuestionAnswererTool.java @@ -1,54 +1,55 @@ package edu.cmu.ark.tool; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Collection; import java.util.List; import edu.cmu.ark.AnalysisUtilities; import edu.cmu.ark.SuperSenseWrapper; import edu.stanford.nlp.trees.GrammaticalStructure; import edu.stanford.nlp.trees.GrammaticalStructureFactory; import edu.stanford.nlp.trees.PennTreebankLanguagePack; import edu.stanford.nlp.trees.Tree; import edu.stanford.nlp.trees.TreebankLanguagePack; import edu.stanford.nlp.trees.TypedDependency; public class QuestionAnswererTool extends BaseTool { public QuestionAnswererTool() throws FileNotFoundException, IOException { super(); } @Override public String getConfigPath() { return null; } @Override public void run() { String input = getDocumentFromStdin(); TreebankLanguagePack tlp = new PennTreebankLanguagePack(); GrammaticalStructureFactory gsf = tlp.grammaticalStructureFactory(); try { // Segment document into sentences - final List<String> sentences = AnalysisUtilities.getSentences(input); + final String[] sentences = input.split("\n"); // Parse individual sentences for (final String sentence : sentences) { - Tree parse = AnalysisUtilities.parseSentence(sentence).getTree(); + String clean_sentence = AnalysisUtilities.preprocess(sentence); + Tree parse = AnalysisUtilities.parseSentence(clean_sentence).getTree(); GrammaticalStructure gs = gsf.newGrammaticalStructure(parse); Collection<TypedDependency> tdl = gs.typedDependenciesCollapsed(); List<String> super_senses = SuperSenseWrapper.getInstance().annotateSentenceWithSupersenses(parse); - System.out.println(sentence); + System.out.println(clean_sentence); System.out.println(parse.labeledYield()); System.out.println(tdl); System.out.println(super_senses + "\n"); } } catch (final Exception e) { e.printStackTrace(); } } }
false
true
public void run() { String input = getDocumentFromStdin(); TreebankLanguagePack tlp = new PennTreebankLanguagePack(); GrammaticalStructureFactory gsf = tlp.grammaticalStructureFactory(); try { // Segment document into sentences final List<String> sentences = AnalysisUtilities.getSentences(input); // Parse individual sentences for (final String sentence : sentences) { Tree parse = AnalysisUtilities.parseSentence(sentence).getTree(); GrammaticalStructure gs = gsf.newGrammaticalStructure(parse); Collection<TypedDependency> tdl = gs.typedDependenciesCollapsed(); List<String> super_senses = SuperSenseWrapper.getInstance().annotateSentenceWithSupersenses(parse); System.out.println(sentence); System.out.println(parse.labeledYield()); System.out.println(tdl); System.out.println(super_senses + "\n"); } } catch (final Exception e) { e.printStackTrace(); } }
public void run() { String input = getDocumentFromStdin(); TreebankLanguagePack tlp = new PennTreebankLanguagePack(); GrammaticalStructureFactory gsf = tlp.grammaticalStructureFactory(); try { // Segment document into sentences final String[] sentences = input.split("\n"); // Parse individual sentences for (final String sentence : sentences) { String clean_sentence = AnalysisUtilities.preprocess(sentence); Tree parse = AnalysisUtilities.parseSentence(clean_sentence).getTree(); GrammaticalStructure gs = gsf.newGrammaticalStructure(parse); Collection<TypedDependency> tdl = gs.typedDependenciesCollapsed(); List<String> super_senses = SuperSenseWrapper.getInstance().annotateSentenceWithSupersenses(parse); System.out.println(clean_sentence); System.out.println(parse.labeledYield()); System.out.println(tdl); System.out.println(super_senses + "\n"); } } catch (final Exception e) { e.printStackTrace(); } }
diff --git a/common/src/main/java/de/escidoc/core/common/business/filter/SRURequest.java b/common/src/main/java/de/escidoc/core/common/business/filter/SRURequest.java index 45880a0fc..ce6e09dae 100644 --- a/common/src/main/java/de/escidoc/core/common/business/filter/SRURequest.java +++ b/common/src/main/java/de/escidoc/core/common/business/filter/SRURequest.java @@ -1,245 +1,248 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at license/ESCIDOC.LICENSE * or http://www.escidoc.de/license. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at license/ESCIDOC.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2006-2010 Fachinformationszentrum Karlsruhe Gesellschaft * fuer wissenschaftlich-technische Information mbH and Max-Planck- * Gesellschaft zur Foerderung der Wissenschaft e.V. * All rights reserved. Use is subject to license terms. */ package de.escidoc.core.common.business.filter; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.Writer; import java.net.URL; import java.net.URLEncoder; import java.util.EnumMap; import java.util.Map; import java.util.Map.Entry; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.cookie.Cookie; import org.apache.http.impl.cookie.BasicClientCookie; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import de.escidoc.core.common.business.Constants; import de.escidoc.core.common.business.fedora.resources.ResourceType; import de.escidoc.core.common.exceptions.system.WebserverSystemException; import de.escidoc.core.common.servlet.EscidocServlet; import de.escidoc.core.common.util.IOUtils; import de.escidoc.core.common.util.configuration.EscidocConfiguration; import de.escidoc.core.common.util.service.ConnectionUtility; import de.escidoc.core.common.util.service.UserContext; import de.escidoc.core.common.util.xml.XmlUtility; /** * Abstract super class for all types of SRU requests. * * @author André Schenk */ @Service("de.escidoc.core.common.business.filter.SRURequest") public class SRURequest { /** * Logging goes there. */ private static final Logger LOGGER = LoggerFactory.getLogger(SRURequest.class); // map from resource type to the corresponding admin index private static final Map<ResourceType, String> ADMIN_INDEXES = new EnumMap<ResourceType, String>(ResourceType.class); static { ADMIN_INDEXES.put(ResourceType.CONTAINER, "item_container_admin"); ADMIN_INDEXES.put(ResourceType.CONTENT_MODEL, "content_model_admin"); ADMIN_INDEXES.put(ResourceType.CONTENT_RELATION, "content_relation_admin"); ADMIN_INDEXES.put(ResourceType.CONTEXT, "context_admin"); ADMIN_INDEXES.put(ResourceType.ITEM, "item_container_admin"); ADMIN_INDEXES.put(ResourceType.OU, "ou_admin"); } @Autowired @Qualifier("escidoc.core.common.util.service.ConnectionUtility") private ConnectionUtility connectionUtility; /** * Protected constructor to prevent instantiation outside of the Spring-context. */ protected SRURequest() { } /** * Send an explain request to the SRW servlet and write the response to the given writer. The given resource type * determines the SRW index to use. * * @param output writer to which the SRW response is written * @param resourceType resource type for which "explain" will be called * @throws WebserverSystemException Thrown if the connection to the SRW servlet failed. */ public final void explain(final Writer output, final ResourceType resourceType) throws WebserverSystemException { try { final String url = EscidocConfiguration.getInstance().get(EscidocConfiguration.SRW_URL) + "/search/" + ADMIN_INDEXES.get(resourceType) + "?operation=explain&version=1.1"; final HttpResponse response = connectionUtility.getRequestURL(new URL(url), null); if (response != null) { final HttpEntity entity = response.getEntity(); BufferedReader input = null; try { input = new BufferedReader(new InputStreamReader(entity.getContent(), getCharset(entity .getContentType().getValue()))); String line; while ((line = input.readLine()) != null) { output.write(line); output.write('\n'); } } finally { IOUtils.closeStream(input); } } } catch (IOException e) { throw new WebserverSystemException(e); } } /** * Extract the charset information from the given content type header. * * @param contentType content type header * @return charset information */ private static String getCharset(final String contentType) { String result = XmlUtility.CHARACTER_ENCODING; if (contentType != null) { // FIXME better use javax.mail.internet.ContentType final String[] parameters = contentType.split(";"); for (final String parameter : parameters) { if (parameter.startsWith("charset")) { final String[] charset = parameter.split("="); if (charset.length > 1) { result = charset[1]; } break; } } } return result; } /** * Send a searchRetrieve request to the SRW servlet and write the response to the given writer. The given resource * type determines the SRW index to use. * * @param output Writer to which the SRW response is written. * @param resourceTypes Resource types to be expected in the SRW response. * @param parameters SRU request parameters * @throws WebserverSystemException Thrown if the connection to the SRW servlet failed. */ public final void searchRetrieve( final Writer output, final ResourceType[] resourceTypes, final SRURequestParameters parameters) throws WebserverSystemException { searchRetrieve(output, resourceTypes, parameters.getQuery(), parameters.getMaximumRecords(), parameters .getStartRecord(), parameters.getExtraData(), parameters.getRecordPacking()); } /** * Send a searchRetrieve request to the SRW servlet and write the response to the given writer. The given resource * type determines the SRW index to use. * * @param output Writer to which the SRW response is written. * @param resourceTypes Resource types to be expected in the SRW response. * @param query Contains a query expressed in CQL to be processed by the server. * @param limit The number of records requested to be returned. The value must be 0 or greater. Default * value if not supplied is determined by the server. The server MAY return less than this * number of records, for example if there are fewer matching records than requested, but MUST * NOT return more than this number of records. * @param offset The position within the sequence of matched records of the first record to be returned. The * first position in the sequence is 1. The value supplied MUST be greater than 0. * @param extraData map with additional parameters like user id, role id * @param recordPacking A string to determine how the record should be escaped in the response. Defined values are * 'string' and 'xml'. The default is 'xml'. * @throws WebserverSystemException Thrown if the connection to the SRW servlet failed. */ public final void searchRetrieve( final Writer output, final ResourceType[] resourceTypes, final String query, final int limit, final int offset, final Map<String, String> extraData, final RecordPacking recordPacking) throws WebserverSystemException { try { - String normalizedQuery = query.replaceAll("\\s+", " "); + String normalizedQuery = null; + if (query != null) { + normalizedQuery = query.replaceAll("\\s+", " "); + } FilterCqlDo filterCqlDo = new FilterCqlDo(normalizedQuery, resourceTypes); String url = EscidocConfiguration.getInstance().get(EscidocConfiguration.SRW_URL) + "/search/" + ADMIN_INDEXES.get(resourceTypes[0]) + '?' + Constants.SRU_PARAMETER_OPERATION + "=searchRetrieve&" + Constants.SRU_PARAMETER_VERSION + "=1.1&" + Constants.SRU_PARAMETER_QUERY + '=' + URLEncoder.encode(filterCqlDo.getTypedFilterQuery(), XmlUtility.CHARACTER_ENCODING); if (limit != LuceneRequestParameters.DEFAULT_MAXIMUM_RECORDS) { url += '&' + Constants.SRU_PARAMETER_MAXIMUM_RECORDS + '=' + limit; } if (offset != LuceneRequestParameters.DEFAULT_START_RECORD) { url += '&' + Constants.SRU_PARAMETER_START_RECORD + '=' + offset; } if (extraData != null) { final StringBuilder urlBuffer = new StringBuilder(url); for (final Entry<String, String> entry : extraData.entrySet()) { urlBuffer.append('&'); urlBuffer.append(entry.getKey()); urlBuffer.append('='); urlBuffer.append(entry.getValue()); } url = urlBuffer.toString(); } if (recordPacking != null) { url += '&' + Constants.SRU_PARAMETER_RECORD_PACKING + '=' + recordPacking.getType(); } LOGGER.info("SRW URL: " + url); final Cookie cookie = new BasicClientCookie(EscidocServlet.COOKIE_LOGIN, UserContext.getHandle()); output.write(connectionUtility.getRequestURLAsString(new URL(url), cookie)); } catch (IOException e) { throw new WebserverSystemException(e); } } /** * Set the connection utility. * * @param connectionUtility ConnectionUtility. */ public void setConnectionUtility(final ConnectionUtility connectionUtility) { this.connectionUtility = connectionUtility; } }
true
true
public final void searchRetrieve( final Writer output, final ResourceType[] resourceTypes, final String query, final int limit, final int offset, final Map<String, String> extraData, final RecordPacking recordPacking) throws WebserverSystemException { try { String normalizedQuery = query.replaceAll("\\s+", " "); FilterCqlDo filterCqlDo = new FilterCqlDo(normalizedQuery, resourceTypes); String url = EscidocConfiguration.getInstance().get(EscidocConfiguration.SRW_URL) + "/search/" + ADMIN_INDEXES.get(resourceTypes[0]) + '?' + Constants.SRU_PARAMETER_OPERATION + "=searchRetrieve&" + Constants.SRU_PARAMETER_VERSION + "=1.1&" + Constants.SRU_PARAMETER_QUERY + '=' + URLEncoder.encode(filterCqlDo.getTypedFilterQuery(), XmlUtility.CHARACTER_ENCODING); if (limit != LuceneRequestParameters.DEFAULT_MAXIMUM_RECORDS) { url += '&' + Constants.SRU_PARAMETER_MAXIMUM_RECORDS + '=' + limit; } if (offset != LuceneRequestParameters.DEFAULT_START_RECORD) { url += '&' + Constants.SRU_PARAMETER_START_RECORD + '=' + offset; } if (extraData != null) { final StringBuilder urlBuffer = new StringBuilder(url); for (final Entry<String, String> entry : extraData.entrySet()) { urlBuffer.append('&'); urlBuffer.append(entry.getKey()); urlBuffer.append('='); urlBuffer.append(entry.getValue()); } url = urlBuffer.toString(); } if (recordPacking != null) { url += '&' + Constants.SRU_PARAMETER_RECORD_PACKING + '=' + recordPacking.getType(); } LOGGER.info("SRW URL: " + url); final Cookie cookie = new BasicClientCookie(EscidocServlet.COOKIE_LOGIN, UserContext.getHandle()); output.write(connectionUtility.getRequestURLAsString(new URL(url), cookie)); } catch (IOException e) { throw new WebserverSystemException(e); } }
public final void searchRetrieve( final Writer output, final ResourceType[] resourceTypes, final String query, final int limit, final int offset, final Map<String, String> extraData, final RecordPacking recordPacking) throws WebserverSystemException { try { String normalizedQuery = null; if (query != null) { normalizedQuery = query.replaceAll("\\s+", " "); } FilterCqlDo filterCqlDo = new FilterCqlDo(normalizedQuery, resourceTypes); String url = EscidocConfiguration.getInstance().get(EscidocConfiguration.SRW_URL) + "/search/" + ADMIN_INDEXES.get(resourceTypes[0]) + '?' + Constants.SRU_PARAMETER_OPERATION + "=searchRetrieve&" + Constants.SRU_PARAMETER_VERSION + "=1.1&" + Constants.SRU_PARAMETER_QUERY + '=' + URLEncoder.encode(filterCqlDo.getTypedFilterQuery(), XmlUtility.CHARACTER_ENCODING); if (limit != LuceneRequestParameters.DEFAULT_MAXIMUM_RECORDS) { url += '&' + Constants.SRU_PARAMETER_MAXIMUM_RECORDS + '=' + limit; } if (offset != LuceneRequestParameters.DEFAULT_START_RECORD) { url += '&' + Constants.SRU_PARAMETER_START_RECORD + '=' + offset; } if (extraData != null) { final StringBuilder urlBuffer = new StringBuilder(url); for (final Entry<String, String> entry : extraData.entrySet()) { urlBuffer.append('&'); urlBuffer.append(entry.getKey()); urlBuffer.append('='); urlBuffer.append(entry.getValue()); } url = urlBuffer.toString(); } if (recordPacking != null) { url += '&' + Constants.SRU_PARAMETER_RECORD_PACKING + '=' + recordPacking.getType(); } LOGGER.info("SRW URL: " + url); final Cookie cookie = new BasicClientCookie(EscidocServlet.COOKIE_LOGIN, UserContext.getHandle()); output.write(connectionUtility.getRequestURLAsString(new URL(url), cookie)); } catch (IOException e) { throw new WebserverSystemException(e); } }
diff --git a/src/main/java/pl/agh/enrollme/service/PreferencesManagementService.java b/src/main/java/pl/agh/enrollme/service/PreferencesManagementService.java index 1639285..1edb406 100644 --- a/src/main/java/pl/agh/enrollme/service/PreferencesManagementService.java +++ b/src/main/java/pl/agh/enrollme/service/PreferencesManagementService.java @@ -1,260 +1,262 @@ package pl.agh.enrollme.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import pl.agh.enrollme.controller.preferencesmanagement.PreferencesManagementController; import pl.agh.enrollme.controller.preferencesmanagement.ProgressRingController; import pl.agh.enrollme.controller.preferencesmanagement.ScheduleController; import pl.agh.enrollme.model.*; import pl.agh.enrollme.repository.*; import pl.agh.enrollme.utils.EnrollmentMode; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Author: Piotr Turek */ @Service public class PreferencesManagementService implements IPreferencesManagementService { private final static Logger LOGGER = LoggerFactory.getLogger(PreferencesManagementService.class); @Autowired private IPersonDAO personDAO; @Autowired private ISubjectDAO subjectDAO; @Autowired private ITermDAO termDAO; @Autowired private IStudentPointsPerTermDAO pointsDAO; @Autowired private IEnrollmentDAO enrollDAO; @Autowired private PersonService personService; @Override @Transactional public ScheduleController createScheduleController(Enroll enroll) { final Person person = personService.getCurrentUser(); LOGGER.debug("Person: " + person + " retrieved from security context"); //Enroll configuration of the current enroll final EnrollConfiguration enrollConfiguration = enroll.getEnrollConfiguration(); LOGGER.debug("EnrollConfiguration: " + enrollConfiguration + " retrieved from enroll: " + enroll); final List<Subject> subjectsByEnrollment = subjectDAO.getSubjectsByEnrollment(enroll); LOGGER.debug("Subjects of " + enroll + " enrollment retrieved: " + subjectsByEnrollment); final List<Subject> personSubjects = subjectDAO.getSubjectsByPerson(person); LOGGER.debug("Subjects of " + person + " person retrieved: " + personSubjects); //list of subjects belonging to the currentEnrollment, choosen by person final List<Subject> subjects = new ArrayList<>(); for (Subject subject : personSubjects) { if (subjectsByEnrollment.contains(subject)) { subjects.add(subject); } } LOGGER.debug("Intersection found: " + subjects); //list of terms to display final List<Term> terms = new ArrayList<>(); for (Subject s : subjects) { final List<Term> termsBySubject = termDAO.getTermsBySubject(s); if (termsBySubject.size() > 0) { terms.addAll(termsBySubject); } } LOGGER.debug("Terms retrieved (" + terms.size() + " of them): " + terms); //list of currently assigned points final List<StudentPointsPerTerm> points = new ArrayList<>(); for (Term t : terms) { final StudentPointsPerTerm byPersonAndTerm = pointsDAO.getByPersonAndTerm(person, t); if (byPersonAndTerm != null) { points.add(byPersonAndTerm); } } LOGGER.debug("Current preferences retrieved (" + points.size() + " of them): " + points); //create missing point per terms so that every term has its sppt (they can be missing because it's the first //the user entered preferences-management or there were some zero-point sppt that didn't get persisted) createMissingSPPT(terms, points, person); LOGGER.debug("Missing point per terms created, there are " + points.size() + " in total."); //creating progress ring controller final ProgressRingController ringController = new ProgressRingController(enrollConfiguration, subjects, terms, points); LOGGER.debug("ProgressRingController created: " + ringController); //creating schedule controller final ScheduleController scheduleController = new ScheduleController(ringController, enrollConfiguration, subjects, terms, points); LOGGER.debug("ScheduleController created: " + scheduleController); return scheduleController; } @Override @Transactional public void saveScheduleController(Enroll currentEnroll, ScheduleController scheduleController) { currentEnroll = enrollDAO.getByPK(currentEnroll.getEnrollID()); //Importing enroll configuration final EnrollConfiguration enrollConfiguration = currentEnroll.getEnrollConfiguration(); if (currentEnroll.getEnrollmentMode() == EnrollmentMode.CLOSED || currentEnroll.getEnrollmentMode() == EnrollmentMode.COMPLETED) { FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN, "Enroll closed!", "Current enrollment has" + " either closed or completed. Unfortunatelly, saving is no longer possible. Contact ... someone ;)"); addMessage(message); LOGGER.debug("Save requested after enroll had been completed/closed!"); return; } //Importing subject/points map final Map<Integer, Integer> pointsMap = scheduleController.getProgressController().getPointsMap(); //Importing extra points used final int extraPointsUsed = scheduleController.getProgressController().getExtraPointsUsed(); //Importing point per terms final List<StudentPointsPerTerm> termPoints = scheduleController.getPoints(); //Validating if (!validateMinimumReached(pointsMap, enrollConfiguration)) { FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN, "Rule Broken!", "You have not reached minimum" + "rule for all subjects. Cannot save!"); addMessage(message); LOGGER.debug("Minimum rule broken!"); return; } LOGGER.debug("Points validated"); int addedCount = 0; int updatedCount = 0; int removedCount = 0; //Persisting points for (StudentPointsPerTerm tp : termPoints) { StudentPointsPerTerm termPoint; Term term; termPoint = pointsDAO.getByPK(tp.getId()); if (termPoint != null) { term = termPoint.getTerm(); } else { term = null; } //termPoint is not present in the database if (termPoint == null) { if (tp.getPoints() != 0) { pointsDAO.add(tp); LOGGER.debug("Term points: " + termPoint + " added to the datebase"); addedCount++; } else { LOGGER.debug("Term points: " + termPoint + " not present in the datebase, but zero-point"); } } else if (!termPoint.getAssigned() && !term.getCertain()) { //is present in the database and isn't assigned yet and corresponding term isn't certain if (termPoint.getPoints() == 0) { pointsDAO.remove(termPoint); LOGGER.debug("Term points: " + termPoint + " removed from the datebase"); removedCount++; } else { + termPoint.setPoints(tp.getPoints()); + termPoint.setReason(tp.getReason()); pointsDAO.update(termPoint); LOGGER.debug("Term points: " + termPoint + " updated in the datebase"); updatedCount++; } } } LOGGER.debug("Points persisted"); final Person person = personService.getCurrentUser(); LOGGER.debug("Current person retrieved"); final List<Subject> subjects = person.getSubjects(); final List<Subject> subjectsSaved = person.getSubjectsSaved(); for (Subject subject : subjects) { if (subject.getHasInteractive() && !subjectsSaved.contains(subject)) { subjectsSaved.add(subject); LOGGER.debug("Subject: " + subject + " added to persons: " + person + " saved subjects list"); } } LOGGER.debug("Saved subjects updated"); personDAO.update(person); LOGGER.debug("Person: " + person + " updated"); FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Choice updated", "Changes successfully saved. " + addedCount + " term points have been added, " + updatedCount + " updated, " + removedCount + " removed from the datebase"); addMessage(message); LOGGER.debug("Saving finished"); } /** * Validates if minimum point usage has been reached for all subjects */ private boolean validateMinimumReached(Map<Integer, Integer> pointsMap, EnrollConfiguration enrollConfiguration) { final Integer minimumPointsPerSubject = enrollConfiguration.getMinimumPointsPerSubject(); for (Integer used : pointsMap.values()) { if (used != null && used < minimumPointsPerSubject) { LOGGER.debug("Minimum rule has not been reached!"); return false; } } LOGGER.debug("Points validated correctly"); return true; } /** * Creates missing SPPTs */ private void createMissingSPPT(List<Term> terms, List<StudentPointsPerTerm> points, Person person) { Map<Term, Boolean> termsPresent = new HashMap<Term, Boolean>(); for (StudentPointsPerTerm sppt : points) { final Term term = sppt.getTerm(); termsPresent.put(term, true); LOGGER.debug("Term: " + term + " has points"); } for (Term term : terms) { Boolean hasPoints = termsPresent.get(term); if (hasPoints == null || hasPoints == false) { points.add(new StudentPointsPerTerm(term, person, 0, "", false)); LOGGER.debug("Points created for term: " + term); } } } private void addMessage(FacesMessage message) { FacesContext.getCurrentInstance().addMessage(null, message); } }
true
true
public void saveScheduleController(Enroll currentEnroll, ScheduleController scheduleController) { currentEnroll = enrollDAO.getByPK(currentEnroll.getEnrollID()); //Importing enroll configuration final EnrollConfiguration enrollConfiguration = currentEnroll.getEnrollConfiguration(); if (currentEnroll.getEnrollmentMode() == EnrollmentMode.CLOSED || currentEnroll.getEnrollmentMode() == EnrollmentMode.COMPLETED) { FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN, "Enroll closed!", "Current enrollment has" + " either closed or completed. Unfortunatelly, saving is no longer possible. Contact ... someone ;)"); addMessage(message); LOGGER.debug("Save requested after enroll had been completed/closed!"); return; } //Importing subject/points map final Map<Integer, Integer> pointsMap = scheduleController.getProgressController().getPointsMap(); //Importing extra points used final int extraPointsUsed = scheduleController.getProgressController().getExtraPointsUsed(); //Importing point per terms final List<StudentPointsPerTerm> termPoints = scheduleController.getPoints(); //Validating if (!validateMinimumReached(pointsMap, enrollConfiguration)) { FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN, "Rule Broken!", "You have not reached minimum" + "rule for all subjects. Cannot save!"); addMessage(message); LOGGER.debug("Minimum rule broken!"); return; } LOGGER.debug("Points validated"); int addedCount = 0; int updatedCount = 0; int removedCount = 0; //Persisting points for (StudentPointsPerTerm tp : termPoints) { StudentPointsPerTerm termPoint; Term term; termPoint = pointsDAO.getByPK(tp.getId()); if (termPoint != null) { term = termPoint.getTerm(); } else { term = null; } //termPoint is not present in the database if (termPoint == null) { if (tp.getPoints() != 0) { pointsDAO.add(tp); LOGGER.debug("Term points: " + termPoint + " added to the datebase"); addedCount++; } else { LOGGER.debug("Term points: " + termPoint + " not present in the datebase, but zero-point"); } } else if (!termPoint.getAssigned() && !term.getCertain()) { //is present in the database and isn't assigned yet and corresponding term isn't certain if (termPoint.getPoints() == 0) { pointsDAO.remove(termPoint); LOGGER.debug("Term points: " + termPoint + " removed from the datebase"); removedCount++; } else { pointsDAO.update(termPoint); LOGGER.debug("Term points: " + termPoint + " updated in the datebase"); updatedCount++; } } } LOGGER.debug("Points persisted"); final Person person = personService.getCurrentUser(); LOGGER.debug("Current person retrieved"); final List<Subject> subjects = person.getSubjects(); final List<Subject> subjectsSaved = person.getSubjectsSaved(); for (Subject subject : subjects) { if (subject.getHasInteractive() && !subjectsSaved.contains(subject)) { subjectsSaved.add(subject); LOGGER.debug("Subject: " + subject + " added to persons: " + person + " saved subjects list"); } } LOGGER.debug("Saved subjects updated"); personDAO.update(person); LOGGER.debug("Person: " + person + " updated"); FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Choice updated", "Changes successfully saved. " + addedCount + " term points have been added, " + updatedCount + " updated, " + removedCount + " removed from the datebase"); addMessage(message); LOGGER.debug("Saving finished"); }
public void saveScheduleController(Enroll currentEnroll, ScheduleController scheduleController) { currentEnroll = enrollDAO.getByPK(currentEnroll.getEnrollID()); //Importing enroll configuration final EnrollConfiguration enrollConfiguration = currentEnroll.getEnrollConfiguration(); if (currentEnroll.getEnrollmentMode() == EnrollmentMode.CLOSED || currentEnroll.getEnrollmentMode() == EnrollmentMode.COMPLETED) { FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN, "Enroll closed!", "Current enrollment has" + " either closed or completed. Unfortunatelly, saving is no longer possible. Contact ... someone ;)"); addMessage(message); LOGGER.debug("Save requested after enroll had been completed/closed!"); return; } //Importing subject/points map final Map<Integer, Integer> pointsMap = scheduleController.getProgressController().getPointsMap(); //Importing extra points used final int extraPointsUsed = scheduleController.getProgressController().getExtraPointsUsed(); //Importing point per terms final List<StudentPointsPerTerm> termPoints = scheduleController.getPoints(); //Validating if (!validateMinimumReached(pointsMap, enrollConfiguration)) { FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN, "Rule Broken!", "You have not reached minimum" + "rule for all subjects. Cannot save!"); addMessage(message); LOGGER.debug("Minimum rule broken!"); return; } LOGGER.debug("Points validated"); int addedCount = 0; int updatedCount = 0; int removedCount = 0; //Persisting points for (StudentPointsPerTerm tp : termPoints) { StudentPointsPerTerm termPoint; Term term; termPoint = pointsDAO.getByPK(tp.getId()); if (termPoint != null) { term = termPoint.getTerm(); } else { term = null; } //termPoint is not present in the database if (termPoint == null) { if (tp.getPoints() != 0) { pointsDAO.add(tp); LOGGER.debug("Term points: " + termPoint + " added to the datebase"); addedCount++; } else { LOGGER.debug("Term points: " + termPoint + " not present in the datebase, but zero-point"); } } else if (!termPoint.getAssigned() && !term.getCertain()) { //is present in the database and isn't assigned yet and corresponding term isn't certain if (termPoint.getPoints() == 0) { pointsDAO.remove(termPoint); LOGGER.debug("Term points: " + termPoint + " removed from the datebase"); removedCount++; } else { termPoint.setPoints(tp.getPoints()); termPoint.setReason(tp.getReason()); pointsDAO.update(termPoint); LOGGER.debug("Term points: " + termPoint + " updated in the datebase"); updatedCount++; } } } LOGGER.debug("Points persisted"); final Person person = personService.getCurrentUser(); LOGGER.debug("Current person retrieved"); final List<Subject> subjects = person.getSubjects(); final List<Subject> subjectsSaved = person.getSubjectsSaved(); for (Subject subject : subjects) { if (subject.getHasInteractive() && !subjectsSaved.contains(subject)) { subjectsSaved.add(subject); LOGGER.debug("Subject: " + subject + " added to persons: " + person + " saved subjects list"); } } LOGGER.debug("Saved subjects updated"); personDAO.update(person); LOGGER.debug("Person: " + person + " updated"); FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Choice updated", "Changes successfully saved. " + addedCount + " term points have been added, " + updatedCount + " updated, " + removedCount + " removed from the datebase"); addMessage(message); LOGGER.debug("Saving finished"); }
diff --git a/maven-scm-providers/maven-scm-providers-cvs/maven-scm-provider-cvs-commons/src/main/java/org/apache/maven/scm/provider/cvslib/command/login/CvsPass.java b/maven-scm-providers/maven-scm-providers-cvs/maven-scm-provider-cvs-commons/src/main/java/org/apache/maven/scm/provider/cvslib/command/login/CvsPass.java index 38792c41..4da619bc 100644 --- a/maven-scm-providers/maven-scm-providers-cvs/maven-scm-provider-cvs-commons/src/main/java/org/apache/maven/scm/provider/cvslib/command/login/CvsPass.java +++ b/maven-scm-providers/maven-scm-providers-cvs/maven-scm-provider-cvs-commons/src/main/java/org/apache/maven/scm/provider/cvslib/command/login/CvsPass.java @@ -1,202 +1,202 @@ package org.apache.maven.scm.provider.cvslib.command.login; /* * Copyright 2001-2006 The Apache Software Foundation. * * 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. */ import org.apache.maven.scm.ScmException; import org.apache.maven.scm.log.ScmLogger; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; /** * Adds an new entry to a CVS password file. * * @version $Id$ * @todo Update this class for support password storage in cvsnt. CVSNT use the windows registry, so, we need a jni * tool for access to the windows registry */ public class CvsPass { /** * CVS Root */ private String cvsRoot = null; /** * Password file to add password to */ private File passFile = null; /** * Password to add to file */ private String password = null; private ScmLogger logger; /** * Array contain char conversion data */ private final char[] shifts = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 114, 120, 53, 79, 96, 109, 72, 108, 70, 64, 76, 67, 116, 74, 68, 87, 111, 52, 75, 119, 49, 34, 82, 81, 95, 65, 112, 86, 118, 110, 122, 105, 41, 57, 83, 43, 46, 102, 40, 89, 38, 103, 45, 50, 42, 123, 91, 35, 125, 55, 54, 66, 124, 126, 59, 47, 92, 71, 115, 78, 88, 107, 106, 56, 36, 121, 117, 104, 101, 100, 69, 73, 99, 63, 94, 93, 39, 37, 61, 48, 58, 113, 32, 90, 44, 98, 60, 51, 33, 97, 62, 77, 84, 80, 85, 223, 225, 216, 187, 166, 229, 189, 222, 188, 141, 249, 148, 200, 184, 136, 248, 190, 199, 170, 181, 204, 138, 232, 218, 183, 255, 234, 220, 247, 213, 203, 226, 193, 174, 172, 228, 252, 217, 201, 131, 230, 197, 211, 145, 238, 161, 179, 160, 212, 207, 221, 254, 173, 202, 146, 224, 151, 140, 196, 205, 130, 135, 133, 143, 246, 192, 159, 244, 239, 185, 168, 215, 144, 139, 165, 180, 157, 147, 186, 214, 176, 227, 231, 219, 169, 175, 156, 206, 198, 129, 164, 150, 210, 154, 177, 134, 127, 182, 128, 158, 208, 162, 132, 167, 209, 149, 241, 153, 251, 237, 236, 171, 195, 243, 233, 253, 240, 194, 250, 191, 155, 142, 137, 245, 235, 163, 242, 178, 152}; /** * Create a CVS task using the default cvspass file location. */ public CvsPass( ScmLogger logger ) { passFile = new File( System.getProperty( "cygwin.user.home", System.getProperty( "user.home" ) ) + File .separatorChar + ".cvspass" ); this.logger = logger; } /** * Does the work. * * @throws ScmException if something is missing * @throws IOException if something goes wrong */ public final void execute() throws ScmException, IOException { if ( cvsRoot == null ) { throw new ScmException( "cvsroot is required" ); } logger.debug( "cvsRoot: " + cvsRoot ); logger.debug( "passFile: " + passFile ); BufferedReader reader = null; PrintWriter writer = null; try { StringBuffer buf = new StringBuffer(); if ( passFile.exists() ) { reader = new BufferedReader( new FileReader( passFile ) ); String line = null; while ( ( line = reader.readLine() ) != null ) { if ( !line.startsWith( cvsRoot ) && !line.startsWith( "/1 " + cvsRoot ) ) { buf.append( line ).append( "\n" ); } else { logger.debug( "cvsroot " + cvsRoot + " already exist in " + passFile.getAbsolutePath() + ". SKIPPED." ); return; } } } if ( password == null ) { - throw new ScmException( "password is required" ); + throw new ScmException( "password is required. You must run a 'cvs -d " + cvsRoot + " login' first." ); } //logger.debug( "password: " + password ); String pwdfile = buf.toString() + "/1 " + cvsRoot + " A" + mangle( password ); logger.debug( "Writing -> " + pwdfile ); writer = new PrintWriter( new FileWriter( passFile ) ); writer.println( pwdfile ); } finally { if ( reader != null ) { try { reader.close(); } catch ( IOException e ) { // ignore } } if ( writer != null ) { writer.close(); } } } private final String mangle( String password ) { StringBuffer buf = new StringBuffer(); for ( int i = 0; i < password.length(); i++ ) { buf.append( shifts[password.charAt( i )] ); } return buf.toString(); } /** * The CVS repository to add an entry for. * * @param cvsRoot the CVS repository */ public void setCvsroot( String cvsRoot ) { this.cvsRoot = cvsRoot; } /** * Password file to add the entry to. * * @param passFile the password file. */ public void setPassfile( File passFile ) { this.passFile = passFile; } /** * Password to be added to the password file. * * @param password the password. */ public void setPassword( String password ) { this.password = password; } }
true
true
public final void execute() throws ScmException, IOException { if ( cvsRoot == null ) { throw new ScmException( "cvsroot is required" ); } logger.debug( "cvsRoot: " + cvsRoot ); logger.debug( "passFile: " + passFile ); BufferedReader reader = null; PrintWriter writer = null; try { StringBuffer buf = new StringBuffer(); if ( passFile.exists() ) { reader = new BufferedReader( new FileReader( passFile ) ); String line = null; while ( ( line = reader.readLine() ) != null ) { if ( !line.startsWith( cvsRoot ) && !line.startsWith( "/1 " + cvsRoot ) ) { buf.append( line ).append( "\n" ); } else { logger.debug( "cvsroot " + cvsRoot + " already exist in " + passFile.getAbsolutePath() + ". SKIPPED." ); return; } } } if ( password == null ) { throw new ScmException( "password is required" ); } //logger.debug( "password: " + password ); String pwdfile = buf.toString() + "/1 " + cvsRoot + " A" + mangle( password ); logger.debug( "Writing -> " + pwdfile ); writer = new PrintWriter( new FileWriter( passFile ) ); writer.println( pwdfile ); } finally { if ( reader != null ) { try { reader.close(); } catch ( IOException e ) { // ignore } } if ( writer != null ) { writer.close(); } } }
public final void execute() throws ScmException, IOException { if ( cvsRoot == null ) { throw new ScmException( "cvsroot is required" ); } logger.debug( "cvsRoot: " + cvsRoot ); logger.debug( "passFile: " + passFile ); BufferedReader reader = null; PrintWriter writer = null; try { StringBuffer buf = new StringBuffer(); if ( passFile.exists() ) { reader = new BufferedReader( new FileReader( passFile ) ); String line = null; while ( ( line = reader.readLine() ) != null ) { if ( !line.startsWith( cvsRoot ) && !line.startsWith( "/1 " + cvsRoot ) ) { buf.append( line ).append( "\n" ); } else { logger.debug( "cvsroot " + cvsRoot + " already exist in " + passFile.getAbsolutePath() + ". SKIPPED." ); return; } } } if ( password == null ) { throw new ScmException( "password is required. You must run a 'cvs -d " + cvsRoot + " login' first." ); } //logger.debug( "password: " + password ); String pwdfile = buf.toString() + "/1 " + cvsRoot + " A" + mangle( password ); logger.debug( "Writing -> " + pwdfile ); writer = new PrintWriter( new FileWriter( passFile ) ); writer.println( pwdfile ); } finally { if ( reader != null ) { try { reader.close(); } catch ( IOException e ) { // ignore } } if ( writer != null ) { writer.close(); } } }
diff --git a/modules/activiti-engine-test-cfg/src/test/java/org/activiti/test/db/ProcessEngineInitializationTest.java b/modules/activiti-engine-test-cfg/src/test/java/org/activiti/test/db/ProcessEngineInitializationTest.java index cc595aaa..9503a604 100644 --- a/modules/activiti-engine-test-cfg/src/test/java/org/activiti/test/db/ProcessEngineInitializationTest.java +++ b/modules/activiti-engine-test-cfg/src/test/java/org/activiti/test/db/ProcessEngineInitializationTest.java @@ -1,107 +1,107 @@ /* 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.activiti.test.db; import java.util.HashMap; import java.util.Map; import org.activiti.ActivitiException; import org.activiti.ActivitiWrongDbException; import org.activiti.DbProcessEngineBuilder; import org.activiti.DbSchemaStrategy; import org.activiti.ProcessEngine; import org.activiti.impl.ProcessEngineImpl; import org.activiti.impl.persistence.IbatisPersistenceSessionFactory; import org.activiti.impl.persistence.PersistenceSessionFactory; import org.activiti.test.LogInitializer; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.hamcrest.Description; import org.junit.Rule; import org.junit.Test; import org.junit.internal.matchers.TypeSafeMatcher; import org.junit.rules.ExpectedException; /** * @author Tom Baeyens */ public class ProcessEngineInitializationTest { @Rule public ExpectedException exception = ExpectedException.none(); @Rule public LogInitializer logInitializer = new LogInitializer(); @Test public void testNoTables() { exception.expect(ActivitiException.class); exception.expectMessage("no activiti tables in db. set property db.schema.strategy=create-drop in activiti.properties for automatic schema creation"); new DbProcessEngineBuilder().configureFromPropertiesResource("org/activiti/test/db/activiti.properties").buildProcessEngine(); } @Test public void testVersionMismatch() { // first create the schema ProcessEngineImpl processEngine = (ProcessEngineImpl) new DbProcessEngineBuilder().configureFromPropertiesResource( - "org/activiti/test/db/activiti.properties").setDbSchemaStrategy(DbSchemaStrategy.CREATE_DROP).buildProcessEngine(); + "org/activiti/test/db/activiti.properties").setDbSchemaStrategy(DbSchemaStrategy.DROP_CREATE).buildProcessEngine(); // then update the version to something that is different to the library // version PersistenceSessionFactory persistenceSessionFactory = processEngine.getPersistenceSessionFactory(); SqlSessionFactory sqlSessionFactory = ((IbatisPersistenceSessionFactory) persistenceSessionFactory).getSqlSessionFactory(); SqlSession sqlSession = sqlSessionFactory.openSession(); boolean success = false; try { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("name", "schema.version"); parameters.put("value", "25.7"); parameters.put("revision", new Integer(1)); parameters.put("newRevision", new Integer(2)); sqlSession.update("updateProperty", parameters); success = true; } catch (Exception e) { throw new ActivitiException("couldn't update db schema version", e); } finally { if (success) { sqlSession.commit(true); } else { sqlSession.rollback(true); } sqlSession.close(); } exception.expect(ActivitiWrongDbException.class); exception.expect(new TypeSafeMatcher<ActivitiWrongDbException>() { @Override public boolean matchesSafely(ActivitiWrongDbException e) { return e.getMessage().contains("version mismatch") && "25.7".equals(e.getDbVersion()) && ProcessEngine.VERSION == e.getLibraryVersion(); } public void describeTo(Description description) { description.appendText("'version mismatch' with dbVersion=25.7 and libraryVersion=").appendValue(ProcessEngine.VERSION); } }); // now we can see what happens if when a process engine is being // build with a version mismatch between library and db tables new DbProcessEngineBuilder().configureFromPropertiesResource("org/activiti/test/db/activiti.properties") .setDbSchemaStrategy(DbSchemaStrategy.CHECK_VERSION).buildProcessEngine(); // closing the original process engine to drop the db tables processEngine.close(); } }
true
true
public void testVersionMismatch() { // first create the schema ProcessEngineImpl processEngine = (ProcessEngineImpl) new DbProcessEngineBuilder().configureFromPropertiesResource( "org/activiti/test/db/activiti.properties").setDbSchemaStrategy(DbSchemaStrategy.CREATE_DROP).buildProcessEngine(); // then update the version to something that is different to the library // version PersistenceSessionFactory persistenceSessionFactory = processEngine.getPersistenceSessionFactory(); SqlSessionFactory sqlSessionFactory = ((IbatisPersistenceSessionFactory) persistenceSessionFactory).getSqlSessionFactory(); SqlSession sqlSession = sqlSessionFactory.openSession(); boolean success = false; try { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("name", "schema.version"); parameters.put("value", "25.7"); parameters.put("revision", new Integer(1)); parameters.put("newRevision", new Integer(2)); sqlSession.update("updateProperty", parameters); success = true; } catch (Exception e) { throw new ActivitiException("couldn't update db schema version", e); } finally { if (success) { sqlSession.commit(true); } else { sqlSession.rollback(true); } sqlSession.close(); } exception.expect(ActivitiWrongDbException.class); exception.expect(new TypeSafeMatcher<ActivitiWrongDbException>() { @Override public boolean matchesSafely(ActivitiWrongDbException e) { return e.getMessage().contains("version mismatch") && "25.7".equals(e.getDbVersion()) && ProcessEngine.VERSION == e.getLibraryVersion(); } public void describeTo(Description description) { description.appendText("'version mismatch' with dbVersion=25.7 and libraryVersion=").appendValue(ProcessEngine.VERSION); } }); // now we can see what happens if when a process engine is being // build with a version mismatch between library and db tables new DbProcessEngineBuilder().configureFromPropertiesResource("org/activiti/test/db/activiti.properties") .setDbSchemaStrategy(DbSchemaStrategy.CHECK_VERSION).buildProcessEngine(); // closing the original process engine to drop the db tables processEngine.close(); }
public void testVersionMismatch() { // first create the schema ProcessEngineImpl processEngine = (ProcessEngineImpl) new DbProcessEngineBuilder().configureFromPropertiesResource( "org/activiti/test/db/activiti.properties").setDbSchemaStrategy(DbSchemaStrategy.DROP_CREATE).buildProcessEngine(); // then update the version to something that is different to the library // version PersistenceSessionFactory persistenceSessionFactory = processEngine.getPersistenceSessionFactory(); SqlSessionFactory sqlSessionFactory = ((IbatisPersistenceSessionFactory) persistenceSessionFactory).getSqlSessionFactory(); SqlSession sqlSession = sqlSessionFactory.openSession(); boolean success = false; try { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("name", "schema.version"); parameters.put("value", "25.7"); parameters.put("revision", new Integer(1)); parameters.put("newRevision", new Integer(2)); sqlSession.update("updateProperty", parameters); success = true; } catch (Exception e) { throw new ActivitiException("couldn't update db schema version", e); } finally { if (success) { sqlSession.commit(true); } else { sqlSession.rollback(true); } sqlSession.close(); } exception.expect(ActivitiWrongDbException.class); exception.expect(new TypeSafeMatcher<ActivitiWrongDbException>() { @Override public boolean matchesSafely(ActivitiWrongDbException e) { return e.getMessage().contains("version mismatch") && "25.7".equals(e.getDbVersion()) && ProcessEngine.VERSION == e.getLibraryVersion(); } public void describeTo(Description description) { description.appendText("'version mismatch' with dbVersion=25.7 and libraryVersion=").appendValue(ProcessEngine.VERSION); } }); // now we can see what happens if when a process engine is being // build with a version mismatch between library and db tables new DbProcessEngineBuilder().configureFromPropertiesResource("org/activiti/test/db/activiti.properties") .setDbSchemaStrategy(DbSchemaStrategy.CHECK_VERSION).buildProcessEngine(); // closing the original process engine to drop the db tables processEngine.close(); }
diff --git a/core/src/com/google/zxing/qrcode/decoder/DecodedBitStreamParser.java b/core/src/com/google/zxing/qrcode/decoder/DecodedBitStreamParser.java index b6efa2b2..aee1b943 100644 --- a/core/src/com/google/zxing/qrcode/decoder/DecodedBitStreamParser.java +++ b/core/src/com/google/zxing/qrcode/decoder/DecodedBitStreamParser.java @@ -1,351 +1,351 @@ /* * Copyright 2007 ZXing 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.google.zxing.qrcode.decoder; import com.google.zxing.ReaderException; import com.google.zxing.common.BitSource; import com.google.zxing.common.CharacterSetECI; import com.google.zxing.common.DecoderResult; import java.io.UnsupportedEncodingException; import java.util.Vector; /** * <p>QR Codes can encode text as bits in one of several modes, and can use multiple modes * in one QR Code. This class decodes the bits back into text.</p> * * <p>See ISO 18004:2006, 6.4.3 - 6.4.7</p> * * @author Sean Owen */ final class DecodedBitStreamParser { /** * See ISO 18004:2006, 6.4.4 Table 5 */ private static final char[] ALPHANUMERIC_CHARS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ' ', '$', '%', '*', '+', '-', '.', '/', ':' }; private static final String SHIFT_JIS = "SJIS"; private static final String EUC_JP = "EUC_JP"; private static final boolean ASSUME_SHIFT_JIS; private static final String UTF8 = "UTF8"; private static final String ISO88591 = "ISO8859_1"; static { String platformDefault = System.getProperty("file.encoding"); ASSUME_SHIFT_JIS = SHIFT_JIS.equalsIgnoreCase(platformDefault) || EUC_JP.equalsIgnoreCase(platformDefault); } private DecodedBitStreamParser() { } static DecoderResult decode(byte[] bytes, Version version, ErrorCorrectionLevel ecLevel) throws ReaderException { BitSource bits = new BitSource(bytes); StringBuffer result = new StringBuffer(); CharacterSetECI currentCharacterSetECI = null; boolean fc1InEffect = false; Vector byteSegments = new Vector(1); Mode mode; do { // While still another segment to read... if (bits.available() < 4) { // OK, assume we're done. Really, a TERMINATOR mode should have been recorded here mode = Mode.TERMINATOR; } else { try { mode = Mode.forBits(bits.readBits(4)); // mode is encoded by 4 bits } catch (IllegalArgumentException iae) { throw ReaderException.getInstance(); } } if (!mode.equals(Mode.TERMINATOR)) { if (mode.equals(Mode.FNC1_FIRST_POSITION) || mode.equals(Mode.FNC1_SECOND_POSITION)) { // We do little with FNC1 except alter the parsed result a bit according to the spec fc1InEffect = true; } else if (mode.equals(Mode.STRUCTURED_APPEND)) { // not really supported; all we do is ignore it // Read next 8 bits (symbol sequence #) and 8 bits (parity data), then continue bits.readBits(16); } else if (mode.equals(Mode.ECI)) { // Count doesn't apply to ECI int value = parseECIValue(bits); currentCharacterSetECI = CharacterSetECI.getCharacterSetECIByValue(value); if (currentCharacterSetECI == null) { throw ReaderException.getInstance(); } } else { // How many characters will follow, encoded in this mode? int count = bits.readBits(mode.getCharacterCountBits(version)); if (mode.equals(Mode.NUMERIC)) { decodeNumericSegment(bits, result, count); } else if (mode.equals(Mode.ALPHANUMERIC)) { decodeAlphanumericSegment(bits, result, count, fc1InEffect); } else if (mode.equals(Mode.BYTE)) { decodeByteSegment(bits, result, count, currentCharacterSetECI, byteSegments); } else if (mode.equals(Mode.KANJI)) { decodeKanjiSegment(bits, result, count); } else { throw ReaderException.getInstance(); } } } } while (!mode.equals(Mode.TERMINATOR)); return new DecoderResult(bytes, result.toString(), byteSegments.isEmpty() ? null : byteSegments, ecLevel); } private static void decodeKanjiSegment(BitSource bits, StringBuffer result, int count) throws ReaderException { // Each character will require 2 bytes. Read the characters as 2-byte pairs // and decode as Shift_JIS afterwards byte[] buffer = new byte[2 * count]; int offset = 0; while (count > 0) { // Each 13 bits encodes a 2-byte character int twoBytes = bits.readBits(13); int assembledTwoBytes = ((twoBytes / 0x0C0) << 8) | (twoBytes % 0x0C0); if (assembledTwoBytes < 0x01F00) { // In the 0x8140 to 0x9FFC range assembledTwoBytes += 0x08140; } else { // In the 0xE040 to 0xEBBF range assembledTwoBytes += 0x0C140; } buffer[offset] = (byte) (assembledTwoBytes >> 8); buffer[offset + 1] = (byte) assembledTwoBytes; offset += 2; count--; } // Shift_JIS may not be supported in some environments: try { result.append(new String(buffer, SHIFT_JIS)); } catch (UnsupportedEncodingException uee) { throw ReaderException.getInstance(); } } private static void decodeByteSegment(BitSource bits, StringBuffer result, int count, CharacterSetECI currentCharacterSetECI, Vector byteSegments) throws ReaderException { byte[] readBytes = new byte[count]; if (count << 3 > bits.available()) { throw ReaderException.getInstance(); } for (int i = 0; i < count; i++) { readBytes[i] = (byte) bits.readBits(8); } String encoding; if (currentCharacterSetECI == null) { // The spec isn't clear on this mode; see // section 6.4.5: t does not say which encoding to assuming // upon decoding. I have seen ISO-8859-1 used as well as // Shift_JIS -- without anything like an ECI designator to // give a hint. encoding = guessEncoding(readBytes); } else { encoding = currentCharacterSetECI.getEncodingName(); } try { result.append(new String(readBytes, encoding)); } catch (UnsupportedEncodingException uce) { throw ReaderException.getInstance(); } byteSegments.addElement(readBytes); } private static void decodeAlphanumericSegment(BitSource bits, StringBuffer result, int count, boolean fc1InEffect) { // Read two characters at a time int start = result.length(); while (count > 1) { int nextTwoCharsBits = bits.readBits(11); result.append(ALPHANUMERIC_CHARS[nextTwoCharsBits / 45]); result.append(ALPHANUMERIC_CHARS[nextTwoCharsBits % 45]); count -= 2; } if (count == 1) { // special case: one character left result.append(ALPHANUMERIC_CHARS[bits.readBits(6)]); } // See section 6.4.8.1, 6.4.8.2 if (fc1InEffect) { // We need to massage the result a bit if in an FNC1 mode: for (int i = start; i < result.length(); i++) { if (result.charAt(i) == '%') { if (i < result.length() - 1 && result.charAt(i + 1) == '%') { // %% is rendered as % result.deleteCharAt(i + 1); } else { // In alpha mode, % should be converted to FNC1 separator 0x1D result.setCharAt(i, (char) 0x1D); } } } } } private static void decodeNumericSegment(BitSource bits, StringBuffer result, int count) throws ReaderException { // Read three digits at a time while (count >= 3) { // Each 10 bits encodes three digits int threeDigitsBits = bits.readBits(10); if (threeDigitsBits >= 1000) { throw ReaderException.getInstance(); } result.append(ALPHANUMERIC_CHARS[threeDigitsBits / 100]); result.append(ALPHANUMERIC_CHARS[(threeDigitsBits / 10) % 10]); result.append(ALPHANUMERIC_CHARS[threeDigitsBits % 10]); count -= 3; } if (count == 2) { // Two digits left over to read, encoded in 7 bits int twoDigitsBits = bits.readBits(7); if (twoDigitsBits >= 100) { throw ReaderException.getInstance(); } result.append(ALPHANUMERIC_CHARS[twoDigitsBits / 10]); result.append(ALPHANUMERIC_CHARS[twoDigitsBits % 10]); } else if (count == 1) { // One digit left over to read int digitBits = bits.readBits(4); if (digitBits >= 10) { throw ReaderException.getInstance(); } result.append(ALPHANUMERIC_CHARS[digitBits]); } } private static String guessEncoding(byte[] bytes) { if (ASSUME_SHIFT_JIS) { return SHIFT_JIS; } // Does it start with the UTF-8 byte order mark? then guess it's UTF-8 if (bytes.length > 3 && bytes[0] == (byte) 0xEF && bytes[1] == (byte) 0xBB && bytes[2] == (byte) 0xBF) { return UTF8; } // For now, merely tries to distinguish ISO-8859-1, UTF-8 and Shift_JIS, // which should be by far the most common encodings. ISO-8859-1 // should not have bytes in the 0x80 - 0x9F range, while Shift_JIS // uses this as a first byte of a two-byte character. If we see this // followed by a valid second byte in Shift_JIS, assume it is Shift_JIS. // If we see something else in that second byte, we'll make the risky guess // that it's UTF-8. int length = bytes.length; boolean canBeISO88591 = true; boolean canBeShiftJIS = true; int maybeDoubleByteCount = 0; int maybeSingleByteKatakanaCount = 0; boolean sawLatin1Supplement = false; boolean lastWasPossibleDoubleByteStart = false; for (int i = 0; i < length && (canBeISO88591 || canBeShiftJIS); i++) { int value = bytes[i] & 0xFF; - if (value == 0xC2 || value == 0xC3 && i < length - 1) { + if ((value == 0xC2 || value == 0xC3) && i < length - 1) { // This is really a poor hack. The slightly more exotic characters people might want to put in // a QR Code, by which I mean the Latin-1 supplement characters (e.g. u-umlaut) have encodings // that start with 0xC2 followed by [0xA0,0xBF], or start with 0xC3 followed by [0x80,0xBF]. int nextValue = bytes[i + 1] & 0xFF; if (nextValue <= 0xBF && ((value == 0xC2 && nextValue >= 0xA0) || (value == 0xC3 && nextValue >= 0x80))) { sawLatin1Supplement = true; } } if (value >= 0x7F && value <= 0x9F) { canBeISO88591 = false; } if (value >= 0xA1 && value <= 0xDF) { // count the number of characters that might be a Shift_JIS single-byte Katakana character if (!lastWasPossibleDoubleByteStart) { maybeSingleByteKatakanaCount++; } } if (!lastWasPossibleDoubleByteStart && ((value >= 0xF0 && value <= 0xFF) || value == 0x80 || value == 0xA0)) { canBeShiftJIS = false; } if (((value >= 0x81 && value <= 0x9F) || (value >= 0xE0 && value <= 0xEF))) { // These start double-byte characters in Shift_JIS. Let's see if it's followed by a valid // second byte. if (lastWasPossibleDoubleByteStart) { // If we just checked this and the last byte for being a valid double-byte // char, don't check starting on this byte. If this and the last byte // formed a valid pair, then this shouldn't be checked to see if it starts // a double byte pair of course. lastWasPossibleDoubleByteStart = false; } else { // ... otherwise do check to see if this plus the next byte form a valid // double byte pair encoding a character. lastWasPossibleDoubleByteStart = true; if (i >= bytes.length - 1) { canBeShiftJIS = false; } else { int nextValue = bytes[i + 1] & 0xFF; if (nextValue < 0x40 || nextValue > 0xFC) { canBeShiftJIS = false; } else { maybeDoubleByteCount++; } // There is some conflicting information out there about which bytes can follow which in // double-byte Shift_JIS characters. The rule above seems to be the one that matches practice. } } } else { lastWasPossibleDoubleByteStart = false; } } // Distinguishing Shift_JIS and ISO-8859-1 can be a little tough. The crude heuristic is: // - If we saw // - at least three byte that starts a double-byte value (bytes that are rare in ISO-8859-1), or // - over 5% of bytes that could be single-byte Katakana (also rare in ISO-8859-1), // - and, saw no sequences that are invalid in Shift_JIS, then we conclude Shift_JIS if (canBeShiftJIS && (maybeDoubleByteCount >= 3 || 20 * maybeSingleByteKatakanaCount > length)) { return SHIFT_JIS; } // Otherwise, we default to ISO-8859-1 unless we know it can't be if (!sawLatin1Supplement && canBeISO88591) { return ISO88591; } // Otherwise, we take a wild guess with UTF-8 return UTF8; } private static int parseECIValue(BitSource bits) { int firstByte = bits.readBits(8); if ((firstByte & 0x80) == 0) { // just one byte return firstByte & 0x7F; } else if ((firstByte & 0xC0) == 0x80) { // two bytes int secondByte = bits.readBits(8); return ((firstByte & 0x3F) << 8) | secondByte; } else if ((firstByte & 0xE0) == 0xC0) { // three bytes int secondThirdBytes = bits.readBits(16); return ((firstByte & 0x1F) << 16) | secondThirdBytes; } throw new IllegalArgumentException("Bad ECI bits starting with byte " + firstByte); } }
true
true
private static String guessEncoding(byte[] bytes) { if (ASSUME_SHIFT_JIS) { return SHIFT_JIS; } // Does it start with the UTF-8 byte order mark? then guess it's UTF-8 if (bytes.length > 3 && bytes[0] == (byte) 0xEF && bytes[1] == (byte) 0xBB && bytes[2] == (byte) 0xBF) { return UTF8; } // For now, merely tries to distinguish ISO-8859-1, UTF-8 and Shift_JIS, // which should be by far the most common encodings. ISO-8859-1 // should not have bytes in the 0x80 - 0x9F range, while Shift_JIS // uses this as a first byte of a two-byte character. If we see this // followed by a valid second byte in Shift_JIS, assume it is Shift_JIS. // If we see something else in that second byte, we'll make the risky guess // that it's UTF-8. int length = bytes.length; boolean canBeISO88591 = true; boolean canBeShiftJIS = true; int maybeDoubleByteCount = 0; int maybeSingleByteKatakanaCount = 0; boolean sawLatin1Supplement = false; boolean lastWasPossibleDoubleByteStart = false; for (int i = 0; i < length && (canBeISO88591 || canBeShiftJIS); i++) { int value = bytes[i] & 0xFF; if (value == 0xC2 || value == 0xC3 && i < length - 1) { // This is really a poor hack. The slightly more exotic characters people might want to put in // a QR Code, by which I mean the Latin-1 supplement characters (e.g. u-umlaut) have encodings // that start with 0xC2 followed by [0xA0,0xBF], or start with 0xC3 followed by [0x80,0xBF]. int nextValue = bytes[i + 1] & 0xFF; if (nextValue <= 0xBF && ((value == 0xC2 && nextValue >= 0xA0) || (value == 0xC3 && nextValue >= 0x80))) { sawLatin1Supplement = true; } } if (value >= 0x7F && value <= 0x9F) { canBeISO88591 = false; } if (value >= 0xA1 && value <= 0xDF) { // count the number of characters that might be a Shift_JIS single-byte Katakana character if (!lastWasPossibleDoubleByteStart) { maybeSingleByteKatakanaCount++; } } if (!lastWasPossibleDoubleByteStart && ((value >= 0xF0 && value <= 0xFF) || value == 0x80 || value == 0xA0)) { canBeShiftJIS = false; } if (((value >= 0x81 && value <= 0x9F) || (value >= 0xE0 && value <= 0xEF))) { // These start double-byte characters in Shift_JIS. Let's see if it's followed by a valid // second byte. if (lastWasPossibleDoubleByteStart) { // If we just checked this and the last byte for being a valid double-byte // char, don't check starting on this byte. If this and the last byte // formed a valid pair, then this shouldn't be checked to see if it starts // a double byte pair of course. lastWasPossibleDoubleByteStart = false; } else { // ... otherwise do check to see if this plus the next byte form a valid // double byte pair encoding a character. lastWasPossibleDoubleByteStart = true; if (i >= bytes.length - 1) { canBeShiftJIS = false; } else { int nextValue = bytes[i + 1] & 0xFF; if (nextValue < 0x40 || nextValue > 0xFC) { canBeShiftJIS = false; } else { maybeDoubleByteCount++; } // There is some conflicting information out there about which bytes can follow which in // double-byte Shift_JIS characters. The rule above seems to be the one that matches practice. } } } else { lastWasPossibleDoubleByteStart = false; } } // Distinguishing Shift_JIS and ISO-8859-1 can be a little tough. The crude heuristic is: // - If we saw // - at least three byte that starts a double-byte value (bytes that are rare in ISO-8859-1), or // - over 5% of bytes that could be single-byte Katakana (also rare in ISO-8859-1), // - and, saw no sequences that are invalid in Shift_JIS, then we conclude Shift_JIS if (canBeShiftJIS && (maybeDoubleByteCount >= 3 || 20 * maybeSingleByteKatakanaCount > length)) { return SHIFT_JIS; } // Otherwise, we default to ISO-8859-1 unless we know it can't be if (!sawLatin1Supplement && canBeISO88591) { return ISO88591; } // Otherwise, we take a wild guess with UTF-8 return UTF8; }
private static String guessEncoding(byte[] bytes) { if (ASSUME_SHIFT_JIS) { return SHIFT_JIS; } // Does it start with the UTF-8 byte order mark? then guess it's UTF-8 if (bytes.length > 3 && bytes[0] == (byte) 0xEF && bytes[1] == (byte) 0xBB && bytes[2] == (byte) 0xBF) { return UTF8; } // For now, merely tries to distinguish ISO-8859-1, UTF-8 and Shift_JIS, // which should be by far the most common encodings. ISO-8859-1 // should not have bytes in the 0x80 - 0x9F range, while Shift_JIS // uses this as a first byte of a two-byte character. If we see this // followed by a valid second byte in Shift_JIS, assume it is Shift_JIS. // If we see something else in that second byte, we'll make the risky guess // that it's UTF-8. int length = bytes.length; boolean canBeISO88591 = true; boolean canBeShiftJIS = true; int maybeDoubleByteCount = 0; int maybeSingleByteKatakanaCount = 0; boolean sawLatin1Supplement = false; boolean lastWasPossibleDoubleByteStart = false; for (int i = 0; i < length && (canBeISO88591 || canBeShiftJIS); i++) { int value = bytes[i] & 0xFF; if ((value == 0xC2 || value == 0xC3) && i < length - 1) { // This is really a poor hack. The slightly more exotic characters people might want to put in // a QR Code, by which I mean the Latin-1 supplement characters (e.g. u-umlaut) have encodings // that start with 0xC2 followed by [0xA0,0xBF], or start with 0xC3 followed by [0x80,0xBF]. int nextValue = bytes[i + 1] & 0xFF; if (nextValue <= 0xBF && ((value == 0xC2 && nextValue >= 0xA0) || (value == 0xC3 && nextValue >= 0x80))) { sawLatin1Supplement = true; } } if (value >= 0x7F && value <= 0x9F) { canBeISO88591 = false; } if (value >= 0xA1 && value <= 0xDF) { // count the number of characters that might be a Shift_JIS single-byte Katakana character if (!lastWasPossibleDoubleByteStart) { maybeSingleByteKatakanaCount++; } } if (!lastWasPossibleDoubleByteStart && ((value >= 0xF0 && value <= 0xFF) || value == 0x80 || value == 0xA0)) { canBeShiftJIS = false; } if (((value >= 0x81 && value <= 0x9F) || (value >= 0xE0 && value <= 0xEF))) { // These start double-byte characters in Shift_JIS. Let's see if it's followed by a valid // second byte. if (lastWasPossibleDoubleByteStart) { // If we just checked this and the last byte for being a valid double-byte // char, don't check starting on this byte. If this and the last byte // formed a valid pair, then this shouldn't be checked to see if it starts // a double byte pair of course. lastWasPossibleDoubleByteStart = false; } else { // ... otherwise do check to see if this plus the next byte form a valid // double byte pair encoding a character. lastWasPossibleDoubleByteStart = true; if (i >= bytes.length - 1) { canBeShiftJIS = false; } else { int nextValue = bytes[i + 1] & 0xFF; if (nextValue < 0x40 || nextValue > 0xFC) { canBeShiftJIS = false; } else { maybeDoubleByteCount++; } // There is some conflicting information out there about which bytes can follow which in // double-byte Shift_JIS characters. The rule above seems to be the one that matches practice. } } } else { lastWasPossibleDoubleByteStart = false; } } // Distinguishing Shift_JIS and ISO-8859-1 can be a little tough. The crude heuristic is: // - If we saw // - at least three byte that starts a double-byte value (bytes that are rare in ISO-8859-1), or // - over 5% of bytes that could be single-byte Katakana (also rare in ISO-8859-1), // - and, saw no sequences that are invalid in Shift_JIS, then we conclude Shift_JIS if (canBeShiftJIS && (maybeDoubleByteCount >= 3 || 20 * maybeSingleByteKatakanaCount > length)) { return SHIFT_JIS; } // Otherwise, we default to ISO-8859-1 unless we know it can't be if (!sawLatin1Supplement && canBeISO88591) { return ISO88591; } // Otherwise, we take a wild guess with UTF-8 return UTF8; }
diff --git a/src/org/jruby/compiler/JITCompiler.java b/src/org/jruby/compiler/JITCompiler.java index 4e835ba55..63ed01ee0 100644 --- a/src/org/jruby/compiler/JITCompiler.java +++ b/src/org/jruby/compiler/JITCompiler.java @@ -1,226 +1,226 @@ /***** BEGIN LICENSE BLOCK ***** * Version: CPL 1.0/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Common Public * License Version 1.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.eclipse.org/legal/cpl-v10.html * * Software distributed under the License is distributed on an "AS * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. * * Copyright (C) 2006-2008 Charles O Nutter <[email protected]> * Copyright (C) 2008 Thomas E Enebo <[email protected]> * * Alternatively, the contents of this file may be used under the terms of * either of the GNU General Public License Version 2 or later (the "GPL"), * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the CPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the CPL, the GPL or the LGPL. ***** END LICENSE BLOCK *****/ package org.jruby.compiler; import java.util.Set; import org.jruby.Ruby; import org.jruby.RubyInstanceConfig; import org.jruby.ast.ArgsNode; import org.jruby.ast.Node; import org.jruby.ast.executable.Script; import org.jruby.ast.util.SexpMaker; import org.jruby.compiler.impl.StandardASMCompiler; import org.jruby.internal.runtime.methods.CallConfiguration; import org.jruby.internal.runtime.methods.DefaultMethod; import org.jruby.parser.StaticScope; import org.jruby.runtime.ThreadContext; import org.jruby.util.ClassCache; import org.jruby.util.CodegenUtils; import org.jruby.util.JavaNameMangler; public class JITCompiler { public static final boolean USE_CACHE = true; public static void runJIT(final DefaultMethod method, final Ruby runtime, final ThreadContext context, final String name) { Set<Script> jittedMethods = runtime.getJittedMethods(); final RubyInstanceConfig instanceConfig = runtime.getInstanceConfig(); ClassCache classCache = instanceConfig.getClassCache(); // This method has JITed already or has been abandoned. Bail out. if (method.getCallCount() < 0) return; try { method.setCallCount(method.getCallCount() + 1); if (method.getCallCount() >= instanceConfig.getJitThreshold()) { // The cache is full. Abandon JIT for this method and bail out. if (classCache.isFull()) { method.setCallCount(-1); return; } JITClassGenerator generator = new JITClassGenerator(name, method, context); String key = SexpMaker.create(name, method.getArgsNode(), method.getBodyNode()); Class<Script> sourceClass = instanceConfig.getClassCache().cacheClassByKey(key, generator); if (sourceClass == null) { // class could not be found nor generated; give up on JIT and bail out method.setCallCount(-1); return; } // finally, grab the script Script jitCompiledScript = (Script) sourceClass.newInstance(); // add to the jitted methods set jittedMethods.add(jitCompiledScript); // logEvery n methods based on configuration if (instanceConfig.getJitLogEvery() > 0) { int methodCount = jittedMethods.size(); if (methodCount % instanceConfig.getJitLogEvery() == 0) { log(method, name, "live compiled methods: " + methodCount); } } if (instanceConfig.isJitLogging()) log(method, name, "done jitting"); method.setJITCallConfig(generator.callConfig()); method.setJITCompiledScript(jitCompiledScript); method.setCallCount(-1); } - } catch (Exception e) { - if (instanceConfig.isJitLoggingVerbose()) log(method, name, "could not compile", e.getMessage()); + } catch (Throwable t) { + if (instanceConfig.isJitLoggingVerbose()) log(method, name, "could not compile", t.getMessage()); method.setCallCount(-1); } } public static class JITClassGenerator implements ClassCache.ClassGenerator { private StandardASMCompiler asmCompiler; private DefaultMethod method; private StaticScope staticScope; private Node bodyNode; private ArgsNode argsNode; private CallConfiguration jitCallConfig; private byte[] bytecode; private String name; public JITClassGenerator(String name, DefaultMethod method, ThreadContext context) { this.method = method; String packageName = "ruby/jit/" + JavaNameMangler.mangleFilenameForClasspath(method.getPosition().getFile()); String cleanName = packageName + "/" + JavaNameMangler.mangleStringForCleanJavaIdentifier(name); this.bodyNode = method.getBodyNode(); this.argsNode = method.getArgsNode(); final String filename = calculateFilename(argsNode, bodyNode); staticScope = method.getStaticScope(); asmCompiler = new StandardASMCompiler(cleanName + method.hashCode() + "_" + context.hashCode(), filename); } @SuppressWarnings("unchecked") protected void compile() { if (bytecode != null) return; asmCompiler.startScript(staticScope); final ASTCompiler compiler = new ASTCompiler(); CompilerCallback args = new CompilerCallback() { public void call(MethodCompiler context) { compiler.compileArgs(argsNode, context); } }; ASTInspector inspector = new ASTInspector(); inspector.inspect(bodyNode); inspector.inspect(argsNode); MethodCompiler methodCompiler; if (bodyNode != null) { // we have a body, do a full-on method methodCompiler = asmCompiler.startMethod("__file__", args, staticScope, inspector); compiler.compile(bodyNode, methodCompiler); } else { // If we don't have a body, check for required or opt args // if opt args, they could have side effects // if required args, need to raise errors if too few args passed // otherwise, method does nothing, make it a nop if (argsNode != null && (argsNode.getRequiredArgsCount() > 0 || argsNode.getOptionalArgsCount() > 0)) { methodCompiler = asmCompiler.startMethod("__file__", args, staticScope, inspector); methodCompiler.loadNil(); } else { methodCompiler = asmCompiler.startMethod("__file__", null, staticScope, inspector); methodCompiler.loadNil(); jitCallConfig = CallConfiguration.NO_FRAME_NO_SCOPE; } } methodCompiler.endMethod(); asmCompiler.endScript(false, false, false); // if we haven't already decided on a do-nothing call if (jitCallConfig == null) { // if we're not doing any of the operations that still need // a scope, use the scopeless config if (inspector.hasClosure() || inspector.hasScopeAwareMethods()) { jitCallConfig = CallConfiguration.FRAME_AND_SCOPE; } else { // switch to a slightly faster call config jitCallConfig = CallConfiguration.FRAME_ONLY; } } bytecode = asmCompiler.getClassByteArray(); name = CodegenUtils.c(asmCompiler.getClassname()); } public byte[] bytecode() { compile(); return bytecode; } public String name() { compile(); return name; } public CallConfiguration callConfig() { compile(); return jitCallConfig; } } private static String calculateFilename(ArgsNode argsNode, Node bodyNode) { if (bodyNode != null) return bodyNode.getPosition().getFile(); if (argsNode != null) return argsNode.getPosition().getFile(); return "__eval__"; } static void log(DefaultMethod method, String name, String message, String... reason) { String className = method.getImplementationClass().getBaseName(); if (className == null) className = "<anon class>"; System.err.print(message + ":" + className + "." + name); if (reason.length > 0) { System.err.print(" because of: \""); for (int i = 0; i < reason.length; i++) { System.err.print(reason[i]); } System.err.print('"'); } System.err.println(""); } }
true
true
public static void runJIT(final DefaultMethod method, final Ruby runtime, final ThreadContext context, final String name) { Set<Script> jittedMethods = runtime.getJittedMethods(); final RubyInstanceConfig instanceConfig = runtime.getInstanceConfig(); ClassCache classCache = instanceConfig.getClassCache(); // This method has JITed already or has been abandoned. Bail out. if (method.getCallCount() < 0) return; try { method.setCallCount(method.getCallCount() + 1); if (method.getCallCount() >= instanceConfig.getJitThreshold()) { // The cache is full. Abandon JIT for this method and bail out. if (classCache.isFull()) { method.setCallCount(-1); return; } JITClassGenerator generator = new JITClassGenerator(name, method, context); String key = SexpMaker.create(name, method.getArgsNode(), method.getBodyNode()); Class<Script> sourceClass = instanceConfig.getClassCache().cacheClassByKey(key, generator); if (sourceClass == null) { // class could not be found nor generated; give up on JIT and bail out method.setCallCount(-1); return; } // finally, grab the script Script jitCompiledScript = (Script) sourceClass.newInstance(); // add to the jitted methods set jittedMethods.add(jitCompiledScript); // logEvery n methods based on configuration if (instanceConfig.getJitLogEvery() > 0) { int methodCount = jittedMethods.size(); if (methodCount % instanceConfig.getJitLogEvery() == 0) { log(method, name, "live compiled methods: " + methodCount); } } if (instanceConfig.isJitLogging()) log(method, name, "done jitting"); method.setJITCallConfig(generator.callConfig()); method.setJITCompiledScript(jitCompiledScript); method.setCallCount(-1); } } catch (Exception e) { if (instanceConfig.isJitLoggingVerbose()) log(method, name, "could not compile", e.getMessage()); method.setCallCount(-1); } }
public static void runJIT(final DefaultMethod method, final Ruby runtime, final ThreadContext context, final String name) { Set<Script> jittedMethods = runtime.getJittedMethods(); final RubyInstanceConfig instanceConfig = runtime.getInstanceConfig(); ClassCache classCache = instanceConfig.getClassCache(); // This method has JITed already or has been abandoned. Bail out. if (method.getCallCount() < 0) return; try { method.setCallCount(method.getCallCount() + 1); if (method.getCallCount() >= instanceConfig.getJitThreshold()) { // The cache is full. Abandon JIT for this method and bail out. if (classCache.isFull()) { method.setCallCount(-1); return; } JITClassGenerator generator = new JITClassGenerator(name, method, context); String key = SexpMaker.create(name, method.getArgsNode(), method.getBodyNode()); Class<Script> sourceClass = instanceConfig.getClassCache().cacheClassByKey(key, generator); if (sourceClass == null) { // class could not be found nor generated; give up on JIT and bail out method.setCallCount(-1); return; } // finally, grab the script Script jitCompiledScript = (Script) sourceClass.newInstance(); // add to the jitted methods set jittedMethods.add(jitCompiledScript); // logEvery n methods based on configuration if (instanceConfig.getJitLogEvery() > 0) { int methodCount = jittedMethods.size(); if (methodCount % instanceConfig.getJitLogEvery() == 0) { log(method, name, "live compiled methods: " + methodCount); } } if (instanceConfig.isJitLogging()) log(method, name, "done jitting"); method.setJITCallConfig(generator.callConfig()); method.setJITCompiledScript(jitCompiledScript); method.setCallCount(-1); } } catch (Throwable t) { if (instanceConfig.isJitLoggingVerbose()) log(method, name, "could not compile", t.getMessage()); method.setCallCount(-1); } }
diff --git a/src/main/java/com/metaweb/gridworks/browsing/facets/NumericBinIndex.java b/src/main/java/com/metaweb/gridworks/browsing/facets/NumericBinIndex.java index b34d3b4..ded39d4 100644 --- a/src/main/java/com/metaweb/gridworks/browsing/facets/NumericBinIndex.java +++ b/src/main/java/com/metaweb/gridworks/browsing/facets/NumericBinIndex.java @@ -1,102 +1,102 @@ package com.metaweb.gridworks.browsing.facets; import java.util.ArrayList; import java.util.List; import java.util.Properties; import com.metaweb.gridworks.expr.Evaluable; import com.metaweb.gridworks.expr.ExpressionUtils; import com.metaweb.gridworks.model.Cell; import com.metaweb.gridworks.model.Project; import com.metaweb.gridworks.model.Row; public class NumericBinIndex { private double _min; private double _max; private double _step; private int[] _bins; public NumericBinIndex(Project project, int cellIndex, Evaluable eval) { Properties bindings = ExpressionUtils.createBindings(project); _min = Double.POSITIVE_INFINITY; _max = Double.NEGATIVE_INFINITY; List<Double> allValues = new ArrayList<Double>(); for (int i = 0; i < project.rows.size(); i++) { Row row = project.rows.get(i); Cell cell = row.getCell(cellIndex); ExpressionUtils.bind(bindings, row, cell); Object value = eval.evaluate(bindings); if (value != null) { if (value.getClass().isArray()) { Object[] a = (Object[]) value; for (Object v : a) { if (v instanceof Number) { processValue(((Number) v).doubleValue(), allValues); } } } else if (value instanceof Number) { processValue(((Number) value).doubleValue(), allValues); } } } - if (getMin() >= getMax()) { + if (_min >= _max) { _step = 0; - _bins = new int[0]; + _bins = new int[1]; return; } double diff = getMax() - getMin(); _step = 1; if (diff > 10) { while (getStep() * 100 < diff) { _step *= 10; } } else { while (getStep() * 100 > diff) { _step /= 10; } } _min = (Math.floor(_min / _step) * _step); _max = (Math.ceil(_max / _step) * _step); int binCount = 1 + (int) Math.ceil((getMax() - getMin()) / getStep()); if (binCount > 100) { _step *= 2; binCount = Math.round((1 + binCount) / 2); } _bins = new int[binCount]; for (double d : allValues) { int bin = (int) Math.round((d - _min) / _step); _bins[bin]++; } } public double getMin() { return _min; } public double getMax() { return _max; } public double getStep() { return _step; } public int[] getBins() { return _bins; } protected void processValue(double v, List<Double> allValues) { _min = Math.min(getMin(), v); _max = Math.max(getMax(), v); allValues.add(v); } }
false
true
public NumericBinIndex(Project project, int cellIndex, Evaluable eval) { Properties bindings = ExpressionUtils.createBindings(project); _min = Double.POSITIVE_INFINITY; _max = Double.NEGATIVE_INFINITY; List<Double> allValues = new ArrayList<Double>(); for (int i = 0; i < project.rows.size(); i++) { Row row = project.rows.get(i); Cell cell = row.getCell(cellIndex); ExpressionUtils.bind(bindings, row, cell); Object value = eval.evaluate(bindings); if (value != null) { if (value.getClass().isArray()) { Object[] a = (Object[]) value; for (Object v : a) { if (v instanceof Number) { processValue(((Number) v).doubleValue(), allValues); } } } else if (value instanceof Number) { processValue(((Number) value).doubleValue(), allValues); } } } if (getMin() >= getMax()) { _step = 0; _bins = new int[0]; return; } double diff = getMax() - getMin(); _step = 1; if (diff > 10) { while (getStep() * 100 < diff) { _step *= 10; } } else { while (getStep() * 100 > diff) { _step /= 10; } } _min = (Math.floor(_min / _step) * _step); _max = (Math.ceil(_max / _step) * _step); int binCount = 1 + (int) Math.ceil((getMax() - getMin()) / getStep()); if (binCount > 100) { _step *= 2; binCount = Math.round((1 + binCount) / 2); } _bins = new int[binCount]; for (double d : allValues) { int bin = (int) Math.round((d - _min) / _step); _bins[bin]++; } }
public NumericBinIndex(Project project, int cellIndex, Evaluable eval) { Properties bindings = ExpressionUtils.createBindings(project); _min = Double.POSITIVE_INFINITY; _max = Double.NEGATIVE_INFINITY; List<Double> allValues = new ArrayList<Double>(); for (int i = 0; i < project.rows.size(); i++) { Row row = project.rows.get(i); Cell cell = row.getCell(cellIndex); ExpressionUtils.bind(bindings, row, cell); Object value = eval.evaluate(bindings); if (value != null) { if (value.getClass().isArray()) { Object[] a = (Object[]) value; for (Object v : a) { if (v instanceof Number) { processValue(((Number) v).doubleValue(), allValues); } } } else if (value instanceof Number) { processValue(((Number) value).doubleValue(), allValues); } } } if (_min >= _max) { _step = 0; _bins = new int[1]; return; } double diff = getMax() - getMin(); _step = 1; if (diff > 10) { while (getStep() * 100 < diff) { _step *= 10; } } else { while (getStep() * 100 > diff) { _step /= 10; } } _min = (Math.floor(_min / _step) * _step); _max = (Math.ceil(_max / _step) * _step); int binCount = 1 + (int) Math.ceil((getMax() - getMin()) / getStep()); if (binCount > 100) { _step *= 2; binCount = Math.round((1 + binCount) / 2); } _bins = new int[binCount]; for (double d : allValues) { int bin = (int) Math.round((d - _min) / _step); _bins[bin]++; } }
diff --git a/SNMP.java b/SNMP.java index e22f8a6..89acdcc 100644 --- a/SNMP.java +++ b/SNMP.java @@ -1,62 +1,62 @@ package plugins.SNMP; import plugins.SNMP.snmplib.*; import freenet.config.Config; import freenet.config.SubConfig; import freenet.pluginmanager.FredPlugin; import freenet.pluginmanager.PluginRespirator; import freenet.support.Logger; public class SNMP implements FredPlugin{ boolean goon=true; PluginRespirator pr; private int port; private String bindto; public void terminate() { Logger.normal(this,"Stopping SNMP"); SNMPAgent.stopSNMPAgent(); goon=false; } public int getPort(){ return port; } public String getBindto(){ return bindto; } public void runPlugin(PluginRespirator pr) { this.pr = pr; SNMPAgent.stopSNMPAgent(); try{ Config c=pr.getNode().config; SubConfig sc=new SubConfig("plugins.snmp",c); - sc.register("port", 4000,2, true, "SNMP port number", "SNMP port number", new SNMPPortNumberCallback()); - sc.register("bindto", "127.0.0.1", 2, true, "Ip address to bind to", "Ip address to bind the SNMP server to", new SNMPBindtoCallback()); + sc.register("port", 4000,2, true, false, "SNMP port number", "SNMP port number", new SNMPPortNumberCallback()); + sc.register("bindto", "127.0.0.1", 2, true, false, "Ip address to bind to", "Ip address to bind the SNMP server to", new SNMPBindtoCallback()); bindto=sc.getString("bindto"); port=sc.getInt("port"); SNMPAgent.setSNMPPort(port); System.out.println("Starting SNMP server on "+bindto+":"+port); SNMPStarter.initialize(); Logger.normal(this,"Starting SNMP server on "+bindto+":"+port); sc.finishedInitialization(); while(goon){ try { Thread.sleep(10000); } catch (InterruptedException e) { // Ignore } }; }catch (IllegalArgumentException e){ Logger.error(this, "Error loading SNMP server"); } } }
true
true
public void runPlugin(PluginRespirator pr) { this.pr = pr; SNMPAgent.stopSNMPAgent(); try{ Config c=pr.getNode().config; SubConfig sc=new SubConfig("plugins.snmp",c); sc.register("port", 4000,2, true, "SNMP port number", "SNMP port number", new SNMPPortNumberCallback()); sc.register("bindto", "127.0.0.1", 2, true, "Ip address to bind to", "Ip address to bind the SNMP server to", new SNMPBindtoCallback()); bindto=sc.getString("bindto"); port=sc.getInt("port"); SNMPAgent.setSNMPPort(port); System.out.println("Starting SNMP server on "+bindto+":"+port); SNMPStarter.initialize(); Logger.normal(this,"Starting SNMP server on "+bindto+":"+port); sc.finishedInitialization(); while(goon){ try { Thread.sleep(10000); } catch (InterruptedException e) { // Ignore } }; }catch (IllegalArgumentException e){ Logger.error(this, "Error loading SNMP server"); } }
public void runPlugin(PluginRespirator pr) { this.pr = pr; SNMPAgent.stopSNMPAgent(); try{ Config c=pr.getNode().config; SubConfig sc=new SubConfig("plugins.snmp",c); sc.register("port", 4000,2, true, false, "SNMP port number", "SNMP port number", new SNMPPortNumberCallback()); sc.register("bindto", "127.0.0.1", 2, true, false, "Ip address to bind to", "Ip address to bind the SNMP server to", new SNMPBindtoCallback()); bindto=sc.getString("bindto"); port=sc.getInt("port"); SNMPAgent.setSNMPPort(port); System.out.println("Starting SNMP server on "+bindto+":"+port); SNMPStarter.initialize(); Logger.normal(this,"Starting SNMP server on "+bindto+":"+port); sc.finishedInitialization(); while(goon){ try { Thread.sleep(10000); } catch (InterruptedException e) { // Ignore } }; }catch (IllegalArgumentException e){ Logger.error(this, "Error loading SNMP server"); } }
diff --git a/org.rubypeople.rdt.core/src/org/rubypeople/rdt/internal/formatter/CodeFormatter.java b/org.rubypeople.rdt.core/src/org/rubypeople/rdt/internal/formatter/CodeFormatter.java index 4bb1c15f..75268220 100644 --- a/org.rubypeople.rdt.core/src/org/rubypeople/rdt/internal/formatter/CodeFormatter.java +++ b/org.rubypeople.rdt.core/src/org/rubypeople/rdt/internal/formatter/CodeFormatter.java @@ -1,440 +1,440 @@ package org.rubypeople.rdt.internal.formatter; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; public class CodeFormatter { private final static String BLOCK_BEGIN_RE = "(class|module|def|if|unless|case|while|until|for|begin|do)"; private final static String BLOCK_MID_RE = "(else|elsif|when|rescue|ensure)"; private final static String BLOCK_END_RE = "(end)"; private final static String DELIMITER_RE = "[?$/(){}#\\`.:\\]\\[]"; private final static String[] LITERAL_BEGIN_LITERALS = { "\"", "'", "=begin", "%[Qqrxw]?.", "/", "<<[\\-]?[']?[a-zA-Z_]+[']?" }; private final static String[] LITERAL_END_RES = { "[^\\\\](\\\\\\\\)*\"", "[^\\\\](\\\\\\\\)*'", "=end", "", "", "" }; private final int BLOCK_BEGIN_PAREN = 2; private final int BLOCK_MID_PAREN = 5; private final int BLOCK_END_PAREN = 8; private final int LITERAL_BEGIN_PAREN = 10; private static Pattern MODIFIER_RE ; private static Pattern OPERATOR_RE ; private static Pattern NON_BLOCK_DO_RE ; private static String LITERAL_BEGIN_RE; // automatically concatenated from LITERAL_BEGIN_LITERALS private static Pattern[] LITERAL_END_RES_COMPILED; static { LITERAL_END_RES_COMPILED = new Pattern[LITERAL_END_RES.length]; for (int i = 0; i < LITERAL_END_RES.length; i++) { try { LITERAL_END_RES_COMPILED[i] = Pattern.compile(LITERAL_END_RES[i]); } catch (PatternSyntaxException e) { System.out.println(e); } } StringBuffer sb = new StringBuffer(); sb.append("("); for (int i = 0; i < LITERAL_BEGIN_LITERALS.length; i++) { sb.append(LITERAL_BEGIN_LITERALS[i]); if (i < LITERAL_BEGIN_LITERALS.length - 1) { sb.append("|"); } } sb.append(")"); LITERAL_BEGIN_RE = sb.toString(); try { MODIFIER_RE = Pattern.compile("if|unless|while|until|rescue"); OPERATOR_RE = Pattern.compile("[\\-,.+*/%&|\\^~=<>:]") ; NON_BLOCK_DO_RE = Pattern.compile("(^|[\\s])(while|until|for|rescue)[\\s]") ; } catch (PatternSyntaxException e) { System.out.println(e); } } private char fillCharacter; private int indentation ; private boolean isDebug ; public CodeFormatter() { this(' ', false); } public CodeFormatter(char fillCharacter, boolean isDebug) { this.fillCharacter = fillCharacter; this.indentation = 2 ; this.isDebug = isDebug ; } public synchronized String formatString(String unformatted) { AbstractBlockMarker firstAbstractBlockMarker = this.createBlockMarkerList(unformatted); if (this.isDebug) { firstAbstractBlockMarker.print(); } try { return this.formatString(unformatted, firstAbstractBlockMarker); } catch (PatternSyntaxException ex) { return unformatted; } } protected String formatString(String unformatted, AbstractBlockMarker abstractBlockMarker) throws PatternSyntaxException { Pattern pat = Pattern.compile("\n"); String[] lines = pat.split(unformatted); IndentationState state = null; StringBuffer formatted = new StringBuffer(); Pattern whitespacePattern = Pattern.compile("^[\t ]*"); for (int i = 0; i < lines.length; i++) { Matcher whitespaceMatcher = whitespacePattern.matcher(lines[i]); whitespaceMatcher.find(); int leadingWhitespace = whitespaceMatcher.end(0); if (state == null) { state = new IndentationState(unformatted, this.getIndentation(), leadingWhitespace, fillCharacter); } state.incPos(leadingWhitespace); String strippedLine = lines[i].substring(leadingWhitespace); AbstractBlockMarker newBlockMarker = this.findNextBlockMarker(abstractBlockMarker, state.getPos(), state); if (newBlockMarker != null) { newBlockMarker.indentBeforePrint(state); newBlockMarker.appendIndentedLine(formatted, state, lines[i], strippedLine); state.saveIndentation(); newBlockMarker.indentAfterPrint(state); abstractBlockMarker = newBlockMarker; } else { abstractBlockMarker.appendIndentedLine(formatted, state, lines[i], strippedLine); } if (i != lines.length - 1) { formatted.append("\n"); } state.incPos(strippedLine.length() + 1); } if (unformatted.lastIndexOf("\n") == unformatted.length() - 1) { formatted.append("\n"); } return formatted.toString(); } private AbstractBlockMarker findNextBlockMarker(AbstractBlockMarker abstractBlockMarker, int pos, IndentationState state) { AbstractBlockMarker startBlockMarker = abstractBlockMarker; while (abstractBlockMarker.getNext() != null && abstractBlockMarker.getNext().getPos() <= pos) { if (abstractBlockMarker != startBlockMarker) { abstractBlockMarker.indentBeforePrint(state); abstractBlockMarker.indentAfterPrint(state); } abstractBlockMarker = abstractBlockMarker.getNext(); } return startBlockMarker == abstractBlockMarker ? null : abstractBlockMarker; } protected AbstractBlockMarker createBlockMarkerList(String unformatted) { Pattern blockBegin = null; Pattern blockMid = null; Pattern blockEnd = null; Pattern pat = null; try { pat = Pattern.compile( - "(^|[\\s])" + "(^|[\\s]|;)" + BLOCK_BEGIN_RE + "($|[\\s]|" + DELIMITER_RE + ")|(^|[\\s])" + BLOCK_MID_RE - + "($|[\\s]|" + DELIMITER_RE + ")|(^|[\\s])" + + "($|[\\s]|" + DELIMITER_RE + ")|(^|[\\s]|;)" + BLOCK_END_RE - + "($|[\\s])|" + + "($|[\\s]|;)|" + LITERAL_BEGIN_RE + "|" + DELIMITER_RE); } catch (PatternSyntaxException e) { System.out.println(e); } int pos = 0; AbstractBlockMarker lastBlockMarker = new NeutralMarker("start", 0); AbstractBlockMarker firstBlockMarker = lastBlockMarker; Matcher re = pat.matcher(unformatted); while (pos != -1 && re.find(pos)) { AbstractBlockMarker newBlockMarker = null; if (re.group(BLOCK_BEGIN_PAREN) != null) { pos = re.end(BLOCK_BEGIN_PAREN); String blockBeginStr = re.group(BLOCK_BEGIN_PAREN) ; if (MODIFIER_RE.matcher(blockBeginStr).matches() && !this.isRubyExprBegin(unformatted, re.start(BLOCK_BEGIN_PAREN), "modifier") ) { continue ; } if (blockBeginStr.equals("do") && this.isNonBlockDo(unformatted, re.start(BLOCK_BEGIN_PAREN)) ) { continue ; } newBlockMarker = new BeginBlockMarker(re.group(BLOCK_BEGIN_PAREN), re.start(BLOCK_BEGIN_PAREN)); } else if (re.group(BLOCK_MID_PAREN) != null) { pos = re.end(BLOCK_MID_PAREN); newBlockMarker = new MidBlockMarker(re.group(BLOCK_MID_PAREN), re.start(BLOCK_MID_PAREN)); } else if (re.group(BLOCK_END_PAREN) != null) { pos = re.end(BLOCK_END_PAREN); newBlockMarker = new EndBlockMarker(re.group(BLOCK_END_PAREN), re.start(BLOCK_END_PAREN)); } else if (re.group(LITERAL_BEGIN_PAREN) != null) { pos = re.end(LITERAL_BEGIN_PAREN); String matchedLiteralBegin = re.group(LITERAL_BEGIN_PAREN); if (matchedLiteralBegin.startsWith("%")) { int delimitChar = matchedLiteralBegin.charAt(matchedLiteralBegin.length() - 1); boolean expand = matchedLiteralBegin.charAt(1) != 'q'; if (delimitChar == '[') { pos = this.forwardString(unformatted, pos, '[', ']', expand); } else if (delimitChar == '(') { pos = this.forwardString(unformatted, pos, '(', ')', expand); } else if (delimitChar == '{') { pos = this.forwardString(unformatted, pos, '{', '}', expand); } else if (delimitChar == '<') { pos = this.forwardString(unformatted, pos, '<', '>', expand); } else { pos = unformatted.indexOf(delimitChar, pos); } } else if (matchedLiteralBegin.startsWith("/")) { // we do not consider reg exp over multiple lines. Therefore a reg exp over // mutliple lines might get formatted. On the other hand code between // two division slashes on several lines is being formatted. We could avoid that // behaviour only if we could make a difference between slashes for division and // slashes for regular expressions. int posClosingSlash = this.forwardString(unformatted, pos, ' ', "/", true); if (posClosingSlash == pos) { continue ; } int posNextLine = unformatted.indexOf("\n", pos) ; if (posNextLine != -1 && posClosingSlash > posNextLine) { continue ; } pos = posClosingSlash ; } else if (matchedLiteralBegin.startsWith("'")) { if (pos > 1 && unformatted.charAt(pos - 2) == '$') { continue; } pos = this.forwardString(unformatted, pos, ' ', "'", true); } else if (matchedLiteralBegin.startsWith("<<")) { int startId = 2 ; int endId = matchedLiteralBegin.length() ; boolean isMinus = (matchedLiteralBegin.charAt(startId) == '-') ; if (isMinus) { startId += 1 ; } if (startId < matchedLiteralBegin.length() -1 && matchedLiteralBegin.charAt(startId) == '\'' ) { startId += 1 ; endId -= 1 ; } String reStr = (isMinus ? "" : "\n") + matchedLiteralBegin.substring(startId, endId) ; try { Pattern idSearch = Pattern.compile(reStr); Matcher matcher = idSearch.matcher(unformatted); if (matcher.find(pos)) { pos = matcher.end(0) ; } else { pos = -1 ; } } catch (PatternSyntaxException e1) { continue ; } } else { for (int i = 0; i < LITERAL_BEGIN_LITERALS.length; i++) { if (LITERAL_BEGIN_LITERALS[i].equals(matchedLiteralBegin)) { Pattern matchEnd = LITERAL_END_RES_COMPILED[i]; pos = -1; Matcher tmpMatch = matchEnd.matcher(unformatted); if (tmpMatch.find(re.end(LITERAL_BEGIN_PAREN) - 1)) { pos = tmpMatch.end(0); } break; } } } newBlockMarker = new NoFormattingMarker(matchedLiteralBegin, re.start(LITERAL_BEGIN_PAREN)); if (pos != -1) { lastBlockMarker.setNext(newBlockMarker); lastBlockMarker = newBlockMarker; newBlockMarker = new NeutralMarker("", pos); } } else { String delimiter = re.group(0); if (delimiter.equals("#")) { pos = unformatted.indexOf("\n", re.end(0)); continue; } else if (delimiter.equals("{")) { newBlockMarker = new BeginBlockMarker("{", re.start(0)); } else if (delimiter.equals("}")) { newBlockMarker = new EndBlockMarker("}", re.start(0)); } else if (delimiter.equals("(")) { newBlockMarker = new FixLengthMarker("(", re.start(0)); } else if (delimiter.equals(")")) { newBlockMarker = new NeutralMarker(")", re.start(0)); } pos = re.end(0); } if (newBlockMarker == null) { continue; } if (lastBlockMarker != null) { lastBlockMarker.setNext(newBlockMarker); } lastBlockMarker = newBlockMarker; } return firstBlockMarker; } /* (defun ruby-forward-string (term &optional end no-error expand) (let ((n 1) (c (string-to-char term)) (re (if expand (concat "[^\\]\\(\\\\\\\\\\)*\\([" term "]\\|\\(#{\\)\\)") (concat "[^\\]\\(\\\\\\\\\\)*[" term "]")))) (while (and (re-search-forward re end no-error) (if (match-beginning 3) (ruby-forward-string "}{" end no-error nil) (> (setq n (if (eq (char-before (point)) c) (1- n) (1+ n))) 0))) (forward-char -1)) (cond ((zerop n)) (no-error nil) (error "unterminated string")))) */ protected int forwardString(String unformatted, int pos, char opening, char closing, boolean expand) { return this.forwardString(unformatted, pos, opening, "\\" + opening + "\\" + closing, expand); } protected int forwardString(String unformatted, int pos, char opening, String term, boolean expand) { int n = 1; try { Pattern pat = Pattern.compile(expand ? "[" + term + "]|(#\\{)" : "[" + term + "]"); Matcher re = pat.matcher(unformatted); while (re.find(pos) && n > 0) { if (re.group(1) != null) { pos = this.forwardString(unformatted, re.end(1), '{', "\\{\\}", expand); } else { pos = re.end(0); if (pos > 2 && unformatted.charAt(pos - 2) == '\\' && unformatted.charAt(pos - 3) != '\\') { continue; } if (re.group(0).charAt(0) == opening) { n += 1; } else { n -= 1; } } } } catch (PatternSyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } return pos; } /* * (defun ruby-expr-beg (&optional option) (save-excursion (store-match-data * nil) (skip-chars-backward " \t") (cond ((bolp) t) ((looking-at "\\?") (or * (bolp) (forward-char -1)) (not (looking-at "\\sw"))) (t (forward-char -1) * (or (looking-at ruby-operator-re) (looking-at "[\\[({,;]") (and (not (eq * option 'modifier)) (looking-at "[!?]")) (and (looking-at ruby-symbol-re) * (skip-chars-backward ruby-symbol-chars) (cond ((or (looking-at * ruby-block-beg-re) (looking-at ruby-block-op-re) (looking-at * ruby-block-mid-re)) (goto-char (match-end 0)) (looking-at "\\>")) (t (and * (not (eq option 'expr-arg)) (looking-at "[a-zA-Z][a-zA-z0-9_]* +/[^ * \t]")))))))))) */ protected int skipCharsBackward(String unformatted, int pos) { // skipCharsBackward returns the position of the first char which is not tab or space left from pos and is in the // same line as pos do { if (pos == 0) { return 0; } if (unformatted.charAt(pos - 1) == '\n') { return pos; } pos -= 1; } while (unformatted.charAt(pos) == '\t' || unformatted.charAt(pos) == ' '); return pos; } protected int backToIndentation(String unformatted, int pos) { do { if (pos == 0) { return 0; } if (unformatted.charAt(pos - 1) == '\n') { break ; } pos -= 1; } while (true); while (unformatted.charAt(pos) == '\t' || unformatted.charAt(pos) == ' ' ) { pos += 1 ; if (pos == unformatted.length()) { break ; } } return pos ; } protected int posOfLineStart(String unformatted, int pos) { do { if (pos == 0) { return 0; } if (unformatted.charAt(pos - 1) == '\n') { break ; } pos -= 1; } while (true); return pos ; } protected boolean matchREBackward(String str, Pattern re) { int pos = str.length() -1 ; while (pos >= 0) { if (str.charAt(pos) == ';') { return false ; } if (re.matcher(str).find(pos)) { return true; } pos -= 1; } return false ; } protected boolean isRubyExprBegin(String unformatted, int pos, String option) { int firstNonSpaceCharInLine = this.skipCharsBackward(unformatted, pos); if (firstNonSpaceCharInLine == 0 || unformatted.charAt(firstNonSpaceCharInLine - 1) == '\n') { return true; } char c = unformatted.charAt(firstNonSpaceCharInLine); if (c == ';') { return true; } String c_str = "" + c ; if (OPERATOR_RE.matcher(c_str).matches()) { return true ; } return false; } protected boolean isNonBlockDo(String unformatted, int pos) { int lineStart = this.posOfLineStart(unformatted, pos) ; return this.matchREBackward(unformatted.substring(lineStart, pos), NON_BLOCK_DO_RE) ; } public int getIndentation() { return indentation; } public void setIndentation(int i) { indentation = i; } public void setDebug(boolean b) { isDebug = b; } }
false
true
protected AbstractBlockMarker createBlockMarkerList(String unformatted) { Pattern blockBegin = null; Pattern blockMid = null; Pattern blockEnd = null; Pattern pat = null; try { pat = Pattern.compile( "(^|[\\s])" + BLOCK_BEGIN_RE + "($|[\\s]|" + DELIMITER_RE + ")|(^|[\\s])" + BLOCK_MID_RE + "($|[\\s]|" + DELIMITER_RE + ")|(^|[\\s])" + BLOCK_END_RE + "($|[\\s])|" + LITERAL_BEGIN_RE + "|" + DELIMITER_RE); } catch (PatternSyntaxException e) { System.out.println(e); } int pos = 0; AbstractBlockMarker lastBlockMarker = new NeutralMarker("start", 0); AbstractBlockMarker firstBlockMarker = lastBlockMarker; Matcher re = pat.matcher(unformatted); while (pos != -1 && re.find(pos)) { AbstractBlockMarker newBlockMarker = null; if (re.group(BLOCK_BEGIN_PAREN) != null) { pos = re.end(BLOCK_BEGIN_PAREN); String blockBeginStr = re.group(BLOCK_BEGIN_PAREN) ; if (MODIFIER_RE.matcher(blockBeginStr).matches() && !this.isRubyExprBegin(unformatted, re.start(BLOCK_BEGIN_PAREN), "modifier") ) { continue ; } if (blockBeginStr.equals("do") && this.isNonBlockDo(unformatted, re.start(BLOCK_BEGIN_PAREN)) ) { continue ; } newBlockMarker = new BeginBlockMarker(re.group(BLOCK_BEGIN_PAREN), re.start(BLOCK_BEGIN_PAREN)); } else if (re.group(BLOCK_MID_PAREN) != null) { pos = re.end(BLOCK_MID_PAREN); newBlockMarker = new MidBlockMarker(re.group(BLOCK_MID_PAREN), re.start(BLOCK_MID_PAREN)); } else if (re.group(BLOCK_END_PAREN) != null) { pos = re.end(BLOCK_END_PAREN); newBlockMarker = new EndBlockMarker(re.group(BLOCK_END_PAREN), re.start(BLOCK_END_PAREN)); } else if (re.group(LITERAL_BEGIN_PAREN) != null) { pos = re.end(LITERAL_BEGIN_PAREN); String matchedLiteralBegin = re.group(LITERAL_BEGIN_PAREN); if (matchedLiteralBegin.startsWith("%")) { int delimitChar = matchedLiteralBegin.charAt(matchedLiteralBegin.length() - 1); boolean expand = matchedLiteralBegin.charAt(1) != 'q'; if (delimitChar == '[') { pos = this.forwardString(unformatted, pos, '[', ']', expand); } else if (delimitChar == '(') { pos = this.forwardString(unformatted, pos, '(', ')', expand); } else if (delimitChar == '{') { pos = this.forwardString(unformatted, pos, '{', '}', expand); } else if (delimitChar == '<') { pos = this.forwardString(unformatted, pos, '<', '>', expand); } else { pos = unformatted.indexOf(delimitChar, pos); } } else if (matchedLiteralBegin.startsWith("/")) { // we do not consider reg exp over multiple lines. Therefore a reg exp over // mutliple lines might get formatted. On the other hand code between // two division slashes on several lines is being formatted. We could avoid that // behaviour only if we could make a difference between slashes for division and // slashes for regular expressions. int posClosingSlash = this.forwardString(unformatted, pos, ' ', "/", true); if (posClosingSlash == pos) { continue ; } int posNextLine = unformatted.indexOf("\n", pos) ; if (posNextLine != -1 && posClosingSlash > posNextLine) { continue ; } pos = posClosingSlash ; } else if (matchedLiteralBegin.startsWith("'")) { if (pos > 1 && unformatted.charAt(pos - 2) == '$') { continue; } pos = this.forwardString(unformatted, pos, ' ', "'", true); } else if (matchedLiteralBegin.startsWith("<<")) { int startId = 2 ; int endId = matchedLiteralBegin.length() ; boolean isMinus = (matchedLiteralBegin.charAt(startId) == '-') ; if (isMinus) { startId += 1 ; } if (startId < matchedLiteralBegin.length() -1 && matchedLiteralBegin.charAt(startId) == '\'' ) { startId += 1 ; endId -= 1 ; } String reStr = (isMinus ? "" : "\n") + matchedLiteralBegin.substring(startId, endId) ; try { Pattern idSearch = Pattern.compile(reStr); Matcher matcher = idSearch.matcher(unformatted); if (matcher.find(pos)) { pos = matcher.end(0) ; } else { pos = -1 ; } } catch (PatternSyntaxException e1) { continue ; } } else { for (int i = 0; i < LITERAL_BEGIN_LITERALS.length; i++) { if (LITERAL_BEGIN_LITERALS[i].equals(matchedLiteralBegin)) { Pattern matchEnd = LITERAL_END_RES_COMPILED[i]; pos = -1; Matcher tmpMatch = matchEnd.matcher(unformatted); if (tmpMatch.find(re.end(LITERAL_BEGIN_PAREN) - 1)) { pos = tmpMatch.end(0); } break; } } } newBlockMarker = new NoFormattingMarker(matchedLiteralBegin, re.start(LITERAL_BEGIN_PAREN)); if (pos != -1) { lastBlockMarker.setNext(newBlockMarker); lastBlockMarker = newBlockMarker; newBlockMarker = new NeutralMarker("", pos); } } else { String delimiter = re.group(0); if (delimiter.equals("#")) { pos = unformatted.indexOf("\n", re.end(0)); continue; } else if (delimiter.equals("{")) { newBlockMarker = new BeginBlockMarker("{", re.start(0)); } else if (delimiter.equals("}")) { newBlockMarker = new EndBlockMarker("}", re.start(0)); } else if (delimiter.equals("(")) { newBlockMarker = new FixLengthMarker("(", re.start(0)); } else if (delimiter.equals(")")) { newBlockMarker = new NeutralMarker(")", re.start(0)); } pos = re.end(0); } if (newBlockMarker == null) { continue; } if (lastBlockMarker != null) { lastBlockMarker.setNext(newBlockMarker); } lastBlockMarker = newBlockMarker; } return firstBlockMarker; }
protected AbstractBlockMarker createBlockMarkerList(String unformatted) { Pattern blockBegin = null; Pattern blockMid = null; Pattern blockEnd = null; Pattern pat = null; try { pat = Pattern.compile( "(^|[\\s]|;)" + BLOCK_BEGIN_RE + "($|[\\s]|" + DELIMITER_RE + ")|(^|[\\s])" + BLOCK_MID_RE + "($|[\\s]|" + DELIMITER_RE + ")|(^|[\\s]|;)" + BLOCK_END_RE + "($|[\\s]|;)|" + LITERAL_BEGIN_RE + "|" + DELIMITER_RE); } catch (PatternSyntaxException e) { System.out.println(e); } int pos = 0; AbstractBlockMarker lastBlockMarker = new NeutralMarker("start", 0); AbstractBlockMarker firstBlockMarker = lastBlockMarker; Matcher re = pat.matcher(unformatted); while (pos != -1 && re.find(pos)) { AbstractBlockMarker newBlockMarker = null; if (re.group(BLOCK_BEGIN_PAREN) != null) { pos = re.end(BLOCK_BEGIN_PAREN); String blockBeginStr = re.group(BLOCK_BEGIN_PAREN) ; if (MODIFIER_RE.matcher(blockBeginStr).matches() && !this.isRubyExprBegin(unformatted, re.start(BLOCK_BEGIN_PAREN), "modifier") ) { continue ; } if (blockBeginStr.equals("do") && this.isNonBlockDo(unformatted, re.start(BLOCK_BEGIN_PAREN)) ) { continue ; } newBlockMarker = new BeginBlockMarker(re.group(BLOCK_BEGIN_PAREN), re.start(BLOCK_BEGIN_PAREN)); } else if (re.group(BLOCK_MID_PAREN) != null) { pos = re.end(BLOCK_MID_PAREN); newBlockMarker = new MidBlockMarker(re.group(BLOCK_MID_PAREN), re.start(BLOCK_MID_PAREN)); } else if (re.group(BLOCK_END_PAREN) != null) { pos = re.end(BLOCK_END_PAREN); newBlockMarker = new EndBlockMarker(re.group(BLOCK_END_PAREN), re.start(BLOCK_END_PAREN)); } else if (re.group(LITERAL_BEGIN_PAREN) != null) { pos = re.end(LITERAL_BEGIN_PAREN); String matchedLiteralBegin = re.group(LITERAL_BEGIN_PAREN); if (matchedLiteralBegin.startsWith("%")) { int delimitChar = matchedLiteralBegin.charAt(matchedLiteralBegin.length() - 1); boolean expand = matchedLiteralBegin.charAt(1) != 'q'; if (delimitChar == '[') { pos = this.forwardString(unformatted, pos, '[', ']', expand); } else if (delimitChar == '(') { pos = this.forwardString(unformatted, pos, '(', ')', expand); } else if (delimitChar == '{') { pos = this.forwardString(unformatted, pos, '{', '}', expand); } else if (delimitChar == '<') { pos = this.forwardString(unformatted, pos, '<', '>', expand); } else { pos = unformatted.indexOf(delimitChar, pos); } } else if (matchedLiteralBegin.startsWith("/")) { // we do not consider reg exp over multiple lines. Therefore a reg exp over // mutliple lines might get formatted. On the other hand code between // two division slashes on several lines is being formatted. We could avoid that // behaviour only if we could make a difference between slashes for division and // slashes for regular expressions. int posClosingSlash = this.forwardString(unformatted, pos, ' ', "/", true); if (posClosingSlash == pos) { continue ; } int posNextLine = unformatted.indexOf("\n", pos) ; if (posNextLine != -1 && posClosingSlash > posNextLine) { continue ; } pos = posClosingSlash ; } else if (matchedLiteralBegin.startsWith("'")) { if (pos > 1 && unformatted.charAt(pos - 2) == '$') { continue; } pos = this.forwardString(unformatted, pos, ' ', "'", true); } else if (matchedLiteralBegin.startsWith("<<")) { int startId = 2 ; int endId = matchedLiteralBegin.length() ; boolean isMinus = (matchedLiteralBegin.charAt(startId) == '-') ; if (isMinus) { startId += 1 ; } if (startId < matchedLiteralBegin.length() -1 && matchedLiteralBegin.charAt(startId) == '\'' ) { startId += 1 ; endId -= 1 ; } String reStr = (isMinus ? "" : "\n") + matchedLiteralBegin.substring(startId, endId) ; try { Pattern idSearch = Pattern.compile(reStr); Matcher matcher = idSearch.matcher(unformatted); if (matcher.find(pos)) { pos = matcher.end(0) ; } else { pos = -1 ; } } catch (PatternSyntaxException e1) { continue ; } } else { for (int i = 0; i < LITERAL_BEGIN_LITERALS.length; i++) { if (LITERAL_BEGIN_LITERALS[i].equals(matchedLiteralBegin)) { Pattern matchEnd = LITERAL_END_RES_COMPILED[i]; pos = -1; Matcher tmpMatch = matchEnd.matcher(unformatted); if (tmpMatch.find(re.end(LITERAL_BEGIN_PAREN) - 1)) { pos = tmpMatch.end(0); } break; } } } newBlockMarker = new NoFormattingMarker(matchedLiteralBegin, re.start(LITERAL_BEGIN_PAREN)); if (pos != -1) { lastBlockMarker.setNext(newBlockMarker); lastBlockMarker = newBlockMarker; newBlockMarker = new NeutralMarker("", pos); } } else { String delimiter = re.group(0); if (delimiter.equals("#")) { pos = unformatted.indexOf("\n", re.end(0)); continue; } else if (delimiter.equals("{")) { newBlockMarker = new BeginBlockMarker("{", re.start(0)); } else if (delimiter.equals("}")) { newBlockMarker = new EndBlockMarker("}", re.start(0)); } else if (delimiter.equals("(")) { newBlockMarker = new FixLengthMarker("(", re.start(0)); } else if (delimiter.equals(")")) { newBlockMarker = new NeutralMarker(")", re.start(0)); } pos = re.end(0); } if (newBlockMarker == null) { continue; } if (lastBlockMarker != null) { lastBlockMarker.setNext(newBlockMarker); } lastBlockMarker = newBlockMarker; } return firstBlockMarker; }
diff --git a/src/main/java/com/thalesgroup/hudson/plugins/klocwork/KloPublisher.java b/src/main/java/com/thalesgroup/hudson/plugins/klocwork/KloPublisher.java index 03623c5..8171d2c 100755 --- a/src/main/java/com/thalesgroup/hudson/plugins/klocwork/KloPublisher.java +++ b/src/main/java/com/thalesgroup/hudson/plugins/klocwork/KloPublisher.java @@ -1,274 +1,276 @@ /******************************************************************************* * Copyright (c) 2011 Thales Corporate Services SAS * * Author : Aravindan Mahendran * * * * 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.thalesgroup.hudson.plugins.klocwork; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.Action; import hudson.model.BuildListener; import hudson.model.Result; import hudson.remoting.VirtualChannel; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Publisher; import hudson.tasks.Recorder; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.kohsuke.stapler.DataBoundConstructor; import com.thalesgroup.hudson.plugins.klocwork.config.KloConfig; import com.thalesgroup.hudson.plugins.klocwork.model.KloReport; import com.thalesgroup.hudson.plugins.klocwork.model.KloSourceContainer; import com.thalesgroup.hudson.plugins.klocwork.model.KloWorkspaceFile; import com.thalesgroup.hudson.plugins.klocwork.parser.KloParserResult; import com.thalesgroup.hudson.plugins.klocwork.util.KloBuildLog; import com.thalesgroup.hudson.plugins.klocwork.util.KloBuildResultEvaluator; import com.thalesgroup.hudson.plugins.klocwork.util.KloBuildReviewLink; import com.thalesgroup.hudson.plugins.klocwork.util.KloParseErrorsLog; import com.thalesgroup.hudson.plugins.klocwork.util.KloProjectReviewLink; //AM : KloPublisher now extends Recorder instead of Publisher //public class KloPublisher extends Publisher implements Serializable { public class KloPublisher extends Recorder implements Serializable { private static final long serialVersionUID = 1L; private KloConfig kloConfig; /* @Override public Action getProjectAction(AbstractProject<?, ?> project) { return new KloProjectAction(project, kloConfig); }*/ @Override public Collection<? extends Action> getProjectActions(AbstractProject<?, ?> project) { List<Action> actions = new ArrayList<Action>(); actions.add(new KloProjectAction(project, kloConfig)); if (kloConfig.getLinkReview()) { actions.add(new KloProjectReviewLink(project)); } return actions; } protected boolean canContinue(final Result result) { return result != Result.ABORTED && result != Result.FAILURE; } public BuildStepMonitor getRequiredMonitorService() { return BuildStepMonitor.BUILD; } @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { if (this.canContinue(build.getResult())) { listener.getLogger().println("Starting the klocwork analysis."); // final FilePath[] moduleRoots = build.getModuleRoots(); // final boolean multipleModuleRoots = moduleRoots != null && moduleRoots.length > 1; // final FilePath moduleRoot = multipleModuleRoots ? build.getWorkspace() : build.getModuleRoot(); KloParserResult parser = new KloParserResult(listener, kloConfig.getKlocworkReportPattern()); KloReport kloReport; try { kloReport = build.getWorkspace().act(parser); } catch (Exception e) { listener.getLogger().println("Error on klocwork analysis: " + e); build.setResult(Result.FAILURE); return false; } if (kloReport == null) { build.setResult(Result.FAILURE); return false; } KloSourceContainer kloSourceContainer = new KloSourceContainer(listener, build.getWorkspace(), kloReport.getAllSeverities()); KloResult result = new KloResult(kloReport, kloSourceContainer, build); Result buildResult = new KloBuildResultEvaluator().evaluateBuildResult( listener, result.getNumberErrorsAccordingConfiguration(kloConfig, false), result.getNumberErrorsAccordingConfiguration(kloConfig, true), kloConfig); if (buildResult != Result.SUCCESS) { build.setResult(buildResult); } build.addAction(new KloBuildAction(build, result, kloConfig)); build.addAction(new KloBuildGraph(build, kloConfig, result.getReport())); // Check config whether to create links for Klocwork Review, parse_errors.log // and build.log if (kloConfig.getLinkReview()) { String host = null, port = null, project = null; - if (kloReport.getAllSeverities().get(0) != null) { - String url = kloReport.getAllSeverities().get(0).get("url"); - if (url !=null){ - Pattern p = Pattern.compile("^http://(.*?):(\\d*?)/.*?=(.*?),.*$"); - Matcher m = p.matcher(url); - if (m.matches()) { - host = m.group(1); - port = m.group(2); - project = m.group(3); - } + if (kloReport.getNumberTotal() != 0) { + if (kloReport.getAllSeverities().get(0) != null) { + String url = kloReport.getAllSeverities().get(0).get("url"); + if (url !=null){ + Pattern p = Pattern.compile("^http://(.*?):(\\d*?)/.*?=(.*?),.*$"); + Matcher m = p.matcher(url); + if (m.matches()) { + host = m.group(1); + port = m.group(2); + project = m.group(3); + } + } } } build.addAction(new KloBuildReviewLink(build, host, port, project)); } if (kloConfig.getLinkBuildLog()) { build.addAction(new KloBuildLog(build)); } if (kloConfig.getLinkParseLog()) { build.addAction(new KloParseErrorsLog(build)); } if (build.getWorkspace().isRemote()) { copyFilesFromSlaveToMaster(build.getRootDir(), launcher.getChannel(), kloSourceContainer.getInternalMap().values()); } listener.getLogger().println("End of the klocwork analysis."); } return true; } /** * Copies all the source files from slave to master for a remote build. * * @param rootDir directory to store the copied files in * @param channel channel to get the files from * @param sourcesFiles the sources files to be copied * @throws IOException if the files could not be written * @throws FileNotFoundException if the files could not be written * @throws InterruptedException if the user cancels the processing */ private void copyFilesFromSlaveToMaster(final File rootDir, final VirtualChannel channel, final Collection<KloWorkspaceFile> sourcesFiles) throws IOException, InterruptedException { File directory = new File(rootDir, KloWorkspaceFile.WORKSPACE_FILES); if (!directory.exists()) { if (!directory.delete()) { //do nothing } if (!directory.mkdir()) { throw new IOException("Can't create directory for remote source files: " + directory.getAbsolutePath()); } } for (KloWorkspaceFile file : sourcesFiles) { if (!file.isSourceIgnored()) { File masterFile = new File(directory, file.getTempName()); if (!masterFile.exists()) { FileOutputStream outputStream = new FileOutputStream(masterFile); new FilePath(channel, file.getFileName()).copyTo(outputStream); } } } } @Override public KloDescriptor getDescriptor() { return DESCRIPTOR; } @DataBoundConstructor public KloPublisher(KloConfig config) { this.kloConfig = config; } @Extension public static final KloDescriptor DESCRIPTOR = new KloDescriptor(); public static final class KloDescriptor extends BuildStepDescriptor<Publisher> { public KloDescriptor() { super(KloPublisher.class); load(); } @Override public String getDisplayName() { return "Publish Klocwork test result report"; } @Override public final String getHelpFile() { return getPluginRoot() + "help.html"; } /** * Returns the root folder of this plug-in. * * @return the name of the root folder of this plug-in */ public String getPluginRoot() { return "/plugin/klocwork/"; } @Override public boolean isApplicable(Class<? extends AbstractProject> jobType) { return true; } public KloConfig getConfig() { return new KloConfig(); } } public KloConfig getKloConfig() { return kloConfig; } public void setKloConfig(KloConfig kloConfig) { this.kloConfig = kloConfig; } }
true
true
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { if (this.canContinue(build.getResult())) { listener.getLogger().println("Starting the klocwork analysis."); // final FilePath[] moduleRoots = build.getModuleRoots(); // final boolean multipleModuleRoots = moduleRoots != null && moduleRoots.length > 1; // final FilePath moduleRoot = multipleModuleRoots ? build.getWorkspace() : build.getModuleRoot(); KloParserResult parser = new KloParserResult(listener, kloConfig.getKlocworkReportPattern()); KloReport kloReport; try { kloReport = build.getWorkspace().act(parser); } catch (Exception e) { listener.getLogger().println("Error on klocwork analysis: " + e); build.setResult(Result.FAILURE); return false; } if (kloReport == null) { build.setResult(Result.FAILURE); return false; } KloSourceContainer kloSourceContainer = new KloSourceContainer(listener, build.getWorkspace(), kloReport.getAllSeverities()); KloResult result = new KloResult(kloReport, kloSourceContainer, build); Result buildResult = new KloBuildResultEvaluator().evaluateBuildResult( listener, result.getNumberErrorsAccordingConfiguration(kloConfig, false), result.getNumberErrorsAccordingConfiguration(kloConfig, true), kloConfig); if (buildResult != Result.SUCCESS) { build.setResult(buildResult); } build.addAction(new KloBuildAction(build, result, kloConfig)); build.addAction(new KloBuildGraph(build, kloConfig, result.getReport())); // Check config whether to create links for Klocwork Review, parse_errors.log // and build.log if (kloConfig.getLinkReview()) { String host = null, port = null, project = null; if (kloReport.getAllSeverities().get(0) != null) { String url = kloReport.getAllSeverities().get(0).get("url"); if (url !=null){ Pattern p = Pattern.compile("^http://(.*?):(\\d*?)/.*?=(.*?),.*$"); Matcher m = p.matcher(url); if (m.matches()) { host = m.group(1); port = m.group(2); project = m.group(3); } } } build.addAction(new KloBuildReviewLink(build, host, port, project)); } if (kloConfig.getLinkBuildLog()) { build.addAction(new KloBuildLog(build)); } if (kloConfig.getLinkParseLog()) { build.addAction(new KloParseErrorsLog(build)); } if (build.getWorkspace().isRemote()) { copyFilesFromSlaveToMaster(build.getRootDir(), launcher.getChannel(), kloSourceContainer.getInternalMap().values()); } listener.getLogger().println("End of the klocwork analysis."); } return true; }
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { if (this.canContinue(build.getResult())) { listener.getLogger().println("Starting the klocwork analysis."); // final FilePath[] moduleRoots = build.getModuleRoots(); // final boolean multipleModuleRoots = moduleRoots != null && moduleRoots.length > 1; // final FilePath moduleRoot = multipleModuleRoots ? build.getWorkspace() : build.getModuleRoot(); KloParserResult parser = new KloParserResult(listener, kloConfig.getKlocworkReportPattern()); KloReport kloReport; try { kloReport = build.getWorkspace().act(parser); } catch (Exception e) { listener.getLogger().println("Error on klocwork analysis: " + e); build.setResult(Result.FAILURE); return false; } if (kloReport == null) { build.setResult(Result.FAILURE); return false; } KloSourceContainer kloSourceContainer = new KloSourceContainer(listener, build.getWorkspace(), kloReport.getAllSeverities()); KloResult result = new KloResult(kloReport, kloSourceContainer, build); Result buildResult = new KloBuildResultEvaluator().evaluateBuildResult( listener, result.getNumberErrorsAccordingConfiguration(kloConfig, false), result.getNumberErrorsAccordingConfiguration(kloConfig, true), kloConfig); if (buildResult != Result.SUCCESS) { build.setResult(buildResult); } build.addAction(new KloBuildAction(build, result, kloConfig)); build.addAction(new KloBuildGraph(build, kloConfig, result.getReport())); // Check config whether to create links for Klocwork Review, parse_errors.log // and build.log if (kloConfig.getLinkReview()) { String host = null, port = null, project = null; if (kloReport.getNumberTotal() != 0) { if (kloReport.getAllSeverities().get(0) != null) { String url = kloReport.getAllSeverities().get(0).get("url"); if (url !=null){ Pattern p = Pattern.compile("^http://(.*?):(\\d*?)/.*?=(.*?),.*$"); Matcher m = p.matcher(url); if (m.matches()) { host = m.group(1); port = m.group(2); project = m.group(3); } } } } build.addAction(new KloBuildReviewLink(build, host, port, project)); } if (kloConfig.getLinkBuildLog()) { build.addAction(new KloBuildLog(build)); } if (kloConfig.getLinkParseLog()) { build.addAction(new KloParseErrorsLog(build)); } if (build.getWorkspace().isRemote()) { copyFilesFromSlaveToMaster(build.getRootDir(), launcher.getChannel(), kloSourceContainer.getInternalMap().values()); } listener.getLogger().println("End of the klocwork analysis."); } return true; }
diff --git a/user/src/com/google/gwt/resources/ext/ResourceGeneratorUtil.java b/user/src/com/google/gwt/resources/ext/ResourceGeneratorUtil.java index 420bf9eea..4f09b767d 100644 --- a/user/src/com/google/gwt/resources/ext/ResourceGeneratorUtil.java +++ b/user/src/com/google/gwt/resources/ext/ResourceGeneratorUtil.java @@ -1,407 +1,411 @@ /* * Copyright 2008 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.google.gwt.resources.ext; import com.google.gwt.core.ext.BadPropertyValueException; import com.google.gwt.core.ext.PropertyOracle; import com.google.gwt.core.ext.SelectionProperty; import com.google.gwt.core.ext.TreeLogger; import com.google.gwt.core.ext.UnableToCompleteException; import com.google.gwt.core.ext.typeinfo.JMethod; import com.google.gwt.core.ext.typeinfo.JPackage; import com.google.gwt.dev.resource.Resource; import com.google.gwt.dev.resource.ResourceOracle; import com.google.gwt.resources.client.ClientBundle.Source; import java.lang.annotation.Annotation; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; /** * Utility methods for building ResourceGenerators. */ public final class ResourceGeneratorUtil { private static class ClassLoaderLocator implements Locator { private final ClassLoader classLoader; public ClassLoaderLocator(ClassLoader classLoader) { this.classLoader = classLoader; } public URL locate(String resourceName) { return classLoader.getResource(resourceName); } } /** * Wrapper interface around different strategies for loading resource data. */ private interface Locator { URL locate(String resourceName); } private static class ResourceOracleLocator implements Locator { private final Map<String, Resource> resourceMap; public ResourceOracleLocator(ResourceOracle oracle) { resourceMap = oracle.getResourceMap(); } public URL locate(String resourceName) { Resource r = resourceMap.get(resourceName); return r == null ? null : r.getURL(); } } /** * These are type names from previous APIs or from APIs with similar * functionality that might be confusing. * * @see #checkForDeprecatedAnnotations */ private static final String[] DEPRECATED_ANNOTATION_NAMES = { "com.google.gwt.libideas.resources.client.ImmutableResourceBundle$Resource", "com.google.gwt.user.client.ui.ImageBundle$Resource"}; private static final List<Class<? extends Annotation>> DEPRECATED_ANNOTATION_CLASSES; static { List<Class<? extends Annotation>> classes = new ArrayList<Class<? extends Annotation>>( DEPRECATED_ANNOTATION_NAMES.length); for (String name : DEPRECATED_ANNOTATION_NAMES) { try { Class<?> maybeAnnotation = Class.forName(name, false, ResourceGeneratorUtil.class.getClassLoader()); // Possibly throws ClassCastException Class<? extends Annotation> annotationClass = maybeAnnotation.asSubclass(Annotation.class); classes.add(annotationClass); } catch (ClassCastException e) { // If it's not an Annotation type, we don't care about it } catch (ClassNotFoundException e) { // This is OK; the annotation doesn't exist. } } if (classes.isEmpty()) { DEPRECATED_ANNOTATION_CLASSES = Collections.emptyList(); } else { DEPRECATED_ANNOTATION_CLASSES = Collections.unmodifiableList(classes); } } /** * Return the base filename of a resource. The behavior is similar to the unix * command <code>basename</code>. * * @param resource the URL of the resource * @return the final name segment of the resource */ public static String baseName(URL resource) { String path = resource.getPath(); return path.substring(path.lastIndexOf('/') + 1); } /** * Find all resources referenced by a method in a bundle. The method's * {@link Source} annotation will be examined and the specified locations will * be expanded into URLs by which they may be accessed on the local system. * <p> * This method is sensitive to the <code>locale</code> deferred-binding * property and will attempt to use a best-match lookup by removing locale * components. * <p> * Loading through a ClassLoader with this method is much slower than the * other <code>findResources</code> methods which make use of the compiler's * ResourceOracle. * * @param logger a TreeLogger that will be used to report errors or warnings * @param context the ResourceContext in which the ResourceGenerator is * operating * @param classLoader the ClassLoader to use when locating resources * @param method the method to examine for {@link Source} annotations * @param defaultSuffixes if the supplied method does not have any * {@link Source} annotations, act as though a Source annotation was * specified, using the name of the method and each of supplied * extensions in the order in which they are specified * @return URLs for each {@link Source} annotation value defined on the * method. * @throws UnableToCompleteException if ore or more of the sources could not * be found. The error will be reported via the <code>logger</code> * provided to this method */ public static URL[] findResources(TreeLogger logger, ClassLoader classLoader, ResourceContext context, JMethod method, String[] defaultSuffixes) throws UnableToCompleteException { return findResources(logger, new ClassLoaderLocator(classLoader), context, method, defaultSuffixes, true); } /** * Find all resources referenced by a method in a bundle. The method's * {@link Source} annotation will be examined and the specified locations will * be expanded into URLs by which they may be accessed on the local system. * <p> * This method is sensitive to the <code>locale</code> deferred-binding * property and will attempt to use a best-match lookup by removing locale * components. * <p> * The compiler's ResourceOracle will be used to resolve resource locations. * If the desired resource cannot be found in the ResourceOracle, this method * will fall back to using the current thread's context ClassLoader. If it is * necessary to alter the way in which resources are located, use the overload * that accepts a ClassLoader. * * @param logger a TreeLogger that will be used to report errors or warnings * @param context the ResourceContext in which the ResourceGenerator is * operating * @param method the method to examine for {@link Source} annotations * @return URLs for each {@link Source} annotation value defined on the * method. * @throws UnableToCompleteException if ore or more of the sources could not * be found. The error will be reported via the <code>logger</code> * provided to this method */ public static URL[] findResources(TreeLogger logger, ResourceContext context, JMethod method) throws UnableToCompleteException { return findResources(logger, context, method, new String[0]); } /** * Find all resources referenced by a method in a bundle. The method's * {@link Source} annotation will be examined and the specified locations will * be expanded into URLs by which they may be accessed on the local system. * <p> * This method is sensitive to the <code>locale</code> deferred-binding * property and will attempt to use a best-match lookup by removing locale * components. * <p> * The compiler's ResourceOracle will be used to resolve resource locations. * If the desired resource cannot be found in the ResourceOracle, this method * will fall back to using the current thread's context ClassLoader. If it is * necessary to alter the way in which resources are located, use the overload * that accepts a ClassLoader. * * @param logger a TreeLogger that will be used to report errors or warnings * @param context the ResourceContext in which the ResourceGenerator is * operating * @param method the method to examine for {@link Source} annotations * @param defaultSuffixes if the supplied method does not have any * {@link Source} annotations, act as though a Source annotation was * specified, using the name of the method and each of supplied * extensions in the order in which they are specified * @return URLs for each {@link Source} annotation value defined on the * method. * @throws UnableToCompleteException if ore or more of the sources could not * be found. The error will be reported via the <code>logger</code> * provided to this method */ public static URL[] findResources(TreeLogger logger, ResourceContext context, JMethod method, String[] defaultSuffixes) throws UnableToCompleteException { // Try to find the resources with ResourceOracle Locator locator = new ResourceOracleLocator( context.getGeneratorContext().getResourcesOracle()); // Don't report errors since we have a fallback mechanism URL[] toReturn = findResources(logger, locator, context, method, defaultSuffixes, false); if (toReturn == null) { // Since not all resources were found, try with ClassLoader locator = new ClassLoaderLocator( Thread.currentThread().getContextClassLoader()); // Do report hard failures toReturn = findResources(logger, locator, context, method, defaultSuffixes, true); } return toReturn; } /** * We want to warn the user about any annotations from ImageBundle or the old * incubator code. */ private static void checkForDeprecatedAnnotations(TreeLogger logger, JMethod method) { for (Class<? extends Annotation> annotationClass : DEPRECATED_ANNOTATION_CLASSES) { if (method.isAnnotationPresent(annotationClass)) { logger.log(TreeLogger.WARN, "Deprecated annotation used; expecting " + Source.class.getCanonicalName() + " but found " + annotationClass.getName() + " instead. It is likely " + "that undesired operation will occur."); } } } /** * Main implementation of findResources. * * @param reportErrors controls whether or not the inability to locate any * given resource should be a hard error (throw an UnableToComplete) * or a soft error (return null). */ private static URL[] findResources(TreeLogger logger, Locator locator, ResourceContext context, JMethod method, String[] defaultSuffixes, boolean reportErrors) throws UnableToCompleteException { logger = logger.branch(TreeLogger.DEBUG, "Finding resources"); String locale; try { PropertyOracle oracle = context.getGeneratorContext().getPropertyOracle(); SelectionProperty prop = oracle.getSelectionProperty(logger, "locale"); locale = prop.getCurrentValue(); } catch (BadPropertyValueException e) { locale = null; } checkForDeprecatedAnnotations(logger, method); boolean error = false; Source resourceAnnotation = method.getAnnotation(Source.class); URL[] toReturn; if (resourceAnnotation == null) { if (defaultSuffixes != null) { for (String extension : defaultSuffixes) { logger.log(TreeLogger.SPAM, "Trying default extension " + extension); URL resourceUrl = tryFindResource(locator, getPathRelativeToPackage( method.getEnclosingType().getPackage(), method.getName() + extension), locale); if (resourceUrl != null) { // Early out because we found a hit return new URL[] {resourceUrl}; } } } if (reportErrors) { logger.log(TreeLogger.ERROR, "No " + Source.class.getName() + " annotation and no resources found with default extensions"); } toReturn = null; error = true; } else { // The user has put an @Source annotation on the accessor method String[] resources = resourceAnnotation.value(); toReturn = new URL[resources.length]; int tagIndex = 0; for (String resource : resources) { // Try to find the resource relative to the package. URL resourceURL = tryFindResource(locator, getPathRelativeToPackage( method.getEnclosingType().getPackage(), resource), locale); // If we didn't find the resource relative to the package, assume it is // absolute. if (resourceURL == null) { resourceURL = tryFindResource(locator, resource, locale); } if (resourceURL == null) { error = true; if (reportErrors) { logger.log(TreeLogger.ERROR, "Resource " + resource + " not found. Is the name specified as Class.getResource()" + " would expect?"); } else { // Speculative attempts should not emit errors logger.log(TreeLogger.DEBUG, "Stopping because " + resource + " not found"); } } toReturn[tagIndex++] = resourceURL; } } - if (error && reportErrors) { - throw new UnableToCompleteException(); + if (error) { + if (reportErrors) { + throw new UnableToCompleteException(); + } else { + return null; + } } return toReturn; } /** * Converts a package relative path into an absolute path. * * @param pkg the package * @param path a path relative to the package * @return an absolute path */ private static String getPathRelativeToPackage(JPackage pkg, String path) { return pkg.getName().replace('.', '/') + '/' + path; } /** * This performs the locale lookup function for a given resource name. * * @param locator the Locator to use to load the resources * @param resourceName the string name of the desired resource * @param locale the locale of the current rebind permutation * @return a URL by which the resource can be loaded, <code>null</code> if one * cannot be found */ private static URL tryFindResource(Locator locator, String resourceName, String locale) { URL toReturn = null; // Look for locale-specific variants of individual resources if (locale != null) { // Convert language_country_variant to independent pieces String[] localeSegments = locale.split("_"); int lastDot = resourceName.lastIndexOf("."); String prefix = lastDot == -1 ? resourceName : resourceName.substring(0, lastDot); String extension = lastDot == -1 ? "" : resourceName.substring(lastDot); for (int i = localeSegments.length - 1; i >= -1; i--) { String localeInsert = ""; for (int j = 0; j <= i; j++) { localeInsert += "_" + localeSegments[j]; } toReturn = locator.locate(prefix + localeInsert + extension); if (toReturn != null) { break; } } } else { toReturn = locator.locate(resourceName); } return toReturn; } /** * Utility class. */ private ResourceGeneratorUtil() { } }
true
true
private static URL[] findResources(TreeLogger logger, Locator locator, ResourceContext context, JMethod method, String[] defaultSuffixes, boolean reportErrors) throws UnableToCompleteException { logger = logger.branch(TreeLogger.DEBUG, "Finding resources"); String locale; try { PropertyOracle oracle = context.getGeneratorContext().getPropertyOracle(); SelectionProperty prop = oracle.getSelectionProperty(logger, "locale"); locale = prop.getCurrentValue(); } catch (BadPropertyValueException e) { locale = null; } checkForDeprecatedAnnotations(logger, method); boolean error = false; Source resourceAnnotation = method.getAnnotation(Source.class); URL[] toReturn; if (resourceAnnotation == null) { if (defaultSuffixes != null) { for (String extension : defaultSuffixes) { logger.log(TreeLogger.SPAM, "Trying default extension " + extension); URL resourceUrl = tryFindResource(locator, getPathRelativeToPackage( method.getEnclosingType().getPackage(), method.getName() + extension), locale); if (resourceUrl != null) { // Early out because we found a hit return new URL[] {resourceUrl}; } } } if (reportErrors) { logger.log(TreeLogger.ERROR, "No " + Source.class.getName() + " annotation and no resources found with default extensions"); } toReturn = null; error = true; } else { // The user has put an @Source annotation on the accessor method String[] resources = resourceAnnotation.value(); toReturn = new URL[resources.length]; int tagIndex = 0; for (String resource : resources) { // Try to find the resource relative to the package. URL resourceURL = tryFindResource(locator, getPathRelativeToPackage( method.getEnclosingType().getPackage(), resource), locale); // If we didn't find the resource relative to the package, assume it is // absolute. if (resourceURL == null) { resourceURL = tryFindResource(locator, resource, locale); } if (resourceURL == null) { error = true; if (reportErrors) { logger.log(TreeLogger.ERROR, "Resource " + resource + " not found. Is the name specified as Class.getResource()" + " would expect?"); } else { // Speculative attempts should not emit errors logger.log(TreeLogger.DEBUG, "Stopping because " + resource + " not found"); } } toReturn[tagIndex++] = resourceURL; } } if (error && reportErrors) { throw new UnableToCompleteException(); } return toReturn; }
private static URL[] findResources(TreeLogger logger, Locator locator, ResourceContext context, JMethod method, String[] defaultSuffixes, boolean reportErrors) throws UnableToCompleteException { logger = logger.branch(TreeLogger.DEBUG, "Finding resources"); String locale; try { PropertyOracle oracle = context.getGeneratorContext().getPropertyOracle(); SelectionProperty prop = oracle.getSelectionProperty(logger, "locale"); locale = prop.getCurrentValue(); } catch (BadPropertyValueException e) { locale = null; } checkForDeprecatedAnnotations(logger, method); boolean error = false; Source resourceAnnotation = method.getAnnotation(Source.class); URL[] toReturn; if (resourceAnnotation == null) { if (defaultSuffixes != null) { for (String extension : defaultSuffixes) { logger.log(TreeLogger.SPAM, "Trying default extension " + extension); URL resourceUrl = tryFindResource(locator, getPathRelativeToPackage( method.getEnclosingType().getPackage(), method.getName() + extension), locale); if (resourceUrl != null) { // Early out because we found a hit return new URL[] {resourceUrl}; } } } if (reportErrors) { logger.log(TreeLogger.ERROR, "No " + Source.class.getName() + " annotation and no resources found with default extensions"); } toReturn = null; error = true; } else { // The user has put an @Source annotation on the accessor method String[] resources = resourceAnnotation.value(); toReturn = new URL[resources.length]; int tagIndex = 0; for (String resource : resources) { // Try to find the resource relative to the package. URL resourceURL = tryFindResource(locator, getPathRelativeToPackage( method.getEnclosingType().getPackage(), resource), locale); // If we didn't find the resource relative to the package, assume it is // absolute. if (resourceURL == null) { resourceURL = tryFindResource(locator, resource, locale); } if (resourceURL == null) { error = true; if (reportErrors) { logger.log(TreeLogger.ERROR, "Resource " + resource + " not found. Is the name specified as Class.getResource()" + " would expect?"); } else { // Speculative attempts should not emit errors logger.log(TreeLogger.DEBUG, "Stopping because " + resource + " not found"); } } toReturn[tagIndex++] = resourceURL; } } if (error) { if (reportErrors) { throw new UnableToCompleteException(); } else { return null; } } return toReturn; }
diff --git a/src/main/java/com/md_5/spigot/Spigot.java b/src/main/java/com/md_5/spigot/Spigot.java index eb70fcf..0da4016 100644 --- a/src/main/java/com/md_5/spigot/Spigot.java +++ b/src/main/java/com/md_5/spigot/Spigot.java @@ -1,416 +1,418 @@ package com.md_5.spigot; import java.io.File; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.net.InetAddress; import java.net.ServerSocket; import java.net.UnknownHostException; import java.util.Map; import net.minecraft.server.Block; import net.minecraft.server.ChunkCoordinates; import net.minecraft.server.ConvertProgressUpdater; import net.minecraft.server.Convertable; import net.minecraft.server.EntityTracker; import net.minecraft.server.IProgressUpdate; import net.minecraft.server.IWorldAccess; import net.minecraft.server.MinecraftServer; import net.minecraft.server.NetworkListenThread; import net.minecraft.server.ServerNBTManager; import net.minecraft.server.WorldLoaderServer; import net.minecraft.server.WorldManager; import net.minecraft.server.WorldMapCollection; import net.minecraft.server.WorldServer; import net.minecraft.server.WorldSettings; import net.minecraft.server.WorldType; import org.bukkit.World; import org.bukkit.WorldCreator; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.CraftWorld; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.AsyncPlayerPreLoginEvent; import org.bukkit.event.player.PlayerLoginEvent; import org.bukkit.event.player.PlayerPreLoginEvent; import org.bukkit.event.world.WorldInitEvent; import org.bukkit.event.world.WorldLoadEvent; import org.bukkit.event.world.WorldSaveEvent; import org.bukkit.event.world.WorldUnloadEvent; import org.bukkit.generator.ChunkGenerator; import org.bukkit.plugin.java.JavaPlugin; public class Spigot extends JavaPlugin implements Listener { public static Spigot instance; // private String restartScriptLocation; private int timeoutTime; private boolean restartOnCrash; private boolean filterUnsafeIps; private String whitelistMessage; // private WatchdogThread watchdog; // private MinecraftServer console; private Map<String, World> worlds; @Override public void onEnable() { instance = this; // FileConfiguration conf = getConfig(); conf.options().copyDefaults(true); saveConfig(); restartScriptLocation = conf.getString("restart-script-location"); timeoutTime = conf.getInt("timeout-time"); restartOnCrash = conf.getBoolean("restart-on-crash"); filterUnsafeIps = conf.getBoolean("filter-unsafe-ips"); whitelistMessage = conf.getString("whitelist-message"); // console = ((CraftServer) getServer()).getHandle().server; worlds = (Map<String, World>) getPrivate(console.server, "worlds");; console.primaryThread.setUncaughtExceptionHandler(new ExceptionHandler()); // hijackWorlds(); // watchdog = new WatchdogThread(timeoutTime * 1000L, restartOnCrash); getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable() { public void run() { watchdog.tick(); } }, 1, 1); // register(); // getServer().getPluginManager().registerEvents(this, this); } private void hijackWorlds() { for (org.bukkit.World w : getServer().getWorlds()) { WorldCreator creator = new WorldCreator(w.getName()); creator.seed(w.getSeed()); creator.environment(w.getEnvironment()); creator.generator(w.getGenerator()); creator.type(w.getWorldType()); creator.generateStructures(w.canGenerateStructures()); // int dimension = ((CraftWorld) w).getHandle().dimension; int gamemode = getServer().getDefaultGameMode().getValue(); WorldMapCollection maps = ((CraftWorld) w).getHandle().worldMaps; // unloadWorld(w, true); getLogger().info("Unloaded world " + w.getName()); // createWorld(creator, gamemode, maps, dimension); } } private void register() { for (int i = 0; i < 255; i++) { Block old = Block.byId[i]; boolean n = Block.n[i]; int lightBlock = Block.lightBlock[i]; boolean p = Block.p[i]; int lightEmission = Block.lightEmission[i]; boolean r = Block.r[i]; boolean s = Block.s[i]; // Block.byId[i] = null; Block replaced = null; switch (i) { case 2: //replaced = new SpecialGrass(i); break; case 6: replaced = new SpecialSapling(i, 15); break; case 59: replaced = new SpecialCrops(i, 88); break; case 75: replaced = new SpecialRedstoneTorch(i, 115, false); break; case 76: replaced = new SpecialRedstoneTorch(i, 99, true); break; case 81: replaced = new SpecialCactus(i, 70); break; case 83: replaced = new SpecialReed(i, 71); break; case 104: replaced = new SpecialStem(i, Block.PUMPKIN); break; case 105: replaced = new SpecialStem(i, Block.MELON); break; } if (replaced != null) { getLogger().info("Replaced block id: " + replaced.id); } else { Block.byId[i] = old; } // Block.n[i] = n; Block.lightBlock[i] = lightBlock; Block.p[i] = p; Block.lightEmission[i] = lightEmission; Block.r[i] = r; Block.s[i] = s; } } @Override public void onDisable() { watchdog.interrupt(); try { watchdog.join(); } catch (InterruptedException ex) { } } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { restart(); return true; } @EventHandler public void onAsyncPlayerPreLogin(AsyncPlayerPreLoginEvent event) { if (filterUnsafeIps) { try { String ip = event.getAddress().getHostAddress(); String[] split = ip.split("\\."); StringBuilder lookup = new StringBuilder(); for (int i = split.length - 1; i >= 0; i--) { lookup.append(split[i]); lookup.append("."); } lookup.append("xbl.spamhaus.org."); if (InetAddress.getByName(lookup.toString()) != null) { event.disallow(PlayerPreLoginEvent.Result.KICK_OTHER, "Your IP address is flagged as unsafe by spamhaus.org/xbl"); } } catch (UnknownHostException ex) { // } } } @EventHandler public void onPlayerLogin(PlayerLoginEvent event) { if (getServer().hasWhitelist() && !event.getPlayer().isWhitelisted()) { event.disallow(PlayerLoginEvent.Result.KICK_WHITELIST, whitelistMessage); } } public void restart() { try { File file = new File(restartScriptLocation); if (file.exists() && !file.isDirectory()) { System.out.println("Attempting to restart with " + restartScriptLocation); // for (Player p : getServer().getOnlinePlayers()) { p.kickPlayer("Server is restarting"); } // NetworkListenThread listenThread = ((CraftServer) getServer()).getHandle().server.networkListenThread; listenThread.b = false; // try { Thread.sleep(100); } catch (InterruptedException ex) { // } // Field field = listenThread.getClass().getDeclaredField("d"); field.setAccessible(true); ((ServerSocket) field.get(listenThread)).close(); // try { ((CraftServer) getServer()).getHandle().server.stop(); } catch (Throwable t) { // } // String os = System.getProperty("os.name").toLowerCase(); if (os.contains("win")) { Runtime.getRuntime().exec("cmd /c start " + file.getPath()); } else { Runtime.getRuntime().exec(file.getPath()); } System.exit(0); } else { System.out.println("Startup script '" + restartScriptLocation + "' does not exist!"); } } catch (Exception ex) { ex.printStackTrace(); } } public World createWorld(WorldCreator creator, int gamemode, WorldMapCollection maps,int dimension) { CraftServer craft = console.server; // if (creator == null) { throw new IllegalArgumentException("Creator may not be null"); } String name = creator.name(); ChunkGenerator generator = creator.generator(); File folder = new File(craft.getWorldContainer(), name); World world = craft.getWorld(name); WorldType type = WorldType.getType(creator.type().getName()); boolean generateStructures = creator.generateStructures(); if (world != null) { return world; } if ((folder.exists()) && (!folder.isDirectory())) { throw new IllegalArgumentException("File exists with the name '" + name + "' and isn't a folder"); } if (generator == null) { generator = craft.getGenerator(name); } Convertable converter = new WorldLoaderServer(craft.getWorldContainer()); if (converter.isConvertable(name)) { getLogger().info("Converting world '" + name + "'"); converter.convert(name, new ConvertProgressUpdater(console)); } boolean used = false; do { for (WorldServer server : console.worlds) { used = server.dimension == dimension; if (used) { dimension++; break; } } } while (used); boolean hardcore = false; WorldServer internal = new SpecialWorld(console, new ServerNBTManager(craft.getWorldContainer(), name, true), name, dimension, new WorldSettings(creator.seed(), gamemode, generateStructures, hardcore, type), creator.environment(), generator); + worlds.remove(name.toLowerCase()); + worlds.put(name.toLowerCase(), internal.getWorld()); if (!(worlds.containsKey(name.toLowerCase()))) { return null; } internal.worldMaps = maps; internal.tracker = new EntityTracker(console, internal); // CraftBukkit internal.addIWorldAccess((IWorldAccess) new WorldManager(console, internal)); internal.difficulty = 1; internal.setSpawnFlags(true, true); console.worlds.add(internal); if (generator != null) { internal.getWorld().getPopulators().addAll(generator.getDefaultPopulators(internal.getWorld())); } getServer().getPluginManager().callEvent(new WorldInitEvent(internal.getWorld())); System.out.print("Preparing start region for level " + (console.worlds.size() - 1) + " (Seed: " + internal.getSeed() + ")"); if (internal.getWorld().getKeepSpawnInMemory()) { short short1 = 196; long i = System.currentTimeMillis(); for (int j = -short1; j <= short1; j += 16) { for (int k = -short1; k <= short1; k += 16) { long l = System.currentTimeMillis(); if (l < i) { i = l; } if (l > i + 1000L) { int i1 = (short1 * 2 + 1) * (short1 * 2 + 1); int j1 = (j + short1) * (short1 * 2 + 1) + k + 1; System.out.println("Preparing spawn area for " + name + ", " + (j1 * 100 / i1) + "%"); i = l; } ChunkCoordinates chunkcoordinates = internal.getSpawn(); internal.chunkProviderServer.getChunkAt(chunkcoordinates.x + j >> 4, chunkcoordinates.z + k >> 4); while (internal.updateLights()) { ; } } } } getServer().getPluginManager().callEvent(new WorldLoadEvent(internal.getWorld())); return internal.getWorld(); } public boolean unloadWorld(World world, boolean save) { if (world == null) { return false; } WorldServer handle = ((CraftWorld) world).getHandle(); if (!(console.worlds.contains(handle))) { return false; } /* if (!(handle.dimension > 1)) { return false; } */ if (handle.players.size() > 0) { return false; } WorldUnloadEvent e = new WorldUnloadEvent(handle.getWorld()); getServer().getPluginManager().callEvent(e); if (e.isCancelled()) { return false; } if (save) { handle.save(true, (IProgressUpdate) null); handle.saveLevel(); WorldSaveEvent event = new WorldSaveEvent(handle.getWorld()); getServer().getPluginManager().callEvent(event); } worlds.remove(world.getName().toLowerCase()); console.worlds.remove(console.worlds.indexOf(handle)); return true; } private Object getPrivate(Object clazz, String field) { Object result = null; try { Field f = clazz.getClass().getDeclaredField(field); f.setAccessible(true); result = f.get(clazz); } catch (Exception ex) { ex.printStackTrace(); } return result; } public static void setPrivate(Class clazz, Object obj, String field, Object value) { try { Field f = clazz.getDeclaredField(field); f.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(f, f.getModifiers() & ~Modifier.FINAL); f.set(obj, value); } catch (Exception ex) { ex.printStackTrace(); } } }
true
true
public World createWorld(WorldCreator creator, int gamemode, WorldMapCollection maps,int dimension) { CraftServer craft = console.server; // if (creator == null) { throw new IllegalArgumentException("Creator may not be null"); } String name = creator.name(); ChunkGenerator generator = creator.generator(); File folder = new File(craft.getWorldContainer(), name); World world = craft.getWorld(name); WorldType type = WorldType.getType(creator.type().getName()); boolean generateStructures = creator.generateStructures(); if (world != null) { return world; } if ((folder.exists()) && (!folder.isDirectory())) { throw new IllegalArgumentException("File exists with the name '" + name + "' and isn't a folder"); } if (generator == null) { generator = craft.getGenerator(name); } Convertable converter = new WorldLoaderServer(craft.getWorldContainer()); if (converter.isConvertable(name)) { getLogger().info("Converting world '" + name + "'"); converter.convert(name, new ConvertProgressUpdater(console)); } boolean used = false; do { for (WorldServer server : console.worlds) { used = server.dimension == dimension; if (used) { dimension++; break; } } } while (used); boolean hardcore = false; WorldServer internal = new SpecialWorld(console, new ServerNBTManager(craft.getWorldContainer(), name, true), name, dimension, new WorldSettings(creator.seed(), gamemode, generateStructures, hardcore, type), creator.environment(), generator); if (!(worlds.containsKey(name.toLowerCase()))) { return null; } internal.worldMaps = maps; internal.tracker = new EntityTracker(console, internal); // CraftBukkit internal.addIWorldAccess((IWorldAccess) new WorldManager(console, internal)); internal.difficulty = 1; internal.setSpawnFlags(true, true); console.worlds.add(internal); if (generator != null) { internal.getWorld().getPopulators().addAll(generator.getDefaultPopulators(internal.getWorld())); } getServer().getPluginManager().callEvent(new WorldInitEvent(internal.getWorld())); System.out.print("Preparing start region for level " + (console.worlds.size() - 1) + " (Seed: " + internal.getSeed() + ")"); if (internal.getWorld().getKeepSpawnInMemory()) { short short1 = 196; long i = System.currentTimeMillis(); for (int j = -short1; j <= short1; j += 16) { for (int k = -short1; k <= short1; k += 16) { long l = System.currentTimeMillis(); if (l < i) { i = l; } if (l > i + 1000L) { int i1 = (short1 * 2 + 1) * (short1 * 2 + 1); int j1 = (j + short1) * (short1 * 2 + 1) + k + 1; System.out.println("Preparing spawn area for " + name + ", " + (j1 * 100 / i1) + "%"); i = l; } ChunkCoordinates chunkcoordinates = internal.getSpawn(); internal.chunkProviderServer.getChunkAt(chunkcoordinates.x + j >> 4, chunkcoordinates.z + k >> 4); while (internal.updateLights()) { ; } } } } getServer().getPluginManager().callEvent(new WorldLoadEvent(internal.getWorld())); return internal.getWorld(); }
public World createWorld(WorldCreator creator, int gamemode, WorldMapCollection maps,int dimension) { CraftServer craft = console.server; // if (creator == null) { throw new IllegalArgumentException("Creator may not be null"); } String name = creator.name(); ChunkGenerator generator = creator.generator(); File folder = new File(craft.getWorldContainer(), name); World world = craft.getWorld(name); WorldType type = WorldType.getType(creator.type().getName()); boolean generateStructures = creator.generateStructures(); if (world != null) { return world; } if ((folder.exists()) && (!folder.isDirectory())) { throw new IllegalArgumentException("File exists with the name '" + name + "' and isn't a folder"); } if (generator == null) { generator = craft.getGenerator(name); } Convertable converter = new WorldLoaderServer(craft.getWorldContainer()); if (converter.isConvertable(name)) { getLogger().info("Converting world '" + name + "'"); converter.convert(name, new ConvertProgressUpdater(console)); } boolean used = false; do { for (WorldServer server : console.worlds) { used = server.dimension == dimension; if (used) { dimension++; break; } } } while (used); boolean hardcore = false; WorldServer internal = new SpecialWorld(console, new ServerNBTManager(craft.getWorldContainer(), name, true), name, dimension, new WorldSettings(creator.seed(), gamemode, generateStructures, hardcore, type), creator.environment(), generator); worlds.remove(name.toLowerCase()); worlds.put(name.toLowerCase(), internal.getWorld()); if (!(worlds.containsKey(name.toLowerCase()))) { return null; } internal.worldMaps = maps; internal.tracker = new EntityTracker(console, internal); // CraftBukkit internal.addIWorldAccess((IWorldAccess) new WorldManager(console, internal)); internal.difficulty = 1; internal.setSpawnFlags(true, true); console.worlds.add(internal); if (generator != null) { internal.getWorld().getPopulators().addAll(generator.getDefaultPopulators(internal.getWorld())); } getServer().getPluginManager().callEvent(new WorldInitEvent(internal.getWorld())); System.out.print("Preparing start region for level " + (console.worlds.size() - 1) + " (Seed: " + internal.getSeed() + ")"); if (internal.getWorld().getKeepSpawnInMemory()) { short short1 = 196; long i = System.currentTimeMillis(); for (int j = -short1; j <= short1; j += 16) { for (int k = -short1; k <= short1; k += 16) { long l = System.currentTimeMillis(); if (l < i) { i = l; } if (l > i + 1000L) { int i1 = (short1 * 2 + 1) * (short1 * 2 + 1); int j1 = (j + short1) * (short1 * 2 + 1) + k + 1; System.out.println("Preparing spawn area for " + name + ", " + (j1 * 100 / i1) + "%"); i = l; } ChunkCoordinates chunkcoordinates = internal.getSpawn(); internal.chunkProviderServer.getChunkAt(chunkcoordinates.x + j >> 4, chunkcoordinates.z + k >> 4); while (internal.updateLights()) { ; } } } } getServer().getPluginManager().callEvent(new WorldLoadEvent(internal.getWorld())); return internal.getWorld(); }
diff --git a/src/BombWall.java b/src/BombWall.java index d998be1..72bacf2 100644 --- a/src/BombWall.java +++ b/src/BombWall.java @@ -1,35 +1,35 @@ import org.newdawn.slick.opengl.Texture; public class BombWall extends Entity { protected Texture bombWall; public BombWall(Game ingame,int hp) { game = ingame; - bombWall = loadTexture("brick.jpg"); - Shot = loadTexture("brickShot.jpg"); + bombWall = loadTexture("bombWall.png"); + Shot = loadTexture("bombWallShot.png"); width = game.map.TILE_SIZE; height = game.map.TILE_SIZE; halfSize = width/2; HP = hp; maxHP = HP; } public void draw() { super.draw(bombWall); if(shoted){ super.draw(Shot); } if(showHP){ drawHP(); } } @Override public void collidedWith(Entity other) { if(other instanceof Bullet){ shoted = true; } } }
true
true
public BombWall(Game ingame,int hp) { game = ingame; bombWall = loadTexture("brick.jpg"); Shot = loadTexture("brickShot.jpg"); width = game.map.TILE_SIZE; height = game.map.TILE_SIZE; halfSize = width/2; HP = hp; maxHP = HP; }
public BombWall(Game ingame,int hp) { game = ingame; bombWall = loadTexture("bombWall.png"); Shot = loadTexture("bombWallShot.png"); width = game.map.TILE_SIZE; height = game.map.TILE_SIZE; halfSize = width/2; HP = hp; maxHP = HP; }
diff --git a/javafx.editor/src/org/netbeans/modules/javafx/editor/GoToSupport.java b/javafx.editor/src/org/netbeans/modules/javafx/editor/GoToSupport.java index b6a32f76..a336c3a3 100644 --- a/javafx.editor/src/org/netbeans/modules/javafx/editor/GoToSupport.java +++ b/javafx.editor/src/org/netbeans/modules/javafx/editor/GoToSupport.java @@ -1,303 +1,303 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): * * The Original Software is NetBeans. The Initial Developer of the Original * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun * Microsystems, Inc. All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. */ package org.netbeans.modules.javafx.editor; import com.sun.javafx.api.tree.JavaFXTreePath; import com.sun.javafx.api.tree.Tree; import com.sun.tools.mjavac.code.Symbol; import com.sun.tools.mjavac.code.Type; import com.sun.tools.javafx.code.JavafxTypes; import java.io.IOException; import java.net.URL; import java.util.EnumSet; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import javax.lang.model.element.Element; import javax.lang.model.element.VariableElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeKind; import javax.swing.SwingUtilities; import javax.swing.text.Document; import javax.swing.text.StyledDocument; import org.netbeans.api.javafx.editor.Cancellable; import org.netbeans.api.javafx.editor.ElementOpen; import org.netbeans.api.javafx.editor.FXSourceUtils; import org.netbeans.api.javafx.editor.FXSourceUtils.URLResult; import org.netbeans.api.javafx.editor.SafeTokenSequence; import org.netbeans.api.javafx.lexer.JFXTokenId; import org.netbeans.api.javafx.source.CompilationController; import org.netbeans.api.javafx.source.JavaFXSource; import org.netbeans.api.javafx.source.JavaFXSource.Phase; import org.netbeans.api.javafx.source.Task; import org.netbeans.api.lexer.Token; import org.netbeans.api.lexer.TokenHierarchy; import org.netbeans.api.lexer.TokenSequence; import org.openide.awt.HtmlBrowser; import org.openide.cookies.EditorCookie; import org.openide.cookies.LineCookie; import org.openide.cookies.OpenCookie; import org.openide.filesystems.FileObject; import org.openide.loaders.DataObject; import org.openide.text.Line; import org.openide.text.NbDocument; import org.openide.util.NbBundle; /** * * @author Petr Nejedly */ public class GoToSupport { /** Static utility class */ private GoToSupport() { } public static void goTo(Document doc, int offset, boolean goToSource) { performGoTo(doc, offset, goToSource, false, false); } public static void goToJavadoc(Document doc, int offset) { performGoTo(doc, offset, false, false, true); } public static String getGoToElementTooltip(Document doc, final int offset, final boolean goToSource) { return performGoTo(doc, offset, goToSource, true, false); } private static FileObject getFileObject(Document doc) { DataObject od = (DataObject) doc.getProperty(Document.StreamDescriptionProperty); return od != null ? od.getPrimaryFile() : null; } private static String performGoTo(final Document doc, final int off, final boolean goToSource, final boolean tooltip, final boolean javadoc) { final FileObject fo = getFileObject(doc); if (fo == null) return null; final JavaFXSource js = JavaFXSource.forFileObject(fo); if (js == null) return null; final String[] result = new String[1]; final AtomicBoolean cancelled = new AtomicBoolean(); final Runnable opener = new Runnable() { public void run() { try { js.runUserActionTask(new Task<CompilationController>() { public void run(final CompilationController controller) throws Exception { if (controller.toPhase(Phase.ANALYZED).lessThan(Phase.ANALYZED)) return; @SuppressWarnings("unchecked") Token<JFXTokenId>[] token = new Token[1]; int[] span = getIdentifierSpan(doc, off, token); if (span == null) { // CALLER.beep(goToSource, javadoc); return ; } final int offset = span[0] + 1; JavaFXTreePath path = controller.getTreeUtilities().pathFor(offset); Tree leaf = path.getLeaf(); if (leaf == null) return; Element el = controller.getTrees().getElement(path); if (el == null) return; if (tooltip) { result[0] = FXSourceUtils.getElementTooltip(controller.getJavafxTypes(), el); return; } else if (javadoc) { result[0] = null; final URLResult res = FXSourceUtils.getJavadoc(el, controller); URL url = res != null ? res.url : null; if (url != null) { HtmlBrowser.URLDisplayer.getDefault().showURL(url); } else { // CALLER.beep(goToSource, javadoc); } } else { if (goToSource && el instanceof VariableElement) { Symbol sym = (Symbol)el; Type type = sym.asType(); // handle sequences as their element type JavafxTypes types = controller.getJavafxTypes(); if (types.isSequence(type)) { type = types.elementType(type); } if (type != null && type.getKind() == TypeKind.DECLARED) { el = ((DeclaredType)type).asElement(); if (el == null) return; } } JavaFXTreePath elpath = controller.getPath(el); Tree tree = elpath != null && path.getCompilationUnit() == elpath.getCompilationUnit()? elpath.getLeaf(): null; if (!cancelled.get()) { if (tree != null) { long startPos = controller.getTrees().getSourcePositions().getStartPosition(controller.getCompilationUnit(), tree); if (startPos != -1l) doOpen(fo, (int)startPos); } else { final Element opening = el; SwingUtilities.invokeLater(new Runnable() { public void run() { try { ElementOpen.open(controller, opening); } catch (Exception e) {} } }); } } } } }, true); } catch (IOException ioe) { throw new IllegalStateException(ioe); } } }; if (tooltip) { opener.run(); } else { RunOffAWT.runOffAWT(new Runnable() { public void run() { opener.run(); } - }, NbBundle.getMessage(GoToSupport.class, "LBL_GoToSupport"), cancelled); // NOI18N + }, NbBundle.getMessage(GoToSupport.class, "LBL_GoToSource"), cancelled); // NOI18N } return result[0]; } private static final Set<JFXTokenId> USABLE_TOKEN_IDS = EnumSet.of(JFXTokenId.IDENTIFIER, JFXTokenId.THIS, JFXTokenId.SUPER); public static int[] getIdentifierSpan(Document doc, int offset, Token<JFXTokenId>[] token) { if (getFileObject(doc) == null) { //do nothing if FO is not attached to the document - the goto would not work anyway: return null; } TokenHierarchy th = TokenHierarchy.get(doc); @SuppressWarnings("unchecked") TokenSequence<JFXTokenId> ts_ = (TokenSequence<JFXTokenId>) th.tokenSequence(); SafeTokenSequence<JFXTokenId> ts = new SafeTokenSequence<JFXTokenId>(ts_, doc, Cancellable.Dummy.getInstance()); if (ts == null) return null; ts.move(offset); if (!ts.moveNext()) return null; Token<JFXTokenId> t = ts.token(); if (!USABLE_TOKEN_IDS.contains(t.id())) { ts.move(offset - 1); if (!ts.moveNext()) return null; t = ts.token(); if (!USABLE_TOKEN_IDS.contains(t.id())) return null; } if (token != null) token[0] = t; return new int [] {ts.offset(), ts.offset() + t.length()}; } public static boolean doOpen(FileObject fo, int offset) { try { DataObject od = DataObject.find(fo); EditorCookie ec = od.getCookie(EditorCookie.class); LineCookie lc = od.getCookie(LineCookie.class); if (ec != null && lc != null && offset != -1) { StyledDocument doc = ec.openDocument(); if (doc != null) { int line = NbDocument.findLineNumber(doc, offset); int lineOffset = NbDocument.findLineOffset(doc, line); final int column = offset - lineOffset; if (line != -1) { final Line l = lc.getLineSet().getCurrent(line); if (l != null) { SwingUtilities.invokeLater(new Runnable() { public void run() { l.show(Line.ShowOpenType.OPEN, Line.ShowVisibilityType.FOCUS, column); } }); return true; } } } } OpenCookie oc = od.getCookie(OpenCookie.class); if (oc != null) { oc.open(); return true; } } catch (IOException e) { } return false; } }
true
true
private static String performGoTo(final Document doc, final int off, final boolean goToSource, final boolean tooltip, final boolean javadoc) { final FileObject fo = getFileObject(doc); if (fo == null) return null; final JavaFXSource js = JavaFXSource.forFileObject(fo); if (js == null) return null; final String[] result = new String[1]; final AtomicBoolean cancelled = new AtomicBoolean(); final Runnable opener = new Runnable() { public void run() { try { js.runUserActionTask(new Task<CompilationController>() { public void run(final CompilationController controller) throws Exception { if (controller.toPhase(Phase.ANALYZED).lessThan(Phase.ANALYZED)) return; @SuppressWarnings("unchecked") Token<JFXTokenId>[] token = new Token[1]; int[] span = getIdentifierSpan(doc, off, token); if (span == null) { // CALLER.beep(goToSource, javadoc); return ; } final int offset = span[0] + 1; JavaFXTreePath path = controller.getTreeUtilities().pathFor(offset); Tree leaf = path.getLeaf(); if (leaf == null) return; Element el = controller.getTrees().getElement(path); if (el == null) return; if (tooltip) { result[0] = FXSourceUtils.getElementTooltip(controller.getJavafxTypes(), el); return; } else if (javadoc) { result[0] = null; final URLResult res = FXSourceUtils.getJavadoc(el, controller); URL url = res != null ? res.url : null; if (url != null) { HtmlBrowser.URLDisplayer.getDefault().showURL(url); } else { // CALLER.beep(goToSource, javadoc); } } else { if (goToSource && el instanceof VariableElement) { Symbol sym = (Symbol)el; Type type = sym.asType(); // handle sequences as their element type JavafxTypes types = controller.getJavafxTypes(); if (types.isSequence(type)) { type = types.elementType(type); } if (type != null && type.getKind() == TypeKind.DECLARED) { el = ((DeclaredType)type).asElement(); if (el == null) return; } } JavaFXTreePath elpath = controller.getPath(el); Tree tree = elpath != null && path.getCompilationUnit() == elpath.getCompilationUnit()? elpath.getLeaf(): null; if (!cancelled.get()) { if (tree != null) { long startPos = controller.getTrees().getSourcePositions().getStartPosition(controller.getCompilationUnit(), tree); if (startPos != -1l) doOpen(fo, (int)startPos); } else { final Element opening = el; SwingUtilities.invokeLater(new Runnable() { public void run() { try { ElementOpen.open(controller, opening); } catch (Exception e) {} } }); } } } } }, true); } catch (IOException ioe) { throw new IllegalStateException(ioe); } } }; if (tooltip) { opener.run(); } else { RunOffAWT.runOffAWT(new Runnable() { public void run() { opener.run(); } }, NbBundle.getMessage(GoToSupport.class, "LBL_GoToSupport"), cancelled); // NOI18N } return result[0]; }
private static String performGoTo(final Document doc, final int off, final boolean goToSource, final boolean tooltip, final boolean javadoc) { final FileObject fo = getFileObject(doc); if (fo == null) return null; final JavaFXSource js = JavaFXSource.forFileObject(fo); if (js == null) return null; final String[] result = new String[1]; final AtomicBoolean cancelled = new AtomicBoolean(); final Runnable opener = new Runnable() { public void run() { try { js.runUserActionTask(new Task<CompilationController>() { public void run(final CompilationController controller) throws Exception { if (controller.toPhase(Phase.ANALYZED).lessThan(Phase.ANALYZED)) return; @SuppressWarnings("unchecked") Token<JFXTokenId>[] token = new Token[1]; int[] span = getIdentifierSpan(doc, off, token); if (span == null) { // CALLER.beep(goToSource, javadoc); return ; } final int offset = span[0] + 1; JavaFXTreePath path = controller.getTreeUtilities().pathFor(offset); Tree leaf = path.getLeaf(); if (leaf == null) return; Element el = controller.getTrees().getElement(path); if (el == null) return; if (tooltip) { result[0] = FXSourceUtils.getElementTooltip(controller.getJavafxTypes(), el); return; } else if (javadoc) { result[0] = null; final URLResult res = FXSourceUtils.getJavadoc(el, controller); URL url = res != null ? res.url : null; if (url != null) { HtmlBrowser.URLDisplayer.getDefault().showURL(url); } else { // CALLER.beep(goToSource, javadoc); } } else { if (goToSource && el instanceof VariableElement) { Symbol sym = (Symbol)el; Type type = sym.asType(); // handle sequences as their element type JavafxTypes types = controller.getJavafxTypes(); if (types.isSequence(type)) { type = types.elementType(type); } if (type != null && type.getKind() == TypeKind.DECLARED) { el = ((DeclaredType)type).asElement(); if (el == null) return; } } JavaFXTreePath elpath = controller.getPath(el); Tree tree = elpath != null && path.getCompilationUnit() == elpath.getCompilationUnit()? elpath.getLeaf(): null; if (!cancelled.get()) { if (tree != null) { long startPos = controller.getTrees().getSourcePositions().getStartPosition(controller.getCompilationUnit(), tree); if (startPos != -1l) doOpen(fo, (int)startPos); } else { final Element opening = el; SwingUtilities.invokeLater(new Runnable() { public void run() { try { ElementOpen.open(controller, opening); } catch (Exception e) {} } }); } } } } }, true); } catch (IOException ioe) { throw new IllegalStateException(ioe); } } }; if (tooltip) { opener.run(); } else { RunOffAWT.runOffAWT(new Runnable() { public void run() { opener.run(); } }, NbBundle.getMessage(GoToSupport.class, "LBL_GoToSource"), cancelled); // NOI18N } return result[0]; }
diff --git a/org.caleydo.core/src/org/caleydo/core/data/perspective/table/TablePerspectiveStatistics.java b/org.caleydo.core/src/org/caleydo/core/data/perspective/table/TablePerspectiveStatistics.java index 55bbf1ad9..0171000a5 100644 --- a/org.caleydo.core/src/org/caleydo/core/data/perspective/table/TablePerspectiveStatistics.java +++ b/org.caleydo.core/src/org/caleydo/core/data/perspective/table/TablePerspectiveStatistics.java @@ -1,345 +1,345 @@ /******************************************************************************* * Caleydo - visualization for molecular biology - http://caleydo.org * * Copyright(C) 2005, 2012 Graz University of Technology, Marc Streit, Alexander Lex, Christian Partl, Johannes Kepler * University Linz </p> * * 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 org.caleydo.core.data.perspective.table; import java.util.ArrayList; import java.util.Collection; import org.caleydo.core.data.collection.Histogram; import org.caleydo.core.data.collection.table.Table; import org.caleydo.core.data.datadomain.ATableBasedDataDomain; import org.caleydo.core.data.perspective.variable.Perspective; import org.caleydo.core.data.perspective.variable.PerspectiveInitializationData; import org.caleydo.core.data.virtualarray.VirtualArray; import org.caleydo.core.id.IDMappingManagerRegistry; import org.caleydo.core.id.IDType; /** * <p> * {@link TablePerspectiveStatistics} provides access and calculates derivable meta-data for the data specified by a * {@link TablePerspective}, such as averages, histograms, etc. * </p> * <p> * Everything is calculated lazily. * </p> * <p> * TODO: There is currently no way to mark this dirty once the perspectives in the container or the container itself * changed. * </p> * * @author Alexander Lex */ public class TablePerspectiveStatistics { /** The table perspective to which we compare **/ private TablePerspective referenceTablePerspective; /** The average of all cells in the container */ private float averageValue = Float.NEGATIVE_INFINITY; /** The histogram for the data in this container along the dimensions */ private Histogram histogram = null; /** The fold-change properties of this container with another container */ private FoldChange foldChange; private TTest tTest; /** * Optionally it is possible to specify the number of bins for the histogram manually. This should only be done if * there really is a reason for it. */ private int numberOfBucketsForHistogram = Integer.MIN_VALUE; /** * A list of averages across dimensions, one for every record in the data container. Sorted as the virtual array. */ private ArrayList<Average> averageRecords; /** Same as {@link #averageRecords} for dimensions */ private ArrayList<Average> averageDimensions; public TablePerspectiveStatistics(TablePerspective referenceTablePerspective) { this.referenceTablePerspective = referenceTablePerspective; } /** * @return the averageValue, see {@link #averageValue} */ public double getAverageValue() { if (Float.isInfinite(averageValue)) calculateAverageValue(); return averageValue; } private void calculateAverageValue() { averageValue = 0; int count = 0; for (Integer recordID : referenceTablePerspective.getRecordPerspective().getVirtualArray()) { VirtualArray dimensionVA = referenceTablePerspective.getDimensionPerspective().getVirtualArray(); if (dimensionVA == null) { averageValue = 0; return; } for (Integer dimensionID : dimensionVA) { Float value = referenceTablePerspective.getDataDomain().getTable() .getNormalizedValue(dimensionID, recordID); if (value != null && !Float.isNaN(value)) { averageValue += value; count++; } } } averageValue /= count; } /** * This is optional! Read more: {@link #numberOfBucketsForHistogram} * * @param numberOfBucketsForHistogram * setter, see {@link #numberOfBucketsForHistogram} */ public void setNumberOfBucketsForHistogram(int numberOfBucketsForHistogram) { this.numberOfBucketsForHistogram = numberOfBucketsForHistogram; } /** * @return the histogram, see {@link #histogram} */ public Histogram getHistogram() { if (histogram == null) histogram = calculateHistogram(referenceTablePerspective.getDataDomain().getTable(), referenceTablePerspective.getRecordPerspective().getVirtualArray(), referenceTablePerspective .getDimensionPerspective().getVirtualArray(), numberOfBucketsForHistogram); return histogram; } /** * Calculates a histogram for a given set of virtual arrays. One of the two VA parameters has to be a dimensionVA, * the other must be a recordVA. The order is irrelevant. * * @param table * @param va1 * @param va2 * @param numberOfBucketsForHistogram * @return */ public static Histogram calculateHistogram(Table table, VirtualArray va1, VirtualArray va2, int numberOfBucketsForHistogram) { VirtualArray recordVA, dimensionVA; if (va1.getIdType().equals(table.getDataDomain().getRecordIDType()) && va2.getIdType().equals(table.getDataDomain().getDimensionIDType())) { recordVA = va1; dimensionVA = va2; } else if (va1.getIdType().equals(table.getDataDomain().getDimensionIDType()) && va2.getIdType().equals(table.getDataDomain().getRecordIDType())) { recordVA = va2; dimensionVA = va1; } else { throw new IllegalArgumentException("Virtual arrays don't match table"); } if (!table.isDataHomogeneous()) { throw new UnsupportedOperationException( "Tried to calcualte a set-wide histogram on a not homogeneous table. This makes no sense. Use dimension based histograms instead!"); } int numberOfBuckets; if (numberOfBucketsForHistogram != Integer.MIN_VALUE) numberOfBuckets = numberOfBucketsForHistogram; else numberOfBuckets = (int) Math.sqrt(recordVA.size()); Histogram histogram = new Histogram(numberOfBuckets); for (Integer dimensionID : dimensionVA) { { for (Integer recordID : recordVA) { float value = table.getNormalizedValue(dimensionID, recordID); if (Float.isNaN(value)) { histogram.addNAN(recordID); } else { // this works because the values in the container are // already noramlized int bucketIndex = (int) (value * numberOfBuckets); if (bucketIndex == numberOfBuckets) bucketIndex--; histogram.add(bucketIndex, recordID); } } } } return histogram; } /** * @return the foldChange, see {@link #foldChange} */ public FoldChange getFoldChange() { if (foldChange == null) foldChange = new FoldChange(); return foldChange; } /** * @return the tTest, see {@link #tTest} */ public TTest getTTest() { if (tTest == null) tTest = new TTest(); return tTest; } /** * @return the averageRecords, see {@link #averageRecords} */ public ArrayList<Average> getAverageRecords() { if (averageRecords == null) calculateAverageRecords(); return averageRecords; } /** * Calculates the arithmetic mean and the standard deviation from the arithmetic mean of the records */ private void calculateAverageRecords() { averageRecords = new ArrayList<Average>(); VirtualArray dimensionVA = referenceTablePerspective.getDimensionPerspective().getVirtualArray(); VirtualArray recordVA = referenceTablePerspective.getRecordPerspective().getVirtualArray(); for (Integer recordID : recordVA) { Average averageRecord = calculateAverage(dimensionVA, referenceTablePerspective.getDataDomain().getTable(), referenceTablePerspective.getRecordPerspective().getIdType(), recordID); averageRecords.add(averageRecord); } } /** * @return the averageRecords, see {@link #averageRecords} */ public ArrayList<Average> getAverageDimensions() { if (averageDimensions == null) calculateAverageDimensions(); return averageDimensions; } /** * Calculates the arithmetic mean and the standard deviation from the arithmetic mean of the dimensions */ private void calculateAverageDimensions() { averageDimensions = new ArrayList<Average>(); VirtualArray dimensionVA = referenceTablePerspective.getDimensionPerspective().getVirtualArray(); VirtualArray recordVA = referenceTablePerspective.getRecordPerspective().getVirtualArray(); for (Integer dimensionID : dimensionVA) { Average averageDimension = calculateAverage(recordVA, referenceTablePerspective.getDataDomain().getTable(), referenceTablePerspective.getDimensionPerspective().getIdType(), dimensionID); averageDimensions.add(averageDimension); } } /** * <p> * Calculates the average and the standard deviation for the values of one dimension or record in the data table. * Whether the average is calculated for the column or row is determined by the type of the {@link VirtualArray}. * </p> * <p> * The objectID has to be of the "opposing" type, i.e., if the virtualArray is of type {@link VirtualArray}, the id * has to be a dimension id. * </p> * <p> * The std-dev is calculated in the same loop as the average, according to <a * href="http://www.strchr.com/standard_deviation_in_one_pass">this blog.</a>. The problems of this method discussed * there doesn not apply here since we use only values between 0 and 1.} * </p> * * * @param virtualArray * @param table * @param objectID * @return */ public static Average calculateAverage(VirtualArray virtualArray, Table table, IDType objectIDType, Integer objectID) { Average averageDimension = new Average(); double sumOfValues = 0; // sum of squares double sqrSum = 0; int nrValidValues = 0; ATableBasedDataDomain dataDomain = table.getDataDomain(); IDType virtualArrayIDType = virtualArray.getIdType(); IDType resolvedVAIDType = dataDomain.getPrimaryIDType(virtualArrayIDType); IDType resolvedObjectIDType = dataDomain.getPrimaryIDType(objectIDType); if (!resolvedVAIDType.equals(virtualArrayIDType)) { PerspectiveInitializationData data = new PerspectiveInitializationData(); data.setData(virtualArray); Perspective tempPerspective = new Perspective(dataDomain, virtualArrayIDType); tempPerspective.init(data); virtualArray = dataDomain.convertForeignPerspective(tempPerspective).getVirtualArray(); } Collection<Integer> ids; if (!resolvedObjectIDType.equals(objectIDType)) { ids = IDMappingManagerRegistry.get().getIDMappingManager(objectIDType) - .getID(objectIDType, resolvedObjectIDType, objectID); + .getIDAsSet(objectIDType, resolvedObjectIDType, objectID); } else { ids = new ArrayList<Integer>(1); ids.add(objectID); } if (ids == null) return null; // IDMappingManager idMappingManager = IDMappingManagerRegistry.get().getIDMappingManager(virtualArrayIDType); for (Integer virtualArrayID : virtualArray) { Float value; for (Integer id : ids) { value = table.getDataDomain().getNormalizedValue(resolvedObjectIDType, id, resolvedVAIDType, virtualArrayID); if (value != null && !value.isNaN()) { sumOfValues += value; sqrSum += Math.pow(value, 2); nrValidValues++; } } } averageDimension.arithmeticMean = sumOfValues / nrValidValues; averageDimension.standardDeviation = Math.sqrt(sqrSum / nrValidValues - (Math.pow(averageDimension.arithmeticMean, 2))); return averageDimension; } }
true
true
public static Average calculateAverage(VirtualArray virtualArray, Table table, IDType objectIDType, Integer objectID) { Average averageDimension = new Average(); double sumOfValues = 0; // sum of squares double sqrSum = 0; int nrValidValues = 0; ATableBasedDataDomain dataDomain = table.getDataDomain(); IDType virtualArrayIDType = virtualArray.getIdType(); IDType resolvedVAIDType = dataDomain.getPrimaryIDType(virtualArrayIDType); IDType resolvedObjectIDType = dataDomain.getPrimaryIDType(objectIDType); if (!resolvedVAIDType.equals(virtualArrayIDType)) { PerspectiveInitializationData data = new PerspectiveInitializationData(); data.setData(virtualArray); Perspective tempPerspective = new Perspective(dataDomain, virtualArrayIDType); tempPerspective.init(data); virtualArray = dataDomain.convertForeignPerspective(tempPerspective).getVirtualArray(); } Collection<Integer> ids; if (!resolvedObjectIDType.equals(objectIDType)) { ids = IDMappingManagerRegistry.get().getIDMappingManager(objectIDType) .getID(objectIDType, resolvedObjectIDType, objectID); } else { ids = new ArrayList<Integer>(1); ids.add(objectID); } if (ids == null) return null; // IDMappingManager idMappingManager = IDMappingManagerRegistry.get().getIDMappingManager(virtualArrayIDType); for (Integer virtualArrayID : virtualArray) { Float value; for (Integer id : ids) { value = table.getDataDomain().getNormalizedValue(resolvedObjectIDType, id, resolvedVAIDType, virtualArrayID); if (value != null && !value.isNaN()) { sumOfValues += value; sqrSum += Math.pow(value, 2); nrValidValues++; } } } averageDimension.arithmeticMean = sumOfValues / nrValidValues; averageDimension.standardDeviation = Math.sqrt(sqrSum / nrValidValues - (Math.pow(averageDimension.arithmeticMean, 2))); return averageDimension; }
public static Average calculateAverage(VirtualArray virtualArray, Table table, IDType objectIDType, Integer objectID) { Average averageDimension = new Average(); double sumOfValues = 0; // sum of squares double sqrSum = 0; int nrValidValues = 0; ATableBasedDataDomain dataDomain = table.getDataDomain(); IDType virtualArrayIDType = virtualArray.getIdType(); IDType resolvedVAIDType = dataDomain.getPrimaryIDType(virtualArrayIDType); IDType resolvedObjectIDType = dataDomain.getPrimaryIDType(objectIDType); if (!resolvedVAIDType.equals(virtualArrayIDType)) { PerspectiveInitializationData data = new PerspectiveInitializationData(); data.setData(virtualArray); Perspective tempPerspective = new Perspective(dataDomain, virtualArrayIDType); tempPerspective.init(data); virtualArray = dataDomain.convertForeignPerspective(tempPerspective).getVirtualArray(); } Collection<Integer> ids; if (!resolvedObjectIDType.equals(objectIDType)) { ids = IDMappingManagerRegistry.get().getIDMappingManager(objectIDType) .getIDAsSet(objectIDType, resolvedObjectIDType, objectID); } else { ids = new ArrayList<Integer>(1); ids.add(objectID); } if (ids == null) return null; // IDMappingManager idMappingManager = IDMappingManagerRegistry.get().getIDMappingManager(virtualArrayIDType); for (Integer virtualArrayID : virtualArray) { Float value; for (Integer id : ids) { value = table.getDataDomain().getNormalizedValue(resolvedObjectIDType, id, resolvedVAIDType, virtualArrayID); if (value != null && !value.isNaN()) { sumOfValues += value; sqrSum += Math.pow(value, 2); nrValidValues++; } } } averageDimension.arithmeticMean = sumOfValues / nrValidValues; averageDimension.standardDeviation = Math.sqrt(sqrSum / nrValidValues - (Math.pow(averageDimension.arithmeticMean, 2))); return averageDimension; }
diff --git a/src/main/java/ru/mystamps/web/config/DbConfig.java b/src/main/java/ru/mystamps/web/config/DbConfig.java index ee7c79b2..89e68a2a 100644 --- a/src/main/java/ru/mystamps/web/config/DbConfig.java +++ b/src/main/java/ru/mystamps/web/config/DbConfig.java @@ -1,99 +1,101 @@ /* * Copyright (C) 2011-2012 Slava Semushin <[email protected]> * * 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package ru.mystamps.web.config; import java.util.HashMap; import java.util.Map; import javax.inject.Inject; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.JpaVendorAdapter; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.AbstractJpaVendorAdapter; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.PlatformTransactionManager; @Configuration @EnableTransactionManagement @ImportResource("classpath:spring/database.xml") public class DbConfig { @Value("${jpa.showSql}") private String showSql; @Value("${jpa.dialectClassName}") private String dialectClassName; @Value("${hibernate.formatSql}") private String formatSql; @Value("${hibernate.hbm2ddl.auto}") private String hbm2ddl; @Inject private DataSource dataSource; @Bean public JpaVendorAdapter getJpaVendorAdapter() { final AbstractJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter(); jpaVendorAdapter.setDatabasePlatform(dialectClassName); jpaVendorAdapter.setShowSql(Boolean.valueOf(showSql)); return jpaVendorAdapter; } @Bean public LocalContainerEntityManagerFactoryBean getEntityManagerFactory() { final LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean(); entityManagerFactory.setJpaVendorAdapter(getJpaVendorAdapter()); entityManagerFactory.setDataSource(dataSource); - entityManagerFactory.setPackagesToScan(new String[] { "ru.mystamps.web.entity" }); + entityManagerFactory.setPackagesToScan(new String[] { + "ru.mystamps.web.entity" + }); final Map<String, String> jpaProperties = new HashMap<String, String>(); jpaProperties.put("hibernate.format_sql", formatSql); jpaProperties.put("hibernate.connection.charset", "UTF-8"); jpaProperties.put("hibernate.hbm2ddl.auto", hbm2ddl); entityManagerFactory.setJpaPropertyMap(jpaProperties); return entityManagerFactory; } @Bean public PlatformTransactionManager getTransactionManager() { final JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(getEntityManagerFactory().getObject()); return transactionManager; } }
true
true
public LocalContainerEntityManagerFactoryBean getEntityManagerFactory() { final LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean(); entityManagerFactory.setJpaVendorAdapter(getJpaVendorAdapter()); entityManagerFactory.setDataSource(dataSource); entityManagerFactory.setPackagesToScan(new String[] { "ru.mystamps.web.entity" }); final Map<String, String> jpaProperties = new HashMap<String, String>(); jpaProperties.put("hibernate.format_sql", formatSql); jpaProperties.put("hibernate.connection.charset", "UTF-8"); jpaProperties.put("hibernate.hbm2ddl.auto", hbm2ddl); entityManagerFactory.setJpaPropertyMap(jpaProperties); return entityManagerFactory; }
public LocalContainerEntityManagerFactoryBean getEntityManagerFactory() { final LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean(); entityManagerFactory.setJpaVendorAdapter(getJpaVendorAdapter()); entityManagerFactory.setDataSource(dataSource); entityManagerFactory.setPackagesToScan(new String[] { "ru.mystamps.web.entity" }); final Map<String, String> jpaProperties = new HashMap<String, String>(); jpaProperties.put("hibernate.format_sql", formatSql); jpaProperties.put("hibernate.connection.charset", "UTF-8"); jpaProperties.put("hibernate.hbm2ddl.auto", hbm2ddl); entityManagerFactory.setJpaPropertyMap(jpaProperties); return entityManagerFactory; }
diff --git a/src/main/java/hudson/plugins/ircbot/v2/IRCConnection.java b/src/main/java/hudson/plugins/ircbot/v2/IRCConnection.java index 104bd37..81d09ca 100644 --- a/src/main/java/hudson/plugins/ircbot/v2/IRCConnection.java +++ b/src/main/java/hudson/plugins/ircbot/v2/IRCConnection.java @@ -1,328 +1,332 @@ package hudson.plugins.ircbot.v2; import hudson.Util; import hudson.plugins.im.AuthenticationHolder; import hudson.plugins.im.GroupChatIMMessageTarget; import hudson.plugins.im.IMConnection; import hudson.plugins.im.IMConnectionListener; import hudson.plugins.im.IMException; import hudson.plugins.im.IMMessage; import hudson.plugins.im.IMMessageListener; import hudson.plugins.im.IMMessageTarget; import hudson.plugins.im.IMPresence; import hudson.plugins.im.bot.Bot; import hudson.plugins.im.tools.ExceptionHelper; import hudson.plugins.ircbot.IrcPublisher.DescriptorImpl; import hudson.plugins.ircbot.v2.PircListener.InviteListener; import hudson.plugins.ircbot.v2.PircListener.JoinListener; import hudson.plugins.ircbot.v2.PircListener.PartListener; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import javax.net.SocketFactory; import javax.net.ssl.SSLSocketFactory; import org.pircbotx.Channel; import org.pircbotx.PircBotX; import org.pircbotx.exception.IrcException; import org.pircbotx.exception.NickAlreadyInUseException; /** * IRC specific implementation of an {@link IMConnection}. * * @author kutzi */ public class IRCConnection implements IMConnection, JoinListener, InviteListener, PartListener { private static final Logger LOGGER = Logger.getLogger(IRCConnection.class.getName()); private final DescriptorImpl descriptor; private final AuthenticationHolder authentication; private final PircBotX pircConnection = new PircBotX(); private final PircListener listener; private List<IMMessageTarget> groupChats; private final Map<String, Bot> bots = new HashMap<String, Bot>(); private final Map<String, Bot> privateChats = new HashMap<String, Bot>(); public IRCConnection(DescriptorImpl descriptor, AuthenticationHolder authentication) { if (LOGGER.isLoggable(Level.FINEST)) { this.pircConnection.setVerbose(true); } this.descriptor = descriptor; this.authentication = authentication; if (descriptor.getDefaultTargets() != null) { this.groupChats = descriptor.getDefaultTargets(); } else { this.groupChats = Collections.emptyList(); } this.pircConnection.setLogin(this.descriptor.getLogin()); this.pircConnection.setName(this.descriptor.getNick()); // lower delay between sending 2 messages to 500ms as we will sometimes send // output which will consist of multiple lines (see comment in send method) // (lowering further than this doesn't seem to work as we will otherwise be easily // be throttled by IRC servers) this.pircConnection.setMessageDelay(500); this.listener = new PircListener(this.pircConnection, this.descriptor.getNick()); } //@Override public void close() { this.listener.explicitDisconnect = true; if (this.pircConnection != null && this.pircConnection.isConnected()) { this.listener.removeJoinListener(this); this.listener.removePartListener(this); this.listener.removeInviteListener(this); this.pircConnection.disconnect(); //this.pircConnection.shutdown(); } } //@Override public boolean isConnected() { return this.pircConnection != null && this.pircConnection.isConnected(); } //@Override public boolean connect() { try { this.pircConnection.setEncoding(this.descriptor.getCharset()); LOGGER.info(String.format("Connecting to %s:%s as %s using charset %s", this.descriptor.getHost(), this.descriptor.getPort(), this.descriptor.getNick(), this.descriptor.getCharset())); String password = Util.fixEmpty(this.descriptor.getPassword()); final SocketFactory sf; if (this.descriptor.isSsl()) { sf = SSLSocketFactory.getDefault(); } else { sf = SocketFactory.getDefault(); } this.pircConnection.connect(this.descriptor.getHost(), this.descriptor.getPort(), password, sf); LOGGER.info("connected to IRC"); if (!this.pircConnection.getListenerManager().listenerExists(this.listener)) { this.pircConnection.getListenerManager().addListener(this.listener); } this.listener.addJoinListener(this); this.listener.addInviteListener(this); this.listener.addPartListener(this); final String nickServPassword = this.descriptor.getNickServPassword(); if(Util.fixEmpty(nickServPassword) != null) { this.pircConnection.identify(nickServPassword); if (!this.groupChats.isEmpty()) { // Sleep some time so chances are good we're already identified // when we try to join the channels. // Unfortunately there seems to be no standard way in IRC to recognize // if one has been identified already. LOGGER.fine("Sleeping some time to wait for being authenticated"); try { Thread.sleep(TimeUnit.SECONDS.toMillis(5)); } catch (InterruptedException e) { // ignore } } } for (IMMessageTarget groupChat : this.groupChats) { try { getGroupChat(groupChat); } catch (Exception e) { // if we got here, the IRC connection could be established, but probably the channel name // is invalid LOGGER.warning("Unable to connect to channel '" + groupChat + "'.\n" + "Message: " + ExceptionHelper.dump(e)); } } listener.addMessageListener(this.descriptor.getNick(), PircListener.CHAT_ESTABLISHER, new ChatEstablishedListener()); return true; } catch (NickAlreadyInUseException e) { LOGGER.warning("Error connecting to irc: " + e); } catch (IOException e) { LOGGER.warning("Error connecting to irc: " + e); } catch (IrcException e) { LOGGER.warning("Error connecting to irc: " + e); + } catch (RuntimeException e) { + // JENKINS-17017: contrary to Javadoc PircBotx (at least 1.7 and 1.8) sometimes + // throw a RuntimeException instead of IOException if connecting fails + LOGGER.warning("Error connecting to irc: " + e); } return false; } private GroupChatIMMessageTarget getGroupChatForChannelName(String channelName) { for (IMMessageTarget messageTarget : groupChats) { if (!(messageTarget instanceof GroupChatIMMessageTarget)) { continue; } GroupChatIMMessageTarget groupChat = (GroupChatIMMessageTarget) messageTarget; if (groupChat.getName().equals(channelName)) { return groupChat; } } return null; } private void getGroupChat(IMMessageTarget groupChat) { if (! (groupChat instanceof GroupChatIMMessageTarget)) { LOGGER.warning(groupChat + " is no channel. Cannot join."); return; } GroupChatIMMessageTarget channel = (GroupChatIMMessageTarget)groupChat; LOGGER.info("Trying to join channel " + channel.getName()); if (channel.hasPassword()) { this.pircConnection.joinChannel(channel.getName(), channel.getPassword()); } else { this.pircConnection.joinChannel(channel.getName()); } } //@Override public void channelJoined(String channelName) { GroupChatIMMessageTarget groupChat = getGroupChatForChannelName(channelName); if (groupChat == null) { LOGGER.log(Level.INFO, "Joined to channel {0} but I don't seem to belong here", channelName); return; } Bot bot = new Bot(new IRCChannel(channelName, this, this.listener, !groupChat.isNotificationOnly()), this.descriptor.getNick(), this.descriptor.getHost(), this.descriptor.getCommandPrefix(), this.authentication); bots.put(channelName, bot); LOGGER.log(Level.INFO, "Joined channel {0} and bot registered", channelName); } //@Override public void inviteReceived(String channelName, String inviter) { GroupChatIMMessageTarget groupChat = getGroupChatForChannelName(channelName); if (groupChat == null) { LOGGER.log(Level.INFO, "Invited to channel {0} but I don't seem to belong here", channelName); return; } LOGGER.log(Level.INFO, "Invited to join {0}", channelName); getGroupChat(groupChat); } //@Override public void channelParted(String channelName) { GroupChatIMMessageTarget groupChat = getGroupChatForChannelName(channelName); if (groupChat == null) { LOGGER.log(Level.INFO, "I'm leaving {0} but I never seemed to belong there in the first place", channelName); return; } if (bots.containsKey(channelName)) { Bot bot = bots.remove(channelName); bot.shutdown(); LOGGER.log(Level.INFO, "I have left {0}", channelName); } else { LOGGER.log(Level.INFO, "No bot ever registered for {0}", channelName); } } //@Override public void addConnectionListener(IMConnectionListener listener) { this.listener.addConnectionListener(listener); } //@Override public void removeConnectionListener(IMConnectionListener listener) { this.listener.removeConnectionListener(listener); } //@Override public void send(IMMessageTarget target, String text) throws IMException { send(target.toString(), text); } public void send(String target, String text) throws IMException { Channel channel = this.pircConnection.getChannel(target); boolean useColors = this.descriptor.isUseColors(); if (useColors) { String mode = channel.getMode(); if (mode.contains("c")) { LOGGER.warning("Bot is configured to use colors, but channel " + target + " disallows colors!"); useColors = false; } } // IRC doesn't support multiline messages (see http://stackoverflow.com/questions/7039478/linebreak-irc-protocol) // therefore we split the message on line breaks and send each line as its own message: String[] lines = text.split("\\r?\\n|\\r"); for (String line : lines) { if (useColors){ line = IRCColorizer.colorize(line); } if (this.descriptor.isUseNotice()) { this.pircConnection.sendNotice(channel, line); } else { this.pircConnection.sendMessage(channel, line); } } } //@Override public void setPresence(IMPresence presence, String statusMessage) throws IMException { if (presence.ordinal() >= IMPresence.OCCUPIED.ordinal()) { if (statusMessage == null || statusMessage.trim().length() == 0) { statusMessage = "away"; } this.pircConnection.sendRawLineNow("AWAY " + statusMessage); } else { this.pircConnection.sendRawLineNow("AWAY"); } } /** * Listens for chat requests from singular users (i.e. private chat requests). * Creates a new bot for each request, if we're not already in a chat with * that user. */ private class ChatEstablishedListener implements IMMessageListener { //@Override public void onMessage(IMMessage message) { if(!message.getTo().equals(descriptor.getNick())) { throw new IllegalStateException("Intercepted message to '" + message.getTo() + "'. That shouldn't happen!"); } synchronized (privateChats) { if (privateChats.containsKey(message.getFrom())) { // ignore. We're already in a chat with partner return; } IRCPrivateChat chat = new IRCPrivateChat(IRCConnection.this, listener, descriptor.getUserName(), message.getFrom()); Bot bot = new Bot(chat, descriptor.getNick(), descriptor.getHost(), descriptor.getCommandPrefix(), authentication); privateChats.put(message.getFrom(), bot); // we must replay this message as it could contain a command bot.onMessage(message); } } } }
true
true
public boolean connect() { try { this.pircConnection.setEncoding(this.descriptor.getCharset()); LOGGER.info(String.format("Connecting to %s:%s as %s using charset %s", this.descriptor.getHost(), this.descriptor.getPort(), this.descriptor.getNick(), this.descriptor.getCharset())); String password = Util.fixEmpty(this.descriptor.getPassword()); final SocketFactory sf; if (this.descriptor.isSsl()) { sf = SSLSocketFactory.getDefault(); } else { sf = SocketFactory.getDefault(); } this.pircConnection.connect(this.descriptor.getHost(), this.descriptor.getPort(), password, sf); LOGGER.info("connected to IRC"); if (!this.pircConnection.getListenerManager().listenerExists(this.listener)) { this.pircConnection.getListenerManager().addListener(this.listener); } this.listener.addJoinListener(this); this.listener.addInviteListener(this); this.listener.addPartListener(this); final String nickServPassword = this.descriptor.getNickServPassword(); if(Util.fixEmpty(nickServPassword) != null) { this.pircConnection.identify(nickServPassword); if (!this.groupChats.isEmpty()) { // Sleep some time so chances are good we're already identified // when we try to join the channels. // Unfortunately there seems to be no standard way in IRC to recognize // if one has been identified already. LOGGER.fine("Sleeping some time to wait for being authenticated"); try { Thread.sleep(TimeUnit.SECONDS.toMillis(5)); } catch (InterruptedException e) { // ignore } } } for (IMMessageTarget groupChat : this.groupChats) { try { getGroupChat(groupChat); } catch (Exception e) { // if we got here, the IRC connection could be established, but probably the channel name // is invalid LOGGER.warning("Unable to connect to channel '" + groupChat + "'.\n" + "Message: " + ExceptionHelper.dump(e)); } } listener.addMessageListener(this.descriptor.getNick(), PircListener.CHAT_ESTABLISHER, new ChatEstablishedListener()); return true; } catch (NickAlreadyInUseException e) { LOGGER.warning("Error connecting to irc: " + e); } catch (IOException e) { LOGGER.warning("Error connecting to irc: " + e); } catch (IrcException e) { LOGGER.warning("Error connecting to irc: " + e); } return false; }
public boolean connect() { try { this.pircConnection.setEncoding(this.descriptor.getCharset()); LOGGER.info(String.format("Connecting to %s:%s as %s using charset %s", this.descriptor.getHost(), this.descriptor.getPort(), this.descriptor.getNick(), this.descriptor.getCharset())); String password = Util.fixEmpty(this.descriptor.getPassword()); final SocketFactory sf; if (this.descriptor.isSsl()) { sf = SSLSocketFactory.getDefault(); } else { sf = SocketFactory.getDefault(); } this.pircConnection.connect(this.descriptor.getHost(), this.descriptor.getPort(), password, sf); LOGGER.info("connected to IRC"); if (!this.pircConnection.getListenerManager().listenerExists(this.listener)) { this.pircConnection.getListenerManager().addListener(this.listener); } this.listener.addJoinListener(this); this.listener.addInviteListener(this); this.listener.addPartListener(this); final String nickServPassword = this.descriptor.getNickServPassword(); if(Util.fixEmpty(nickServPassword) != null) { this.pircConnection.identify(nickServPassword); if (!this.groupChats.isEmpty()) { // Sleep some time so chances are good we're already identified // when we try to join the channels. // Unfortunately there seems to be no standard way in IRC to recognize // if one has been identified already. LOGGER.fine("Sleeping some time to wait for being authenticated"); try { Thread.sleep(TimeUnit.SECONDS.toMillis(5)); } catch (InterruptedException e) { // ignore } } } for (IMMessageTarget groupChat : this.groupChats) { try { getGroupChat(groupChat); } catch (Exception e) { // if we got here, the IRC connection could be established, but probably the channel name // is invalid LOGGER.warning("Unable to connect to channel '" + groupChat + "'.\n" + "Message: " + ExceptionHelper.dump(e)); } } listener.addMessageListener(this.descriptor.getNick(), PircListener.CHAT_ESTABLISHER, new ChatEstablishedListener()); return true; } catch (NickAlreadyInUseException e) { LOGGER.warning("Error connecting to irc: " + e); } catch (IOException e) { LOGGER.warning("Error connecting to irc: " + e); } catch (IrcException e) { LOGGER.warning("Error connecting to irc: " + e); } catch (RuntimeException e) { // JENKINS-17017: contrary to Javadoc PircBotx (at least 1.7 and 1.8) sometimes // throw a RuntimeException instead of IOException if connecting fails LOGGER.warning("Error connecting to irc: " + e); } return false; }
diff --git a/src/main/java/org/animotron/animi/Utils.java b/src/main/java/org/animotron/animi/Utils.java index 498acfa..7d9a8eb 100644 --- a/src/main/java/org/animotron/animi/Utils.java +++ b/src/main/java/org/animotron/animi/Utils.java @@ -1,256 +1,256 @@ /* * Copyright (C) 2012 The Animo Project * http://animotron.org * * This file is part of Animi. * * Animotron is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * Animotron 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 Affero General Public License for more details. * * You should have received a copy of * the GNU Affero General Public License along with Animotron. * If not, see <http://www.gnu.org/licenses/>. */ package org.animotron.animi; import static org.jocl.CL.*; import java.awt.image.BufferedImage; import org.animotron.animi.cortex.CortexZoneComplex; import org.animotron.animi.cortex.Mapping; import org.jocl.Pointer; import org.jocl.Sizeof; import org.jocl.cl_event; /** * @author <a href="mailto:[email protected]">Dmitriy Shabanov</a> * */ public class Utils { private final static double LUM_RED = 0.299; private final static double LUM_GREEN = 0.587; private final static double LUM_BLUE = 0.114; public static int calcGrey(final BufferedImage img, final int x, final int y) { int value = img.getRGB(x, y); int r = get_red(value); int g = get_green(value); int b = get_blue(value); // return r+g+b; // return (r+g+b) /3; return (int) Math.round(r * LUM_RED + g * LUM_GREEN + b * LUM_BLUE); } public static int create_rgb(int alpha, int r, int g, int b) { int rgb = (alpha << 24) + (r << 16) + (g << 8) + b; return rgb; } public static int get_alpha(int rgb) { return (rgb >> 24) & 0xFF; // return rgb & 0xFF000000; } public static int get_red(int rgb) { return (rgb >> 16) & 0xFF; // return rgb & 0x00FF0000; } public static int get_green(int rgb) { return (rgb >> 8) & 0xFF; } public static int get_blue(int rgb) { return rgb & 0xFF; } public static BufferedImage drawRF( final BufferedImage image, final int boxSize, final int offsetX, final int offsetY, final int cnX, final int cnY, final int pN, final Mapping m) { final CortexZoneComplex cz = m.toZone; final int offset = (cnY * cz.width * m.linksSenapseRecordSize) + (m.linksSenapseRecordSize * cnX); // final int offsetWeight = (cnY * cz.width * m.linksWeightRecordSize) + (m.linksWeightRecordSize * cnX); int offsetPackagers = cz.package_size * m.ns_links; int lOffset = (cnY * cz.width * offsetPackagers) + (cnX * offsetPackagers) + (pN * m.ns_links); int pX = 0, pY = 0; for (int l = 0; l < m.ns_links; l++) { int xi = m.linksSenapse[offset + 2*l ]; int yi = m.linksSenapse[offset + 2*l + 1]; pX = (boxSize / 2) + (xi - (int)(cnX * m.fX)); pY = (boxSize / 2) + (yi - (int)(cnY * m.fY)); if ( pX > 0 && pX < boxSize && pY > 0 && pY < boxSize) { int value = image.getRGB(offsetX + pX, offsetY + pY); int G = Utils.get_green(value); int B = Utils.get_blue(value); int R = Utils.get_red(value); // switch (link.delay) { // case 0: // g += 255 * link.q;; // if (g > 255) g = 255; // // break; // case 1: // b += 255 * link.q; // if (b > 255) b = 255; // // break; // default: // r += 255 * link.q; // if (r > 255) r = 255; // // break; // } // image.setRGB(pX, pY, Utils.create_rgb(255, r, g, b)); // int c = calcGrey(image, offsetX + pX, offsetY + pY); // c += 255 * m.linksWeight[lOffset + l]; // if (c > 255) c = 255; // else if (c < 0) c = 0; // image.setRGB(offsetX + pX, offsetY + pY, create_rgb(255, c, c, c)); if (m.linksWeight[lOffset + l] > 0.0f) { B += 255 * m.linksWeight[lOffset + l] * 5; if (B > 255) B = 255; } else { G += 255 * m.linksWeight[lOffset + l] * 5; if (G > 255) G = 255; }; - image.setRGB(offsetX + pX, offsetY + pY, create_rgb(255, R, G, B)); + image.setRGB(offsetX + pX, offsetY + pY, create_rgb(255, 0, G, B)); } } return image; } public static BufferedImage drawRF( final BufferedImage image, final int cnX, final int cnY, final Mapping m) { final CortexZoneComplex cz = m.toZone; final int pos = cnY * cz.width + cnX; final int offset = (cnY * cz.width * m.linksSenapseRecordSize) + (m.linksSenapseRecordSize * cnX); final int offsetWeight = (cnY * cz.width * m.linksWeightRecordSize) + (m.linksWeightRecordSize * cnX); int pX = 0, pY = 0; for (int l = 0; l < m.ns_links; l++) { int xi = m.linksSenapse[offset + 2*l ]; int yi = m.linksSenapse[offset + 2*l + 1]; pX = xi; pY = yi; if ( pX > 0 && pX < image.getWidth() && pY > 0 && pY < image.getHeight()) { // int value = image.getRGB(pX, pY); // // int g = Utils.get_green(value); // int b = Utils.get_blue(value); // int r = Utils.get_red(value); // // switch (link.delay) { // case 0: // g += 255 * link.q;; // if (g > 255) g = 255; // // break; // case 1: // b += 255 * link.q; // if (b > 255) b = 255; // // break; // default: // r += 255 * link.q; // if (r > 255) r = 255; // // break; // } // image.setRGB(pX, pY, Utils.create_rgb(255, r, g, b)); int packageNumber = 0; for (int p = 0; p < cz.package_size; p++) { if (cz.pCols[(cnY * cz.width * cz.package_size) + (cnX * cz.package_size) + p] >= cz.cols[pos]) { packageNumber = p; break; } } int c = calcGrey(image, pX, pY); c += 255 * cz.cols[pos] * m.linksWeight[offsetWeight + (packageNumber * m.ns_links) + l]; if (c > 255) c = 255; image.setRGB(pX, pY, create_rgb(255, c, c, c)); } } return image; } /* * Print "benchmarking" information */ public static void printBenchmarkInfo(String description, cl_event event) { StringBuilder sb = new StringBuilder(); sb .append(description) .append(" ") .append(computeExecutionTimeMs(event)) .append(" ms"); System.out.println(sb.toString()); } /* * Compute the execution time for the given event, in milliseconds */ private static double computeExecutionTimeMs(cl_event event) { long startTime[] = new long[1]; long endTime[] = new long[1]; clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_END, Sizeof.cl_ulong, Pointer.to(endTime), null); clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_START, Sizeof.cl_ulong, Pointer.to(startTime), null); return (endTime[0]-startTime[0]) / 1e6; } public static String debug(float[] array) { return debug(array, 7); } public static String debug(float[] array, int count) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < count; i++) { sb.append(array[i]).append(", "); } return sb.append(array[count]).toString(); } }
true
true
public static BufferedImage drawRF( final BufferedImage image, final int boxSize, final int offsetX, final int offsetY, final int cnX, final int cnY, final int pN, final Mapping m) { final CortexZoneComplex cz = m.toZone; final int offset = (cnY * cz.width * m.linksSenapseRecordSize) + (m.linksSenapseRecordSize * cnX); // final int offsetWeight = (cnY * cz.width * m.linksWeightRecordSize) + (m.linksWeightRecordSize * cnX); int offsetPackagers = cz.package_size * m.ns_links; int lOffset = (cnY * cz.width * offsetPackagers) + (cnX * offsetPackagers) + (pN * m.ns_links); int pX = 0, pY = 0; for (int l = 0; l < m.ns_links; l++) { int xi = m.linksSenapse[offset + 2*l ]; int yi = m.linksSenapse[offset + 2*l + 1]; pX = (boxSize / 2) + (xi - (int)(cnX * m.fX)); pY = (boxSize / 2) + (yi - (int)(cnY * m.fY)); if ( pX > 0 && pX < boxSize && pY > 0 && pY < boxSize) { int value = image.getRGB(offsetX + pX, offsetY + pY); int G = Utils.get_green(value); int B = Utils.get_blue(value); int R = Utils.get_red(value); // switch (link.delay) { // case 0: // g += 255 * link.q;; // if (g > 255) g = 255; // // break; // case 1: // b += 255 * link.q; // if (b > 255) b = 255; // // break; // default: // r += 255 * link.q; // if (r > 255) r = 255; // // break; // } // image.setRGB(pX, pY, Utils.create_rgb(255, r, g, b)); // int c = calcGrey(image, offsetX + pX, offsetY + pY); // c += 255 * m.linksWeight[lOffset + l]; // if (c > 255) c = 255; // else if (c < 0) c = 0; // image.setRGB(offsetX + pX, offsetY + pY, create_rgb(255, c, c, c)); if (m.linksWeight[lOffset + l] > 0.0f) { B += 255 * m.linksWeight[lOffset + l] * 5; if (B > 255) B = 255; } else { G += 255 * m.linksWeight[lOffset + l] * 5; if (G > 255) G = 255; }; image.setRGB(offsetX + pX, offsetY + pY, create_rgb(255, R, G, B)); } } return image; }
public static BufferedImage drawRF( final BufferedImage image, final int boxSize, final int offsetX, final int offsetY, final int cnX, final int cnY, final int pN, final Mapping m) { final CortexZoneComplex cz = m.toZone; final int offset = (cnY * cz.width * m.linksSenapseRecordSize) + (m.linksSenapseRecordSize * cnX); // final int offsetWeight = (cnY * cz.width * m.linksWeightRecordSize) + (m.linksWeightRecordSize * cnX); int offsetPackagers = cz.package_size * m.ns_links; int lOffset = (cnY * cz.width * offsetPackagers) + (cnX * offsetPackagers) + (pN * m.ns_links); int pX = 0, pY = 0; for (int l = 0; l < m.ns_links; l++) { int xi = m.linksSenapse[offset + 2*l ]; int yi = m.linksSenapse[offset + 2*l + 1]; pX = (boxSize / 2) + (xi - (int)(cnX * m.fX)); pY = (boxSize / 2) + (yi - (int)(cnY * m.fY)); if ( pX > 0 && pX < boxSize && pY > 0 && pY < boxSize) { int value = image.getRGB(offsetX + pX, offsetY + pY); int G = Utils.get_green(value); int B = Utils.get_blue(value); int R = Utils.get_red(value); // switch (link.delay) { // case 0: // g += 255 * link.q;; // if (g > 255) g = 255; // // break; // case 1: // b += 255 * link.q; // if (b > 255) b = 255; // // break; // default: // r += 255 * link.q; // if (r > 255) r = 255; // // break; // } // image.setRGB(pX, pY, Utils.create_rgb(255, r, g, b)); // int c = calcGrey(image, offsetX + pX, offsetY + pY); // c += 255 * m.linksWeight[lOffset + l]; // if (c > 255) c = 255; // else if (c < 0) c = 0; // image.setRGB(offsetX + pX, offsetY + pY, create_rgb(255, c, c, c)); if (m.linksWeight[lOffset + l] > 0.0f) { B += 255 * m.linksWeight[lOffset + l] * 5; if (B > 255) B = 255; } else { G += 255 * m.linksWeight[lOffset + l] * 5; if (G > 255) G = 255; }; image.setRGB(offsetX + pX, offsetY + pY, create_rgb(255, 0, G, B)); } } return image; }
diff --git a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/launcher/UnresolvedJREStatusHandler.java b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/launcher/UnresolvedJREStatusHandler.java index 7518f4c77..1233e1f16 100644 --- a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/launcher/UnresolvedJREStatusHandler.java +++ b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/launcher/UnresolvedJREStatusHandler.java @@ -1,109 +1,114 @@ package org.eclipse.jdt.internal.debug.ui.launcher; /******************************************************************************* * Copyright (c) 2001, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IStatus; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.ILaunchConfigurationType; import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy; import org.eclipse.debug.core.IStatusHandler; import org.eclipse.jdt.debug.ui.launchConfigurations.JavaJRETab; import org.eclipse.jdt.internal.debug.core.JDIDebugPlugin; import org.eclipse.jdt.internal.debug.ui.JDIDebugUIPlugin; import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants; import org.eclipse.jdt.launching.IVMInstall; import org.eclipse.jdt.launching.IVMInstallType; import org.eclipse.jdt.launching.JavaRuntime; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; /** * When a project's JRE cannot be resolved for building, this status handler * is called. */ public class UnresolvedJREStatusHandler implements IStatusHandler { protected ILaunchConfigurationWorkingCopy fConfig; class JREDialog extends ErrorDialog { private JavaJRETab fJRETab; /** * */ public JREDialog(IStatus status) { super(JDIDebugUIPlugin.getActiveWorkbenchShell(), LauncherMessages.getString("UnresolvedJREStatusHandler.Error_1"), LauncherMessages.getString("UnresolvedJREStatusHandler.Unable_to_resolve_system_library._Select_an_alternate_JRE._2"), status, IStatus.ERROR); //$NON-NLS-1$ //$NON-NLS-2$ } /** * @see Dialog#createDialogArea(Composite) */ protected Control createDialogArea(Composite parent) { Composite comp = (Composite)super.createDialogArea(parent); fJRETab = new JavaJRETab(); fJRETab.setVMSpecificArgumentsVisible(false); fJRETab.createControl(comp); GridData gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = 2; fJRETab.getControl().setLayoutData(gd); fJRETab.setDefaults(fConfig); fJRETab.initializeFrom(fConfig); return comp; } /** * @see Dialog#okPressed() */ protected void okPressed() { fJRETab.performApply(fConfig); super.okPressed(); } } /** * @param source source is an instnace of <code>IJavaProject</code> * @return an instance of <code>IVMInstall</code> or <code>null</code> * * @see IStatusHandler#handleStatus(IStatus, Object) */ - public Object handleStatus(IStatus status, Object source) throws CoreException { + public Object handleStatus(final IStatus status, Object source) throws CoreException { ILaunchConfigurationType type = DebugPlugin.getDefault().getLaunchManager().getLaunchConfigurationType(IJavaLaunchConfigurationConstants.ID_JAVA_APPLICATION); fConfig = type.newInstance(null, "TEMP_CONFIG"); //$NON-NLS-1$ - JREDialog dialog = new JREDialog(status); - dialog.open(); + Runnable r = new Runnable() { + public void run() { + JREDialog dialog = new JREDialog(status); + dialog.open(); + } + }; + JDIDebugUIPlugin.getStandardDisplay().syncExec(r); IVMInstall vm = null; String typeId = fConfig.getAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_INSTALL_TYPE, (String)null); String name = fConfig.getAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_INSTALL_NAME, (String)null); if (typeId == null) { vm = JavaRuntime.getDefaultVMInstall(); } else { IVMInstallType vmType = JavaRuntime.getVMInstallType(typeId); if (vmType != null) { vm = vmType.findVMInstallByName(name); } } return vm; } }
false
true
public Object handleStatus(IStatus status, Object source) throws CoreException { ILaunchConfigurationType type = DebugPlugin.getDefault().getLaunchManager().getLaunchConfigurationType(IJavaLaunchConfigurationConstants.ID_JAVA_APPLICATION); fConfig = type.newInstance(null, "TEMP_CONFIG"); //$NON-NLS-1$ JREDialog dialog = new JREDialog(status); dialog.open(); IVMInstall vm = null; String typeId = fConfig.getAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_INSTALL_TYPE, (String)null); String name = fConfig.getAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_INSTALL_NAME, (String)null); if (typeId == null) { vm = JavaRuntime.getDefaultVMInstall(); } else { IVMInstallType vmType = JavaRuntime.getVMInstallType(typeId); if (vmType != null) { vm = vmType.findVMInstallByName(name); } } return vm; }
public Object handleStatus(final IStatus status, Object source) throws CoreException { ILaunchConfigurationType type = DebugPlugin.getDefault().getLaunchManager().getLaunchConfigurationType(IJavaLaunchConfigurationConstants.ID_JAVA_APPLICATION); fConfig = type.newInstance(null, "TEMP_CONFIG"); //$NON-NLS-1$ Runnable r = new Runnable() { public void run() { JREDialog dialog = new JREDialog(status); dialog.open(); } }; JDIDebugUIPlugin.getStandardDisplay().syncExec(r); IVMInstall vm = null; String typeId = fConfig.getAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_INSTALL_TYPE, (String)null); String name = fConfig.getAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_INSTALL_NAME, (String)null); if (typeId == null) { vm = JavaRuntime.getDefaultVMInstall(); } else { IVMInstallType vmType = JavaRuntime.getVMInstallType(typeId); if (vmType != null) { vm = vmType.findVMInstallByName(name); } } return vm; }
diff --git a/src/hunternif/mc/dota2items/client/gui/GuiManaBar.java b/src/hunternif/mc/dota2items/client/gui/GuiManaBar.java index e4638ac..790db4c 100644 --- a/src/hunternif/mc/dota2items/client/gui/GuiManaBar.java +++ b/src/hunternif/mc/dota2items/client/gui/GuiManaBar.java @@ -1,107 +1,107 @@ package hunternif.mc.dota2items.client.gui; import hunternif.mc.dota2items.Dota2Items; import hunternif.mc.dota2items.core.EntityStats; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Gui; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.attributes.AttributeInstance; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.client.event.RenderGameOverlayEvent.ElementType; import net.minecraftforge.common.ForgeHooks; import net.minecraftforge.event.ForgeSubscribe; import org.lwjgl.opengl.GL11; public class GuiManaBar extends Gui { private static final ResourceLocation texture = new ResourceLocation(Dota2Items.ID+":textures/gui/mana.png"); private static final int HIGHLIGHT_TIME = 10; // [ticks] /** Let's call the 10 discrete mana units on screen "drops". */ private static final int HALF_DROPS_COUNT = 20; private Minecraft mc; private int prevMana = 0; private long lastChange = 0; public static int yPos; public GuiManaBar(Minecraft mc) { this.mc = mc; } @ForgeSubscribe - public void onRenderArmor(RenderGameOverlayEvent event) { + public void onRenderHotBar(RenderGameOverlayEvent event) { // Only interested in Post-ExperienceBar events (the end of overlay rendering) - if (event.isCancelable() || event.type != ElementType.EXPERIENCE || mc.thePlayer.capabilities.isCreativeMode) { + if (event.isCancelable() || event.type != ElementType.HOTBAR || mc.thePlayer.capabilities.isCreativeMode) { return; } EntityStats stats = Dota2Items.mechanics.getOrCreateEntityStats(mc.thePlayer); if (stats.getMaxMana() == 0) { return; } float halfDrop = (float)stats.getMaxMana() / (float)HALF_DROPS_COUNT; int mana = MathHelper.floor_float((float)stats.getMana() / halfDrop); long ticksSinceLastChange = mc.thePlayer.ticksExisted - lastChange; boolean highlight = ticksSinceLastChange <= HIGHLIGHT_TIME && ticksSinceLastChange / 3 % 2 == 1; GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glDisable(GL11.GL_LIGHTING); mc.renderEngine.func_110577_a(texture); int width = event.resolution.getScaledWidth(); int height = event.resolution.getScaledHeight(); int left = width / 2 - 91; int top = height - 39; // Account for health bars: AttributeInstance attrMaxHealth = this.mc.thePlayer.func_110148_a(SharedMonsterAttributes.field_111267_a); float healthMax = (float)attrMaxHealth.func_111126_e(); float absorb = this.mc.thePlayer.func_110139_bj(); int healthRows = MathHelper.ceiling_float_int((healthMax + absorb) / 2.0F / 10.0F); int rowHeight = Math.max(10 - (healthRows - 2), 3); top -= healthRows * rowHeight; // Account for armor: if (ForgeHooks.getTotalArmorValue(mc.thePlayer) > 0) { top -= 10; } yPos = top; int regen = -1; for (int i = 0; i < 10; ++i) { int idx = i * 2 + 1; int x = left + i * 8; int y = top; if (i == regen) { y -= 2; } drawTexturedModalRect(x, y, (highlight ? 9 : 0), 0, 9, 9); if (highlight) { if (idx < prevMana) { drawTexturedModalRect(x, y, 54, 0, 9, 9); } else if (idx == prevMana) { drawTexturedModalRect(x, y, 63, 0, 9, 9); } } if (idx < mana) { drawTexturedModalRect(x, y, 36, 0, 9, 9); } else if (idx == mana) { drawTexturedModalRect(x, y, 45, 0, 9, 9); } } if (prevMana != mana) { lastChange = mc.thePlayer.ticksExisted; } prevMana = mana; } }
false
true
public void onRenderArmor(RenderGameOverlayEvent event) { // Only interested in Post-ExperienceBar events (the end of overlay rendering) if (event.isCancelable() || event.type != ElementType.EXPERIENCE || mc.thePlayer.capabilities.isCreativeMode) { return; } EntityStats stats = Dota2Items.mechanics.getOrCreateEntityStats(mc.thePlayer); if (stats.getMaxMana() == 0) { return; } float halfDrop = (float)stats.getMaxMana() / (float)HALF_DROPS_COUNT; int mana = MathHelper.floor_float((float)stats.getMana() / halfDrop); long ticksSinceLastChange = mc.thePlayer.ticksExisted - lastChange; boolean highlight = ticksSinceLastChange <= HIGHLIGHT_TIME && ticksSinceLastChange / 3 % 2 == 1; GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glDisable(GL11.GL_LIGHTING); mc.renderEngine.func_110577_a(texture); int width = event.resolution.getScaledWidth(); int height = event.resolution.getScaledHeight(); int left = width / 2 - 91; int top = height - 39; // Account for health bars: AttributeInstance attrMaxHealth = this.mc.thePlayer.func_110148_a(SharedMonsterAttributes.field_111267_a); float healthMax = (float)attrMaxHealth.func_111126_e(); float absorb = this.mc.thePlayer.func_110139_bj(); int healthRows = MathHelper.ceiling_float_int((healthMax + absorb) / 2.0F / 10.0F); int rowHeight = Math.max(10 - (healthRows - 2), 3); top -= healthRows * rowHeight; // Account for armor: if (ForgeHooks.getTotalArmorValue(mc.thePlayer) > 0) { top -= 10; } yPos = top; int regen = -1; for (int i = 0; i < 10; ++i) { int idx = i * 2 + 1; int x = left + i * 8; int y = top; if (i == regen) { y -= 2; } drawTexturedModalRect(x, y, (highlight ? 9 : 0), 0, 9, 9); if (highlight) { if (idx < prevMana) { drawTexturedModalRect(x, y, 54, 0, 9, 9); } else if (idx == prevMana) { drawTexturedModalRect(x, y, 63, 0, 9, 9); } } if (idx < mana) { drawTexturedModalRect(x, y, 36, 0, 9, 9); } else if (idx == mana) { drawTexturedModalRect(x, y, 45, 0, 9, 9); } } if (prevMana != mana) { lastChange = mc.thePlayer.ticksExisted; } prevMana = mana; }
public void onRenderHotBar(RenderGameOverlayEvent event) { // Only interested in Post-ExperienceBar events (the end of overlay rendering) if (event.isCancelable() || event.type != ElementType.HOTBAR || mc.thePlayer.capabilities.isCreativeMode) { return; } EntityStats stats = Dota2Items.mechanics.getOrCreateEntityStats(mc.thePlayer); if (stats.getMaxMana() == 0) { return; } float halfDrop = (float)stats.getMaxMana() / (float)HALF_DROPS_COUNT; int mana = MathHelper.floor_float((float)stats.getMana() / halfDrop); long ticksSinceLastChange = mc.thePlayer.ticksExisted - lastChange; boolean highlight = ticksSinceLastChange <= HIGHLIGHT_TIME && ticksSinceLastChange / 3 % 2 == 1; GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glDisable(GL11.GL_LIGHTING); mc.renderEngine.func_110577_a(texture); int width = event.resolution.getScaledWidth(); int height = event.resolution.getScaledHeight(); int left = width / 2 - 91; int top = height - 39; // Account for health bars: AttributeInstance attrMaxHealth = this.mc.thePlayer.func_110148_a(SharedMonsterAttributes.field_111267_a); float healthMax = (float)attrMaxHealth.func_111126_e(); float absorb = this.mc.thePlayer.func_110139_bj(); int healthRows = MathHelper.ceiling_float_int((healthMax + absorb) / 2.0F / 10.0F); int rowHeight = Math.max(10 - (healthRows - 2), 3); top -= healthRows * rowHeight; // Account for armor: if (ForgeHooks.getTotalArmorValue(mc.thePlayer) > 0) { top -= 10; } yPos = top; int regen = -1; for (int i = 0; i < 10; ++i) { int idx = i * 2 + 1; int x = left + i * 8; int y = top; if (i == regen) { y -= 2; } drawTexturedModalRect(x, y, (highlight ? 9 : 0), 0, 9, 9); if (highlight) { if (idx < prevMana) { drawTexturedModalRect(x, y, 54, 0, 9, 9); } else if (idx == prevMana) { drawTexturedModalRect(x, y, 63, 0, 9, 9); } } if (idx < mana) { drawTexturedModalRect(x, y, 36, 0, 9, 9); } else if (idx == mana) { drawTexturedModalRect(x, y, 45, 0, 9, 9); } } if (prevMana != mana) { lastChange = mc.thePlayer.ticksExisted; } prevMana = mana; }
diff --git a/src/me/jayfella/c3p0extension/C3p0ExtensionPlugin.java b/src/me/jayfella/c3p0extension/C3p0ExtensionPlugin.java index e11ca18..6d233cc 100644 --- a/src/me/jayfella/c3p0extension/C3p0ExtensionPlugin.java +++ b/src/me/jayfella/c3p0extension/C3p0ExtensionPlugin.java @@ -1,172 +1,175 @@ package me.jayfella.c3p0extension; import com.mchange.v2.c3p0.ComboPooledDataSource; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.logging.Level; import org.bukkit.plugin.java.JavaPlugin; public final class C3p0ExtensionPlugin extends JavaPlugin { private final Map<DatabaseConnection, ComboPooledDataSource> dataSources = new HashMap<>(); public C3p0ExtensionPlugin() { Properties p = new Properties(System.getProperties()); p.put("com.mchange.v2.log.MLog", "com.mchange.v2.log.FallbackMLog"); p.put("com.mchange.v2.log.FallbackMLog.DEFAULT_CUTOFF_LEVEL", "SEVERE"); System.setProperties(p); } @Override public void onEnable() { } @Override public void onDisable() { // Close all connections for the sake of being tidy. Iterator it = dataSources.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry)it.next(); ComboPooledDataSource source = (ComboPooledDataSource)pair.getValue(); source.close(); it.remove(); } } public boolean createDataSource(DatabaseConnection databaseConnection) { //ensure a datasource doesnt already exist for this database if (dataSources.get(databaseConnection) != null) { return true; } StringBuilder connectionString = new StringBuilder() .append("jdbc:") - .append(databaseConnection.getDatabaseType() - .getPrefix()) + .append(databaseConnection.getDatabaseType().getPrefix()) .append(databaseConnection.getAddress()); if (databaseConnection.getDatabaseType().requiresPort()) { connectionString .append(":") .append(databaseConnection.getPort()) .append("/") - .append(databaseConnection.getDatabaseName()) - .toString(); + .append(databaseConnection.getDatabaseName()); + } + else + { + connectionString + .append(databaseConnection.getDatabaseName()); } ComboPooledDataSource comboPool; try { comboPool = new ComboPooledDataSource(); comboPool.setAcquireIncrement(1); comboPool.setBreakAfterAcquireFailure(true); comboPool.setIdleConnectionTestPeriod(300); comboPool.setDriverClass(databaseConnection.getDatabaseType().getDriver()); comboPool.setJdbcUrl(connectionString.toString()); comboPool.setUser(databaseConnection.getUsername()); comboPool.setPassword(databaseConnection.getPassword()); comboPool.setInitialPoolSize(databaseConnection.getInitialPoolSize()); comboPool.setMinPoolSize(databaseConnection.getMaxPoolSize()); comboPool.setAcquireIncrement(databaseConnection.getacquireIncrement()); comboPool.setMaxPoolSize(databaseConnection.getMaxPoolSize()); } catch (Exception ex) { this.getLogger().log(Level.WARNING, ex.getMessage(), ex); return false; } // check the connection to ensure its valid. if (!checkConnection(comboPool)) { return false; } this.dataSources.put(databaseConnection, comboPool); return true; } public ComboPooledDataSource getDataSource(DatabaseConnection databaseConnection) { return dataSources.get(databaseConnection); } public Connection getConnection(DatabaseConnection databaseConnection) throws SQLException { return this.getDataSource(databaseConnection).getConnection(); } private boolean checkConnection(ComboPooledDataSource comboPool) { this.getLogger().log(Level.INFO, "Attempting connection to database: {0}", comboPool.getJdbcUrl()); Connection con = null; Statement st = null; ResultSet rs = null; try { con = comboPool.getConnection(); st = con.createStatement(); rs = st.executeQuery("SELECT VERSION()"); if (rs.next()) { this.getLogger().info("Database connection successful."); return true; } else { this.getLogger().info("Database connection FAILED."); return false; } } catch (SQLException ex) { this.getLogger().info("Database connection FAILED."); this.getLogger().log(Level.SEVERE, ex.getMessage(), ex); return false; } finally { try { if (rs != null) rs.close(); if (st != null) st.close(); if (con != null) con.close(); } catch (SQLException ex) { this.getLogger().log(Level.WARNING, ex.getMessage(), ex); return false; } } } }
false
true
public boolean createDataSource(DatabaseConnection databaseConnection) { //ensure a datasource doesnt already exist for this database if (dataSources.get(databaseConnection) != null) { return true; } StringBuilder connectionString = new StringBuilder() .append("jdbc:") .append(databaseConnection.getDatabaseType() .getPrefix()) .append(databaseConnection.getAddress()); if (databaseConnection.getDatabaseType().requiresPort()) { connectionString .append(":") .append(databaseConnection.getPort()) .append("/") .append(databaseConnection.getDatabaseName()) .toString(); } ComboPooledDataSource comboPool; try { comboPool = new ComboPooledDataSource(); comboPool.setAcquireIncrement(1); comboPool.setBreakAfterAcquireFailure(true); comboPool.setIdleConnectionTestPeriod(300); comboPool.setDriverClass(databaseConnection.getDatabaseType().getDriver()); comboPool.setJdbcUrl(connectionString.toString()); comboPool.setUser(databaseConnection.getUsername()); comboPool.setPassword(databaseConnection.getPassword()); comboPool.setInitialPoolSize(databaseConnection.getInitialPoolSize()); comboPool.setMinPoolSize(databaseConnection.getMaxPoolSize()); comboPool.setAcquireIncrement(databaseConnection.getacquireIncrement()); comboPool.setMaxPoolSize(databaseConnection.getMaxPoolSize()); } catch (Exception ex) { this.getLogger().log(Level.WARNING, ex.getMessage(), ex); return false; } // check the connection to ensure its valid. if (!checkConnection(comboPool)) { return false; } this.dataSources.put(databaseConnection, comboPool); return true; }
public boolean createDataSource(DatabaseConnection databaseConnection) { //ensure a datasource doesnt already exist for this database if (dataSources.get(databaseConnection) != null) { return true; } StringBuilder connectionString = new StringBuilder() .append("jdbc:") .append(databaseConnection.getDatabaseType().getPrefix()) .append(databaseConnection.getAddress()); if (databaseConnection.getDatabaseType().requiresPort()) { connectionString .append(":") .append(databaseConnection.getPort()) .append("/") .append(databaseConnection.getDatabaseName()); } else { connectionString .append(databaseConnection.getDatabaseName()); } ComboPooledDataSource comboPool; try { comboPool = new ComboPooledDataSource(); comboPool.setAcquireIncrement(1); comboPool.setBreakAfterAcquireFailure(true); comboPool.setIdleConnectionTestPeriod(300); comboPool.setDriverClass(databaseConnection.getDatabaseType().getDriver()); comboPool.setJdbcUrl(connectionString.toString()); comboPool.setUser(databaseConnection.getUsername()); comboPool.setPassword(databaseConnection.getPassword()); comboPool.setInitialPoolSize(databaseConnection.getInitialPoolSize()); comboPool.setMinPoolSize(databaseConnection.getMaxPoolSize()); comboPool.setAcquireIncrement(databaseConnection.getacquireIncrement()); comboPool.setMaxPoolSize(databaseConnection.getMaxPoolSize()); } catch (Exception ex) { this.getLogger().log(Level.WARNING, ex.getMessage(), ex); return false; } // check the connection to ensure its valid. if (!checkConnection(comboPool)) { return false; } this.dataSources.put(databaseConnection, comboPool); return true; }
diff --git a/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/KnowledgeStoreServiceImpl.java b/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/KnowledgeStoreServiceImpl.java index 02cd409adc..3343babc7b 100644 --- a/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/KnowledgeStoreServiceImpl.java +++ b/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/KnowledgeStoreServiceImpl.java @@ -1,192 +1,192 @@ package org.drools.persistence.jpa; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.Properties; import org.drools.KnowledgeBase; import org.drools.SessionConfiguration; import org.drools.command.CommandService; import org.drools.command.impl.CommandBasedStatefulKnowledgeSession; import org.drools.persistence.SingleSessionCommandService; import org.drools.persistence.jpa.KnowledgeStoreService; import org.drools.persistence.jpa.processinstance.JPAWorkItemManagerFactory; import org.drools.process.instance.WorkItemManagerFactory; import org.drools.runtime.CommandExecutor; import org.drools.runtime.Environment; import org.drools.runtime.KnowledgeSessionConfiguration; import org.drools.runtime.StatefulKnowledgeSession; import org.drools.time.TimerService; public class KnowledgeStoreServiceImpl implements KnowledgeStoreService { private Class< ? extends CommandExecutor> commandServiceClass; private Class< ? extends WorkItemManagerFactory> workItemManagerFactoryClass; private Class< ? extends TimerService> timerServiceClass; private Properties configProps = new Properties(); public KnowledgeStoreServiceImpl() { setDefaultImplementations(); } protected void setDefaultImplementations() { setCommandServiceClass( SingleSessionCommandService.class ); setProcessInstanceManagerFactoryClass( "org.jbpm.persistence.processinstance.JPAProcessInstanceManagerFactory" ); setWorkItemManagerFactoryClass( JPAWorkItemManagerFactory.class ); setProcessSignalManagerFactoryClass( "org.jbpm.persistence.processinstance.JPASignalManagerFactory" ); setTimerServiceClass( JpaJDKTimerService.class ); } public StatefulKnowledgeSession newStatefulKnowledgeSession(KnowledgeBase kbase, KnowledgeSessionConfiguration configuration, Environment environment) { if ( configuration == null ) { configuration = new SessionConfiguration(); } if ( environment == null ) { throw new IllegalArgumentException( "Environment cannot be null" ); } return new CommandBasedStatefulKnowledgeSession( (CommandService) buildCommanService( kbase, mergeConfig( configuration ), environment ) ); } public StatefulKnowledgeSession loadStatefulKnowledgeSession(long id, KnowledgeBase kbase, KnowledgeSessionConfiguration configuration, Environment environment) { if ( configuration == null ) { configuration = new SessionConfiguration(); } if ( environment == null ) { throw new IllegalArgumentException( "Environment cannot be null" ); } return new CommandBasedStatefulKnowledgeSession( (CommandService) buildCommanService( id, kbase, mergeConfig( configuration ), environment ) ); } private CommandExecutor buildCommanService(long sessionId, KnowledgeBase kbase, KnowledgeSessionConfiguration conf, Environment env) { try { Class< ? extends CommandExecutor> serviceClass = getCommandServiceClass(); - Constructor< ? extends CommandExecutor> constructor = serviceClass.getConstructor( int.class, + Constructor< ? extends CommandExecutor> constructor = serviceClass.getConstructor( long.class, KnowledgeBase.class, KnowledgeSessionConfiguration.class, Environment.class ); return constructor.newInstance( sessionId, kbase, conf, env ); } catch ( SecurityException e ) { throw new IllegalStateException( e ); } catch ( NoSuchMethodException e ) { throw new IllegalStateException( e ); } catch ( IllegalArgumentException e ) { throw new IllegalStateException( e ); } catch ( InstantiationException e ) { throw new IllegalStateException( e ); } catch ( IllegalAccessException e ) { throw new IllegalStateException( e ); } catch ( InvocationTargetException e ) { throw new IllegalStateException( e ); } } private CommandExecutor buildCommanService(KnowledgeBase kbase, KnowledgeSessionConfiguration conf, Environment env) { Class< ? extends CommandExecutor> serviceClass = getCommandServiceClass(); try { Constructor< ? extends CommandExecutor> constructor = serviceClass.getConstructor( KnowledgeBase.class, KnowledgeSessionConfiguration.class, Environment.class ); return constructor.newInstance( kbase, conf, env ); } catch ( SecurityException e ) { throw new IllegalStateException( e ); } catch ( NoSuchMethodException e ) { throw new IllegalStateException( e ); } catch ( IllegalArgumentException e ) { throw new IllegalStateException( e ); } catch ( InstantiationException e ) { throw new IllegalStateException( e ); } catch ( IllegalAccessException e ) { throw new IllegalStateException( e ); } catch ( InvocationTargetException e ) { throw new IllegalStateException( e ); } } private KnowledgeSessionConfiguration mergeConfig(KnowledgeSessionConfiguration configuration) { ((SessionConfiguration) configuration).addProperties( configProps ); return configuration; } public long getStatefulKnowledgeSessionId(StatefulKnowledgeSession ksession) { if ( ksession instanceof CommandBasedStatefulKnowledgeSession ) { SingleSessionCommandService commandService = (SingleSessionCommandService) ((CommandBasedStatefulKnowledgeSession) ksession).getCommandService(); return commandService.getSessionId(); } throw new IllegalArgumentException( "StatefulKnowledgeSession must be an a CommandBasedStatefulKnowledgeSession" ); } public void setCommandServiceClass(Class< ? extends CommandExecutor> commandServiceClass) { if ( commandServiceClass != null ) { this.commandServiceClass = commandServiceClass; configProps.put( "drools.commandService", commandServiceClass.getName() ); } } public Class< ? extends CommandExecutor> getCommandServiceClass() { return commandServiceClass; } public void setTimerServiceClass(Class< ? extends TimerService> timerServiceClass) { if ( timerServiceClass != null ) { this.timerServiceClass = timerServiceClass; configProps.put( "drools.timerService", timerServiceClass.getName() ); } } public Class< ? extends TimerService> getTimerServiceClass() { return timerServiceClass; } public void setProcessInstanceManagerFactoryClass(String processInstanceManagerFactoryClass) { configProps.put( "drools.processInstanceManagerFactory", processInstanceManagerFactoryClass ); } public void setWorkItemManagerFactoryClass(Class< ? extends WorkItemManagerFactory> workItemManagerFactoryClass) { if ( workItemManagerFactoryClass != null ) { this.workItemManagerFactoryClass = workItemManagerFactoryClass; configProps.put( "drools.workItemManagerFactory", workItemManagerFactoryClass.getName() ); } } public Class< ? extends WorkItemManagerFactory> getWorkItemManagerFactoryClass() { return workItemManagerFactoryClass; } public void setProcessSignalManagerFactoryClass(String processSignalManagerFactoryClass) { configProps.put( "drools.processSignalManagerFactory", processSignalManagerFactoryClass ); } }
true
true
private CommandExecutor buildCommanService(long sessionId, KnowledgeBase kbase, KnowledgeSessionConfiguration conf, Environment env) { try { Class< ? extends CommandExecutor> serviceClass = getCommandServiceClass(); Constructor< ? extends CommandExecutor> constructor = serviceClass.getConstructor( int.class, KnowledgeBase.class, KnowledgeSessionConfiguration.class, Environment.class ); return constructor.newInstance( sessionId, kbase, conf, env ); } catch ( SecurityException e ) { throw new IllegalStateException( e ); } catch ( NoSuchMethodException e ) { throw new IllegalStateException( e ); } catch ( IllegalArgumentException e ) { throw new IllegalStateException( e ); } catch ( InstantiationException e ) { throw new IllegalStateException( e ); } catch ( IllegalAccessException e ) { throw new IllegalStateException( e ); } catch ( InvocationTargetException e ) { throw new IllegalStateException( e ); } }
private CommandExecutor buildCommanService(long sessionId, KnowledgeBase kbase, KnowledgeSessionConfiguration conf, Environment env) { try { Class< ? extends CommandExecutor> serviceClass = getCommandServiceClass(); Constructor< ? extends CommandExecutor> constructor = serviceClass.getConstructor( long.class, KnowledgeBase.class, KnowledgeSessionConfiguration.class, Environment.class ); return constructor.newInstance( sessionId, kbase, conf, env ); } catch ( SecurityException e ) { throw new IllegalStateException( e ); } catch ( NoSuchMethodException e ) { throw new IllegalStateException( e ); } catch ( IllegalArgumentException e ) { throw new IllegalStateException( e ); } catch ( InstantiationException e ) { throw new IllegalStateException( e ); } catch ( IllegalAccessException e ) { throw new IllegalStateException( e ); } catch ( InvocationTargetException e ) { throw new IllegalStateException( e ); } }
diff --git a/bennu-core/src/myorg/_development/PropertiesManager.java b/bennu-core/src/myorg/_development/PropertiesManager.java index fffc8a44..dc8f7a88 100755 --- a/bennu-core/src/myorg/_development/PropertiesManager.java +++ b/bennu-core/src/myorg/_development/PropertiesManager.java @@ -1,112 +1,112 @@ /* * @(#)PropertiesManager.java * * Copyright 2009 Instituto Superior Tecnico * Founding Authors: João Figueiredo, Luis Cruz, Paulo Abrantes, Susana Fernandes * * https://fenix-ashes.ist.utl.pt/ * * This file is part of the MyOrg web application infrastructure. * * MyOrg 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.* * * MyOrg 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 MyOrg. If not, see <http://www.gnu.org/licenses/>. * */ package myorg._development; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Properties; import pt.ist.fenixWebFramework.Config; import pt.ist.fenixWebFramework.Config.CasConfig; /** * The <code>PropertiesManager</code> class is a application wide utility for * accessing the applications configuration and properties. * * @author João Figueiredo * @author Luis Cruz * @author Paulo Abrantes * @author Susana Fernandes * * @version 1.0 */ public class PropertiesManager extends pt.utl.ist.fenix.tools.util.PropertiesManager { private static final Properties properties = new Properties(); static { try { loadProperties(properties, "/configuration.properties"); } catch (IOException e) { throw new RuntimeException("Unable to load properties files.", e); } } public static String getProperty(final String key) { return properties.getProperty(key); } public static boolean getBooleanProperty(final String key) { return Boolean.parseBoolean(properties.getProperty(key)); } public static Integer getIntegerProperty(final String key) { return Integer.valueOf(properties.getProperty(key)); } public static void setProperty(final String key, final String value) { properties.setProperty(key, value); } public static Config getFenixFrameworkConfig(final String[] domainModels) { final Map<String, CasConfig> casConfigMap = new HashMap<String, CasConfig>(); for (final Object key : properties.keySet()) { final String property = (String) key; int i = property.indexOf(".cas.enable"); if (i >= 0) { final String hostname = property.substring(0, i); if (getBooleanProperty(property)) { final String casLoginUrl = getProperty(hostname + ".cas.loginUrl"); - final String casLogoutUrl = getProperty(hostname + ".cas.loginUrl"); + final String casLogoutUrl = getProperty(hostname + ".cas.logoutUrl"); final String casValidateUrl = getProperty(hostname + ".cas.ValidateUrl"); - final String serviceUrl = getProperty(hostname + ".cas.logoutUrl"); + final String serviceUrl = getProperty(hostname + ".cas.serviceUrl"); new CasConfig(casLoginUrl, casLogoutUrl, casValidateUrl, serviceUrl); } } } return new Config() {{ domainModelPaths = domainModels; dbAlias = getProperty("db.alias"); dbUsername = getProperty("db.user"); dbPassword = getProperty("db.pass"); appName = getProperty("app.name"); appContext = getProperty("app.context"); filterRequestWithDigest = getBooleanProperty("filter.request.with.digest"); tamperingRedirect = getProperty("digest.tampering.url"); errorIfChangingDeletedObject = getBooleanProperty("error.if.changing.deleted.object"); defaultLanguage = getProperty("language"); defaultLocation = getProperty("location"); defaultVariant = getProperty("variant"); updateDataRepositoryStructure = true; casConfigByHost = Collections.unmodifiableMap(casConfigMap); }}; } }
false
true
public static Config getFenixFrameworkConfig(final String[] domainModels) { final Map<String, CasConfig> casConfigMap = new HashMap<String, CasConfig>(); for (final Object key : properties.keySet()) { final String property = (String) key; int i = property.indexOf(".cas.enable"); if (i >= 0) { final String hostname = property.substring(0, i); if (getBooleanProperty(property)) { final String casLoginUrl = getProperty(hostname + ".cas.loginUrl"); final String casLogoutUrl = getProperty(hostname + ".cas.loginUrl"); final String casValidateUrl = getProperty(hostname + ".cas.ValidateUrl"); final String serviceUrl = getProperty(hostname + ".cas.logoutUrl"); new CasConfig(casLoginUrl, casLogoutUrl, casValidateUrl, serviceUrl); } } } return new Config() {{ domainModelPaths = domainModels; dbAlias = getProperty("db.alias"); dbUsername = getProperty("db.user"); dbPassword = getProperty("db.pass"); appName = getProperty("app.name"); appContext = getProperty("app.context"); filterRequestWithDigest = getBooleanProperty("filter.request.with.digest"); tamperingRedirect = getProperty("digest.tampering.url"); errorIfChangingDeletedObject = getBooleanProperty("error.if.changing.deleted.object"); defaultLanguage = getProperty("language"); defaultLocation = getProperty("location"); defaultVariant = getProperty("variant"); updateDataRepositoryStructure = true; casConfigByHost = Collections.unmodifiableMap(casConfigMap); }}; }
public static Config getFenixFrameworkConfig(final String[] domainModels) { final Map<String, CasConfig> casConfigMap = new HashMap<String, CasConfig>(); for (final Object key : properties.keySet()) { final String property = (String) key; int i = property.indexOf(".cas.enable"); if (i >= 0) { final String hostname = property.substring(0, i); if (getBooleanProperty(property)) { final String casLoginUrl = getProperty(hostname + ".cas.loginUrl"); final String casLogoutUrl = getProperty(hostname + ".cas.logoutUrl"); final String casValidateUrl = getProperty(hostname + ".cas.ValidateUrl"); final String serviceUrl = getProperty(hostname + ".cas.serviceUrl"); new CasConfig(casLoginUrl, casLogoutUrl, casValidateUrl, serviceUrl); } } } return new Config() {{ domainModelPaths = domainModels; dbAlias = getProperty("db.alias"); dbUsername = getProperty("db.user"); dbPassword = getProperty("db.pass"); appName = getProperty("app.name"); appContext = getProperty("app.context"); filterRequestWithDigest = getBooleanProperty("filter.request.with.digest"); tamperingRedirect = getProperty("digest.tampering.url"); errorIfChangingDeletedObject = getBooleanProperty("error.if.changing.deleted.object"); defaultLanguage = getProperty("language"); defaultLocation = getProperty("location"); defaultVariant = getProperty("variant"); updateDataRepositoryStructure = true; casConfigByHost = Collections.unmodifiableMap(casConfigMap); }}; }
diff --git a/src/org/latte/Run.java b/src/org/latte/Run.java index 93b0e6b..3766d7e 100644 --- a/src/org/latte/Run.java +++ b/src/org/latte/Run.java @@ -1,27 +1,27 @@ package org.latte; import org.apache.log4j.PropertyConfigurator; import org.latte.scripting.Javascript; import org.latte.scripting.ScriptLoader; public class Run { /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { PropertyConfigurator.configure("log4j.properties"); if(args.length == 1) { ((Javascript)new ScriptLoader("").get(args[0])).eval(null); } else if(args.length == 2) { - ((Javascript)new ScriptLoader(args[0].split(";")).get(args[1])).eval(null); + ((Javascript)new ScriptLoader(args[0].split(":")).get(args[1])).eval(null); } else { System.err.println("expecting 1 or 2 argument(s)"); System.exit(-1); } } }
true
true
public static void main(String[] args) throws Exception { PropertyConfigurator.configure("log4j.properties"); if(args.length == 1) { ((Javascript)new ScriptLoader("").get(args[0])).eval(null); } else if(args.length == 2) { ((Javascript)new ScriptLoader(args[0].split(";")).get(args[1])).eval(null); } else { System.err.println("expecting 1 or 2 argument(s)"); System.exit(-1); } }
public static void main(String[] args) throws Exception { PropertyConfigurator.configure("log4j.properties"); if(args.length == 1) { ((Javascript)new ScriptLoader("").get(args[0])).eval(null); } else if(args.length == 2) { ((Javascript)new ScriptLoader(args[0].split(":")).get(args[1])).eval(null); } else { System.err.println("expecting 1 or 2 argument(s)"); System.exit(-1); } }
diff --git a/src/se/chalmers/watchme/activity/AddMovieActivity.java b/src/se/chalmers/watchme/activity/AddMovieActivity.java index fa03742..623647a 100644 --- a/src/se/chalmers/watchme/activity/AddMovieActivity.java +++ b/src/se/chalmers/watchme/activity/AddMovieActivity.java @@ -1,131 +1,131 @@ package se.chalmers.watchme.activity; import java.util.Calendar; import se.chalmers.watchme.R; import se.chalmers.watchme.R.id; import se.chalmers.watchme.R.layout; import se.chalmers.watchme.R.menu; import se.chalmers.watchme.database.DatabaseHandler; import se.chalmers.watchme.model.Movie; import se.chalmers.watchme.notifications.NotificationClient; import android.os.Bundle; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.DatePicker; import android.widget.TextView; import android.widget.Toast; import android.support.v4.app.NavUtils; import android.view.View.OnClickListener; public class AddMovieActivity extends Activity { private TextView textField; private DatePicker picker; // The handler to interface with the notification system and scheduler private NotificationClient notifications; // The database handler private DatabaseHandler db; @SuppressLint("NewApi") @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_movie); getActionBar().setDisplayHomeAsUpEnabled(true); this.textField = (TextView) findViewById(R.id.movie_name_field); this.picker = (DatePicker) findViewById(R.id.date_picker); this.db = new DatabaseHandler(this); this.notifications = new NotificationClient(this); this.notifications.connectToService(); } /** * Click callback. Create a new Movie object and set it on * the Intent, and then finish this Activity. */ public void onAddButtonClick(View view) { addMovie(); finish(); } private void addMovie() { Movie movie = new Movie(textField.getText().toString()); db.addMovie(movie); Intent home = new Intent(this, MainActivity.class); setResult(RESULT_OK, home); home.putExtra("movie", movie); // Set a notification for the date picked setNotification(movie); } private void setNotification(Movie movie) { //TODO The date info below should come from the // movie model - not directly from the date picker int day = this.picker.getDayOfMonth(); int month = this.picker.getMonth(); int year = this.picker.getYear(); Calendar date = Calendar.getInstance(); date.set(year, month, day); // Set the timestamp to midnight - date.set(Calendar.HOUR_OF_DAY, 22); - date.set(Calendar.MINUTE, 20); + date.set(Calendar.HOUR_OF_DAY, 0); + date.set(Calendar.MINUTE, 0); date.set(Calendar.SECOND, 0); this.notifications.setMovieNotification(movie, date); Toast.makeText(this, "Notification set for " + day + "/" + (month+1) + "/"+year, Toast.LENGTH_LONG).show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_add_movie, menu); return true; } @Override protected void onStop() { // Disconnect the service (if started) when this activity is stopped. if(this.notifications != null) { this.notifications.disconnectService(); } super.onStop(); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: NavUtils.navigateUpFromSameTask(this); return true; } return super.onOptionsItemSelected(item); } }
true
true
private void setNotification(Movie movie) { //TODO The date info below should come from the // movie model - not directly from the date picker int day = this.picker.getDayOfMonth(); int month = this.picker.getMonth(); int year = this.picker.getYear(); Calendar date = Calendar.getInstance(); date.set(year, month, day); // Set the timestamp to midnight date.set(Calendar.HOUR_OF_DAY, 22); date.set(Calendar.MINUTE, 20); date.set(Calendar.SECOND, 0); this.notifications.setMovieNotification(movie, date); Toast.makeText(this, "Notification set for " + day + "/" + (month+1) + "/"+year, Toast.LENGTH_LONG).show(); }
private void setNotification(Movie movie) { //TODO The date info below should come from the // movie model - not directly from the date picker int day = this.picker.getDayOfMonth(); int month = this.picker.getMonth(); int year = this.picker.getYear(); Calendar date = Calendar.getInstance(); date.set(year, month, day); // Set the timestamp to midnight date.set(Calendar.HOUR_OF_DAY, 0); date.set(Calendar.MINUTE, 0); date.set(Calendar.SECOND, 0); this.notifications.setMovieNotification(movie, date); Toast.makeText(this, "Notification set for " + day + "/" + (month+1) + "/"+year, Toast.LENGTH_LONG).show(); }
diff --git a/Core/SDK/org.emftext.sdk.codegen.resource.ui/src/org/emftext/sdk/codegen/resource/ui/generators/ui/HyperlinkDetectorGenerator.java b/Core/SDK/org.emftext.sdk.codegen.resource.ui/src/org/emftext/sdk/codegen/resource/ui/generators/ui/HyperlinkDetectorGenerator.java index e72207a6e..614f377b2 100644 --- a/Core/SDK/org.emftext.sdk.codegen.resource.ui/src/org/emftext/sdk/codegen/resource/ui/generators/ui/HyperlinkDetectorGenerator.java +++ b/Core/SDK/org.emftext.sdk.codegen.resource.ui/src/org/emftext/sdk/codegen/resource/ui/generators/ui/HyperlinkDetectorGenerator.java @@ -1,103 +1,103 @@ /******************************************************************************* * Copyright (c) 2006-2012 * Software Technology Group, Dresden University of Technology * DevBoost GmbH, Berlin, Amtsgericht Charlottenburg, HRB 140026 * * 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 * * Contributors: * Software Technology Group - TU Dresden, Germany; * DevBoost GmbH - Berlin, Germany * - initial API and implementation ******************************************************************************/ package org.emftext.sdk.codegen.resource.ui.generators.ui; import static org.emftext.sdk.codegen.resource.ui.IUIClassNameConstants.BAD_LOCATION_EXCEPTION; import static org.emftext.sdk.codegen.resource.ui.IUIClassNameConstants.ECORE_UTIL; import static org.emftext.sdk.codegen.resource.ui.IUIClassNameConstants.E_OBJECT; import static org.emftext.sdk.codegen.resource.ui.IUIClassNameConstants.I_HYPERLINK; import static org.emftext.sdk.codegen.resource.ui.IUIClassNameConstants.I_HYPERLINK_DETECTOR; import static org.emftext.sdk.codegen.resource.ui.IUIClassNameConstants.I_REGION; import static org.emftext.sdk.codegen.resource.ui.IUIClassNameConstants.I_TEXT_VIEWER; import static org.emftext.sdk.codegen.resource.ui.IUIClassNameConstants.LIST; import static org.emftext.sdk.codegen.resource.ui.IUIClassNameConstants.REGION; import static org.emftext.sdk.codegen.resource.ui.IUIClassNameConstants.RESOURCE; import org.emftext.sdk.codegen.composites.JavaComposite; import org.emftext.sdk.codegen.composites.StringComposite; import org.emftext.sdk.codegen.parameters.ArtifactParameter; import org.emftext.sdk.codegen.resource.GenerationContext; import org.emftext.sdk.codegen.resource.ui.generators.UIJavaBaseGenerator; public class HyperlinkDetectorGenerator extends UIJavaBaseGenerator<ArtifactParameter<GenerationContext>> { public void generateJavaContents(JavaComposite sc) { sc.add("package " + getResourcePackageName() + ";"); sc.addLineBreak(); sc.addJavadoc( "A hyperlink detector returns hyperlink if the token, where the mouse cursor " + "hovers, is a proxy." ); sc.add("public class " + getResourceClassName() + " implements " + I_HYPERLINK_DETECTOR + " {"); sc.addLineBreak(); addFields(sc); addConstructor(sc); addDetectHyperlinksMethod(sc); sc.add("}"); } private void addFields(StringComposite sc) { sc.add("private " + iTextResourceClassName + " textResource;"); sc.addLineBreak(); } private void addDetectHyperlinksMethod(JavaComposite sc) { sc.add("public " + I_HYPERLINK + "[] detectHyperlinks(" + I_TEXT_VIEWER + " textViewer, " + I_REGION + " region, boolean canShowMultipleHyperlinks) {"); sc.add(iLocationMapClassName + " locationMap = textResource.getLocationMap();"); sc.add(LIST + "<" + E_OBJECT + "> elementsAtOffset = locationMap.getElementsAt(region.getOffset());"); sc.add(E_OBJECT + " resolvedEObject = null;"); sc.add("for (" + E_OBJECT + " eObject : elementsAtOffset) {"); sc.add("if (eObject.eIsProxy()) {"); sc.add("resolvedEObject = " + ECORE_UTIL + ".resolve(eObject, textResource);"); sc.add("if (resolvedEObject == eObject) {"); sc.add("continue;"); sc.add("}"); sc.add("int offset = locationMap.getCharStart(eObject);"); sc.add("int length = locationMap.getCharEnd(eObject) - offset + 1;"); sc.add("String text = null;"); sc.add("try {"); sc.add("text = textViewer.getDocument().get(offset, length);"); sc.add("} catch (" + BAD_LOCATION_EXCEPTION + " e) {"); sc.add("}"); - sc.addComment("we skipt elements that are not contained in a resource, because we cannot jump to them anyway"); + sc.addComment("we skip elements that are not contained in a resource, because we cannot jump to them anyway"); sc.add("if (resolvedEObject.eResource() != null) {"); sc.add(I_HYPERLINK + " hyperlink = new " + hyperlinkClassName + "(new " + REGION + "(offset, length), resolvedEObject, text);"); - sc.add("return new " + I_HYPERLINK + "[] { hyperlink };"); + sc.add("return new " + I_HYPERLINK + "[] {hyperlink};"); sc.add("}"); sc.add("}"); sc.add("}"); sc.add("return null;"); sc.add("}"); sc.addLineBreak(); } private void addConstructor(JavaComposite sc) { sc.addJavadoc( "Creates a hyperlink detector.", "@param resource the resource to use for calculating the locations." ); sc.add("public " + getResourceClassName() + "(" + RESOURCE + " resource) {"); sc.add("textResource = (" + iTextResourceClassName + ") resource;"); sc.add("}"); sc.addLineBreak(); } }
false
true
private void addDetectHyperlinksMethod(JavaComposite sc) { sc.add("public " + I_HYPERLINK + "[] detectHyperlinks(" + I_TEXT_VIEWER + " textViewer, " + I_REGION + " region, boolean canShowMultipleHyperlinks) {"); sc.add(iLocationMapClassName + " locationMap = textResource.getLocationMap();"); sc.add(LIST + "<" + E_OBJECT + "> elementsAtOffset = locationMap.getElementsAt(region.getOffset());"); sc.add(E_OBJECT + " resolvedEObject = null;"); sc.add("for (" + E_OBJECT + " eObject : elementsAtOffset) {"); sc.add("if (eObject.eIsProxy()) {"); sc.add("resolvedEObject = " + ECORE_UTIL + ".resolve(eObject, textResource);"); sc.add("if (resolvedEObject == eObject) {"); sc.add("continue;"); sc.add("}"); sc.add("int offset = locationMap.getCharStart(eObject);"); sc.add("int length = locationMap.getCharEnd(eObject) - offset + 1;"); sc.add("String text = null;"); sc.add("try {"); sc.add("text = textViewer.getDocument().get(offset, length);"); sc.add("} catch (" + BAD_LOCATION_EXCEPTION + " e) {"); sc.add("}"); sc.addComment("we skipt elements that are not contained in a resource, because we cannot jump to them anyway"); sc.add("if (resolvedEObject.eResource() != null) {"); sc.add(I_HYPERLINK + " hyperlink = new " + hyperlinkClassName + "(new " + REGION + "(offset, length), resolvedEObject, text);"); sc.add("return new " + I_HYPERLINK + "[] { hyperlink };"); sc.add("}"); sc.add("}"); sc.add("}"); sc.add("return null;"); sc.add("}"); sc.addLineBreak(); }
private void addDetectHyperlinksMethod(JavaComposite sc) { sc.add("public " + I_HYPERLINK + "[] detectHyperlinks(" + I_TEXT_VIEWER + " textViewer, " + I_REGION + " region, boolean canShowMultipleHyperlinks) {"); sc.add(iLocationMapClassName + " locationMap = textResource.getLocationMap();"); sc.add(LIST + "<" + E_OBJECT + "> elementsAtOffset = locationMap.getElementsAt(region.getOffset());"); sc.add(E_OBJECT + " resolvedEObject = null;"); sc.add("for (" + E_OBJECT + " eObject : elementsAtOffset) {"); sc.add("if (eObject.eIsProxy()) {"); sc.add("resolvedEObject = " + ECORE_UTIL + ".resolve(eObject, textResource);"); sc.add("if (resolvedEObject == eObject) {"); sc.add("continue;"); sc.add("}"); sc.add("int offset = locationMap.getCharStart(eObject);"); sc.add("int length = locationMap.getCharEnd(eObject) - offset + 1;"); sc.add("String text = null;"); sc.add("try {"); sc.add("text = textViewer.getDocument().get(offset, length);"); sc.add("} catch (" + BAD_LOCATION_EXCEPTION + " e) {"); sc.add("}"); sc.addComment("we skip elements that are not contained in a resource, because we cannot jump to them anyway"); sc.add("if (resolvedEObject.eResource() != null) {"); sc.add(I_HYPERLINK + " hyperlink = new " + hyperlinkClassName + "(new " + REGION + "(offset, length), resolvedEObject, text);"); sc.add("return new " + I_HYPERLINK + "[] {hyperlink};"); sc.add("}"); sc.add("}"); sc.add("}"); sc.add("return null;"); sc.add("}"); sc.addLineBreak(); }
diff --git a/android/src/com/google/zxing/client/android/camera/CameraManager.java b/android/src/com/google/zxing/client/android/camera/CameraManager.java index d35d991d..6a4113bd 100755 --- a/android/src/com/google/zxing/client/android/camera/CameraManager.java +++ b/android/src/com/google/zxing/client/android/camera/CameraManager.java @@ -1,273 +1,277 @@ /* * Copyright (C) 2008 ZXing 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.google.zxing.client.android.camera; import android.content.Context; import android.graphics.Point; import android.graphics.Rect; import android.hardware.Camera; import android.os.Handler; import android.util.Log; import android.view.SurfaceHolder; import com.google.zxing.client.android.PlanarYUVLuminanceSource; import java.io.IOException; /** * This object wraps the Camera service object and expects to be the only one talking to it. The * implementation encapsulates the steps needed to take preview-sized images, which are used for * both preview and decoding. * * @author [email protected] (Daniel Switkin) */ public final class CameraManager { private static final String TAG = CameraManager.class.getSimpleName(); private static final int MIN_FRAME_WIDTH = 240; private static final int MIN_FRAME_HEIGHT = 240; private static final int MAX_FRAME_WIDTH = 600; private static final int MAX_FRAME_HEIGHT = 400; private final CameraConfigurationManager configManager; private Camera camera; private Rect framingRect; private Rect framingRectInPreview; private boolean initialized; private boolean previewing; private int requestedFramingRectWidth; private int requestedFramingRectHeight; /** * Preview frames are delivered here, which we pass on to the registered handler. Make sure to * clear the handler so it will only receive one message. */ private final PreviewCallback previewCallback; /** Autofocus callbacks arrive here, and are dispatched to the Handler which requested them. */ private final AutoFocusCallback autoFocusCallback; public CameraManager(Context context) { this.configManager = new CameraConfigurationManager(context); previewCallback = new PreviewCallback(configManager); autoFocusCallback = new AutoFocusCallback(); } /** * Opens the camera driver and initializes the hardware parameters. * * @param holder The surface object which the camera will draw preview frames into. * @throws IOException Indicates the camera driver failed to open. */ public void openDriver(SurfaceHolder holder) throws IOException { Camera theCamera = camera; if (theCamera == null) { theCamera = Camera.open(); if (theCamera == null) { throw new IOException(); } camera = theCamera; } theCamera.setPreviewDisplay(holder); if (!initialized) { initialized = true; configManager.initFromCameraParameters(theCamera); if (requestedFramingRectWidth > 0 && requestedFramingRectHeight > 0) { setManualFramingRect(requestedFramingRectWidth, requestedFramingRectHeight); requestedFramingRectWidth = 0; requestedFramingRectHeight = 0; } } configManager.setDesiredCameraParameters(theCamera); } /** * Closes the camera driver if still in use. */ public void closeDriver() { if (camera != null) { camera.release(); camera = null; // Make sure to clear these each time we close the camera, so that any scanning rect // requested by intent is forgotten. framingRect = null; framingRectInPreview = null; } } /** * Asks the camera hardware to begin drawing preview frames to the screen. */ public void startPreview() { Camera theCamera = camera; if (theCamera != null && !previewing) { theCamera.startPreview(); previewing = true; } } /** * Tells the camera to stop drawing preview frames. */ public void stopPreview() { if (camera != null && previewing) { camera.stopPreview(); previewCallback.setHandler(null, 0); autoFocusCallback.setHandler(null, 0); previewing = false; } } /** * A single preview frame will be returned to the handler supplied. The data will arrive as byte[] * in the message.obj field, with width and height encoded as message.arg1 and message.arg2, * respectively. * * @param handler The handler to send the message to. * @param message The what field of the message to be sent. */ public void requestPreviewFrame(Handler handler, int message) { Camera theCamera = camera; if (theCamera != null && previewing) { previewCallback.setHandler(handler, message); theCamera.setOneShotPreviewCallback(previewCallback); } } /** * Asks the camera hardware to perform an autofocus. * * @param handler The Handler to notify when the autofocus completes. * @param message The message to deliver. */ public void requestAutoFocus(Handler handler, int message) { if (camera != null && previewing) { autoFocusCallback.setHandler(handler, message); try { camera.autoFocus(autoFocusCallback); } catch (RuntimeException re) { // Have heard RuntimeException reported in Android 4.0.x+; continue? Log.w(TAG, "Unexpected exception while focusing", re); } } } /** * Calculates the framing rect which the UI should draw to show the user where to place the * barcode. This target helps with alignment as well as forces the user to hold the device * far enough away to ensure the image will be in focus. * * @return The rectangle to draw on screen in window coordinates. */ public Rect getFramingRect() { if (framingRect == null) { if (camera == null) { return null; } Point screenResolution = configManager.getScreenResolution(); + if (screenResolution == null) { + // Called early, before init even finished + return null; + } int width = screenResolution.x * 3 / 4; if (width < MIN_FRAME_WIDTH) { width = MIN_FRAME_WIDTH; } else if (width > MAX_FRAME_WIDTH) { width = MAX_FRAME_WIDTH; } int height = screenResolution.y * 3 / 4; if (height < MIN_FRAME_HEIGHT) { height = MIN_FRAME_HEIGHT; } else if (height > MAX_FRAME_HEIGHT) { height = MAX_FRAME_HEIGHT; } int leftOffset = (screenResolution.x - width) / 2; int topOffset = (screenResolution.y - height) / 2; framingRect = new Rect(leftOffset, topOffset, leftOffset + width, topOffset + height); Log.d(TAG, "Calculated framing rect: " + framingRect); } return framingRect; } /** * Like {@link #getFramingRect} but coordinates are in terms of the preview frame, * not UI / screen. */ public Rect getFramingRectInPreview() { if (framingRectInPreview == null) { Rect framingRect = getFramingRect(); if (framingRect == null) { return null; } Rect rect = new Rect(framingRect); Point cameraResolution = configManager.getCameraResolution(); Point screenResolution = configManager.getScreenResolution(); if (cameraResolution == null || screenResolution == null) { // Called early, before init even finished return null; } rect.left = rect.left * cameraResolution.x / screenResolution.x; rect.right = rect.right * cameraResolution.x / screenResolution.x; rect.top = rect.top * cameraResolution.y / screenResolution.y; rect.bottom = rect.bottom * cameraResolution.y / screenResolution.y; framingRectInPreview = rect; } return framingRectInPreview; } /** * Allows third party apps to specify the scanning rectangle dimensions, rather than determine * them automatically based on screen resolution. * * @param width The width in pixels to scan. * @param height The height in pixels to scan. */ public void setManualFramingRect(int width, int height) { if (initialized) { Point screenResolution = configManager.getScreenResolution(); if (width > screenResolution.x) { width = screenResolution.x; } if (height > screenResolution.y) { height = screenResolution.y; } int leftOffset = (screenResolution.x - width) / 2; int topOffset = (screenResolution.y - height) / 2; framingRect = new Rect(leftOffset, topOffset, leftOffset + width, topOffset + height); Log.d(TAG, "Calculated manual framing rect: " + framingRect); framingRectInPreview = null; } else { requestedFramingRectWidth = width; requestedFramingRectHeight = height; } } /** * A factory method to build the appropriate LuminanceSource object based on the format * of the preview buffers, as described by Camera.Parameters. * * @param data A preview frame. * @param width The width of the image. * @param height The height of the image. * @return A PlanarYUVLuminanceSource instance. */ public PlanarYUVLuminanceSource buildLuminanceSource(byte[] data, int width, int height) { Rect rect = getFramingRectInPreview(); if (rect == null) { return null; } // Go ahead and assume it's YUV rather than die. return new PlanarYUVLuminanceSource(data, width, height, rect.left, rect.top, rect.width(), rect.height(), false); } }
true
true
public Rect getFramingRect() { if (framingRect == null) { if (camera == null) { return null; } Point screenResolution = configManager.getScreenResolution(); int width = screenResolution.x * 3 / 4; if (width < MIN_FRAME_WIDTH) { width = MIN_FRAME_WIDTH; } else if (width > MAX_FRAME_WIDTH) { width = MAX_FRAME_WIDTH; } int height = screenResolution.y * 3 / 4; if (height < MIN_FRAME_HEIGHT) { height = MIN_FRAME_HEIGHT; } else if (height > MAX_FRAME_HEIGHT) { height = MAX_FRAME_HEIGHT; } int leftOffset = (screenResolution.x - width) / 2; int topOffset = (screenResolution.y - height) / 2; framingRect = new Rect(leftOffset, topOffset, leftOffset + width, topOffset + height); Log.d(TAG, "Calculated framing rect: " + framingRect); } return framingRect; }
public Rect getFramingRect() { if (framingRect == null) { if (camera == null) { return null; } Point screenResolution = configManager.getScreenResolution(); if (screenResolution == null) { // Called early, before init even finished return null; } int width = screenResolution.x * 3 / 4; if (width < MIN_FRAME_WIDTH) { width = MIN_FRAME_WIDTH; } else if (width > MAX_FRAME_WIDTH) { width = MAX_FRAME_WIDTH; } int height = screenResolution.y * 3 / 4; if (height < MIN_FRAME_HEIGHT) { height = MIN_FRAME_HEIGHT; } else if (height > MAX_FRAME_HEIGHT) { height = MAX_FRAME_HEIGHT; } int leftOffset = (screenResolution.x - width) / 2; int topOffset = (screenResolution.y - height) / 2; framingRect = new Rect(leftOffset, topOffset, leftOffset + width, topOffset + height); Log.d(TAG, "Calculated framing rect: " + framingRect); } return framingRect; }
diff --git a/src/net/sf/freecol/client/control/InGameInputHandler.java b/src/net/sf/freecol/client/control/InGameInputHandler.java index fbcdd4bc4..b3885d5b2 100644 --- a/src/net/sf/freecol/client/control/InGameInputHandler.java +++ b/src/net/sf/freecol/client/control/InGameInputHandler.java @@ -1,1713 +1,1713 @@ /** * Copyright (C) 2002-2007 The FreeCol Team * * This file is part of FreeCol. * * FreeCol 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. * * FreeCol 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 FreeCol. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.freecol.client.control; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.SwingUtilities; import net.sf.freecol.FreeCol; import net.sf.freecol.client.FreeColClient; import net.sf.freecol.client.gui.Canvas; import net.sf.freecol.client.gui.animation.Animation; import net.sf.freecol.client.gui.animation.UnitMoveAnimation; import net.sf.freecol.client.gui.i18n.Messages; import net.sf.freecol.common.model.AbstractUnit; import net.sf.freecol.common.model.Colony; import net.sf.freecol.common.model.CombatModel.CombatResult; import net.sf.freecol.common.model.CombatModel.CombatResultType; import net.sf.freecol.common.model.DiplomaticTrade; import net.sf.freecol.common.model.FoundingFather; import net.sf.freecol.common.model.FoundingFather.FoundingFatherType; import net.sf.freecol.common.model.FreeColGameObject; import net.sf.freecol.common.model.Goods; import net.sf.freecol.common.model.GoodsType; import net.sf.freecol.common.model.LostCityRumour; import net.sf.freecol.common.model.Map; import net.sf.freecol.common.model.Map.Direction; import net.sf.freecol.common.model.Map.Position; import net.sf.freecol.common.model.ModelMessage; import net.sf.freecol.common.model.Modifier; import net.sf.freecol.common.model.Monarch; import net.sf.freecol.common.model.Player; import net.sf.freecol.common.model.Player.Stance; import net.sf.freecol.common.model.Settlement; import net.sf.freecol.common.model.Tension; import net.sf.freecol.common.model.Tile; import net.sf.freecol.common.model.Unit; import net.sf.freecol.common.model.UnitType; import net.sf.freecol.common.networking.Connection; import net.sf.freecol.common.networking.Message; import org.w3c.dom.Element; import org.w3c.dom.NodeList; /** * Handles the network messages that arrives while in the getGame(). */ public final class InGameInputHandler extends InputHandler { private static final Logger logger = Logger.getLogger(InGameInputHandler.class.getName()); /** * The constructor to use. * * @param freeColClient The main controller. */ public InGameInputHandler(FreeColClient freeColClient) { super(freeColClient); } /** * Deals with incoming messages that have just been received. * * @param connection The <code>Connection</code> the message was received * on. * @param element The root element of the message. * @return The reply. */ @Override public Element handle(Connection connection, Element element) { Element reply = null; if (element != null) { String type = element.getTagName(); logger.log(Level.FINEST, "Received message " + type); if (type.equals("update")) { reply = update(element); } else if (type.equals("remove")) { reply = remove(element); } else if (type.equals("opponentMove")) { reply = opponentMove(element); } else if (type.equals("opponentAttack")) { reply = opponentAttack(element); } else if (type.equals("setCurrentPlayer")) { reply = setCurrentPlayer(element); } else if (type.equals("newTurn")) { reply = newTurn(element); } else if (type.equals("setDead")) { reply = setDead(element); } else if (type.equals("gameEnded")) { reply = gameEnded(element); } else if (type.equals("chat")) { reply = chat(element); } else if (type.equals("disconnect")) { reply = disconnect(element); } else if (type.equals("error")) { reply = error(element); } else if (type.equals("chooseFoundingFather")) { reply = chooseFoundingFather(element); } else if (type.equals("deliverGift")) { reply = deliverGift(element); } else if (type.equals("indianDemand")) { reply = indianDemand(element); } else if (type.equals("reconnect")) { reply = reconnect(element); } else if (type.equals("setAI")) { reply = setAI(element); } else if (type.equals("monarchAction")) { reply = monarchAction(element); } else if (type.equals("removeGoods")) { reply = removeGoods(element); } else if (type.equals("lostCityRumour")) { reply = lostCityRumour(element); } else if (type.equals("setStance")) { reply = setStance(element); } else if (type.equals("giveIndependence")) { reply = giveIndependence(element); } else if (type.equals("newConvert")) { reply = newConvert(element); } else if (type.equals("diplomaticTrade")) { reply = diplomaticTrade(element); } else if (type.equals("marketElement")) { reply = marketElement(element); } else { logger.warning("Message is of unsupported type \"" + type + "\"."); } logger.log(Level.FINEST, "Handled message " + type); } else { throw new RuntimeException("Received empty (null) message! - should never happen"); } return reply; } /** * Handles an "reconnect"-message. * * @param element The element (root element in a DOM-parsed XML tree) that * holds all the information. */ private Element reconnect(Element element) { logger.finest("Entered reconnect..."); if (new ShowConfirmDialogSwingTask("reconnect.text", "reconnect.yes", "reconnect.no").confirm()) { logger.finest("User wants to reconnect, do it!"); new ReconnectSwingTask().invokeLater(); } else { // This fairly drastic operation can be done in any thread, // no need to use SwingUtilities. logger.finest("No reconnect, quit."); getFreeColClient().quit(); } return null; } /** * Handles an "update"-message. * * @param updateElement The element (root element in a DOM-parsed XML tree) * that holds all the information. * @return The reply. */ public Element update(Element updateElement) { updateGameObjects(updateElement.getChildNodes()); new RefreshCanvasSwingTask().invokeLater(); return null; } /** * Updates all FreeColGameObjects from the childNodes of the message * @param nodeList The list of nodes from the message */ private void updateGameObjects(NodeList nodeList) { for (int i = 0; i < nodeList.getLength(); i++) { Element element = (Element) nodeList.item(i); FreeColGameObject fcgo = getGame().getFreeColGameObjectSafely(element.getAttribute("ID")); if (fcgo != null) { fcgo.readFromXMLElement(element); } else { logger.warning("Could not find 'FreeColGameObject' with ID: " + element.getAttribute("ID")); } } } /** * Handles a "remove"-message. * * @param removeElement The element (root element in a DOM-parsed XML tree) * that holds all the information. */ private Element remove(Element removeElement) { NodeList nodeList = removeElement.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Element element = (Element) nodeList.item(i); FreeColGameObject fcgo = getGame().getFreeColGameObject(element.getAttribute("ID")); if (fcgo != null) { fcgo.dispose(); } else { logger.warning("Could not find 'FreeColGameObject' with ID: " + element.getAttribute("ID")); } } new RefreshCanvasSwingTask().invokeLater(); return null; } /** * Handles an "opponentMove"-message. * * @param opponentMoveElement The element (root element in a DOM-parsed XML * tree) that holds all the information. */ private Element opponentMove(Element opponentMoveElement) { Map map = getGame().getMap(); Direction direction = Enum.valueOf(Direction.class, opponentMoveElement.getAttribute("direction")); if (!opponentMoveElement.hasAttribute("tile")) { final Unit unit = (Unit) getGame().getFreeColGameObjectSafely(opponentMoveElement.getAttribute("unit")); if (unit == null) { logger.warning("Could not find the 'unit' in 'opponentMove'. Unit ID: " + opponentMoveElement.getAttribute("unit")); return null; } if (unit.getTile() == null) { logger.warning("Ignoring opponentMove, unit " + unit.getId() + " has no tile!"); return null; } final Tile newTile = map.getNeighbourOrNull(direction, unit.getTile()); //Playing the animation before actually moving the unit try { new UnitMoveAnimationCanvasSwingTask(unit, newTile).invokeAndWait(); } catch (InvocationTargetException exception) { logger.warning("UnitMoveAnimationCanvasSwingTask raised " + exception.toString()); } if (getFreeColClient().getMyPlayer().canSee(newTile)) { unit.moveToTile(newTile); } else { unit.dispose(); } } else { String tileID = opponentMoveElement.getAttribute("tile"); Element unitElement = Message.getChildElement(opponentMoveElement, Unit.getXMLElementTagName()); if (unitElement == null) { logger.warning("unitElement == null"); throw new NullPointerException("unitElement == null"); } Unit u = (Unit) getGame().getFreeColGameObjectSafely(unitElement.getAttribute("ID")); if (u == null) { u = new Unit(getGame(), unitElement); } else { u.readFromXMLElement(unitElement); } final Unit unit = u; if (opponentMoveElement.hasAttribute("inUnit")) { String inUnitID = opponentMoveElement.getAttribute("inUnit"); Unit inUnit = (Unit) getGame().getFreeColGameObjectSafely(inUnitID); NodeList units = opponentMoveElement.getElementsByTagName(Unit.getXMLElementTagName()); Element locationElement = null; for (int i = 0; i < units.getLength() && locationElement == null; i++) { Element element = (Element) units.item(i); if (element.getAttribute("ID").equals(inUnitID)) locationElement = element; } if (locationElement != null) { if (inUnit == null) { inUnit = new Unit(getGame(), locationElement); } else { inUnit.readFromXMLElement(locationElement); } } } if (getGame().getFreeColGameObject(tileID) == null) { logger.warning("Could not find tile with id: " + tileID); unit.setLocation(null); // Can't go on without the tile return null; } final Tile newTile = (Tile) getGame().getFreeColGameObject(tileID); if (unit.getLocation() == null) { // Getting the previous tile so we can animate the movement properly final Tile oldTile = map.getNeighbourOrNull(direction.getReverseDirection(), unit.getTile()); unit.setLocation(oldTile); // TODO: This may be not a good idea since this method does a lot of updating } //Playing the animation before actually moving the unit try { new UnitMoveAnimationCanvasSwingTask(unit, newTile).invokeAndWait(); } catch (InvocationTargetException exception) { logger.warning("UnitMoveAnimationCanvasSwingTask raised " + exception.toString()); } unit.setLocation(newTile); } return null; } /** * Handles an "opponentAttack"-message. * * @param opponentAttackElement The element (root element in a DOM-parsed * XML tree) that holds all the information. */ private Element opponentAttack(Element opponentAttackElement) { Unit unit = (Unit) getGame().getFreeColGameObject(opponentAttackElement.getAttribute("unit")); Colony colony = (Colony) getGame().getFreeColGameObjectSafely(opponentAttackElement.getAttribute("colony")); Unit defender = (Unit) getGame().getFreeColGameObjectSafely(opponentAttackElement.getAttribute("defender")); CombatResultType result = Enum.valueOf(CombatResultType.class, opponentAttackElement.getAttribute("result")); int damage = Integer.parseInt(opponentAttackElement.getAttribute("damage")); int plunderGold = Integer.parseInt(opponentAttackElement.getAttribute("plunderGold")); if (opponentAttackElement.hasAttribute("update")) { String updateAttribute = opponentAttackElement.getAttribute("update"); if (updateAttribute.equals("unit")) { Element unitElement = Message.getChildElement(opponentAttackElement, Unit.getXMLElementTagName()); if (unitElement == null) { logger.warning("unitElement == null"); throw new NullPointerException("unitElement == null"); } unit = (Unit) getGame().getFreeColGameObject(unitElement.getAttribute("ID")); if (unit == null) { unit = new Unit(getGame(), unitElement); } else { unit.readFromXMLElement(unitElement); } unit.setLocation(unit.getTile()); if (unit.getTile() == null) { logger.warning("unit.getTile() == null"); throw new NullPointerException("unit.getTile() == null"); } } else if (updateAttribute.equals("defender")) { Element defenderTileElement = Message.getChildElement(opponentAttackElement, Tile .getXMLElementTagName()); if (defenderTileElement != null) { Tile defenderTile = (Tile) getGame().getFreeColGameObject(defenderTileElement.getAttribute("ID")); defenderTile.readFromXMLElement(defenderTileElement); } Element defenderElement = Message.getChildElement(opponentAttackElement, Unit.getXMLElementTagName()); if (defenderElement == null) { logger.warning("defenderElement == null"); throw new NullPointerException("defenderElement == null"); } defender = (Unit) getGame().getFreeColGameObject(defenderElement.getAttribute("ID")); if (defender == null) { defender = new Unit(getGame(), defenderElement); } else { defender.readFromXMLElement(defenderElement); } defender.setLocation(defender.getTile()); if (defender.getTile() == null) { logger.warning("defender.getTile() == null"); throw new NullPointerException(); } } else if (updateAttribute.equals("tile")) { Element tileElement = Message.getChildElement(opponentAttackElement, Tile .getXMLElementTagName()); Tile tile = (Tile) getGame().getFreeColGameObject(tileElement.getAttribute("ID")); if (tile == null) { tile = new Tile(getGame(), tileElement); } else { tile.readFromXMLElement(tileElement); } colony = tile.getColony(); } else { logger.warning("Unknown update: " + updateAttribute); throw new IllegalStateException("Unknown update " + updateAttribute); } } if (unit == null && colony == null) { logger.warning("unit == null && colony == null"); throw new NullPointerException("unit == null && colony == null"); } if (defender == null) { logger.warning("defender == null"); throw new NullPointerException("defender == null"); } if (colony != null) { unit.getGame().getCombatModel().bombard(colony, defender, new CombatResult(result, damage)); } else { unit.getGame().getCombatModel().attack(unit, defender, new CombatResult(result, damage), plunderGold); if (!unit.isDisposed() && (unit.getLocation() == null || !unit.isVisibleTo(getFreeColClient().getMyPlayer()))) { unit.dispose(); } } if (!defender.isDisposed() && (defender.getLocation() == null || !defender.isVisibleTo(getFreeColClient().getMyPlayer()))) { if (result == CombatResultType.DONE_SETTLEMENT && defender.getColony() != null && !defender.getColony().isDisposed()) { defender.getColony().setUnitCount(defender.getColony().getUnitCount()); } defender.dispose(); } new RefreshCanvasSwingTask().invokeLater(); return null; } /** * Handles a "setCurrentPlayer"-message. * * @param setCurrentPlayerElement The element (root element in a DOM-parsed * XML tree) that holds all the information. */ private Element setCurrentPlayer(Element setCurrentPlayerElement) { final Player currentPlayer = (Player) getGame().getFreeColGameObject(setCurrentPlayerElement.getAttribute("player")); logger.finest("About to set currentPlayer to " + currentPlayer.getName()); try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { getFreeColClient().getInGameController().setCurrentPlayer(currentPlayer); getFreeColClient().getActionManager().update(); } }); } catch (InterruptedException e) { // Ignore } catch (InvocationTargetException e) { // Ignore } logger.finest("Succeeded in setting currentPlayer to " + currentPlayer.getName()); new RefreshCanvasSwingTask(true).invokeLater(); return null; } /** * Handles a "newTurn"-message. * * @param newTurnElement The element (root element in a DOM-parsed XML tree) * that holds all the information. */ private Element newTurn(Element newTurnElement) { getGame().newTurn(); new UpdateMenuBarSwingTask().invokeLater(); return null; } /** * Handles a "setDead"-message. * * @param element The element (root element in a DOM-parsed XML tree) that * holds all the information. */ private Element setDead(Element element) { FreeColClient freeColClient = getFreeColClient(); Player player = (Player) getGame().getFreeColGameObject(element.getAttribute("player")); player.setDead(true); if (player == freeColClient.getMyPlayer()) { if (freeColClient.isSingleplayer()) { if (!new ShowConfirmDialogSwingTask("defeatedSingleplayer.text", "defeatedSingleplayer.yes", "defeatedSingleplayer.no").confirm()) { freeColClient.quit(); } else { freeColClient.getFreeColServer().enterRevengeMode(player.getName()); } } else { if (!new ShowConfirmDialogSwingTask("defeated.text", "defeated.yes", "defeated.no").confirm()) { freeColClient.quit(); } } } return null; } /** * Handles a "gameEnded"-message. * * @param element The element (root element in a DOM-parsed XML tree) that * holds all the information. */ private Element gameEnded(Element element) { FreeColClient freeColClient = getFreeColClient(); Player winner = (Player) getGame().getFreeColGameObject(element.getAttribute("winner")); if (winner == freeColClient.getMyPlayer()) { new ShowVictoryPanelSwingTask().invokeLater(); } // else: The client has already received the message of defeat. return null; } /** * Handles a "chat"-message. * * @param element The element (root element in a DOM-parsed XML tree) that * holds all the information. */ private Element chat(Element element) { final Player sender = (Player) getGame().getFreeColGameObjectSafely(element.getAttribute("sender")); final String message = element.getAttribute("message"); final boolean privateChat = Boolean.valueOf(element.getAttribute("privateChat")).booleanValue(); SwingUtilities.invokeLater(new Runnable() { public void run() { getFreeColClient().getCanvas().displayChatMessage(sender, message, privateChat); } }); return null; } /** * Handles an "error"-message. * * @param element The element (root element in a DOM-parsed XML tree) that * holds all the information. */ private Element error(Element element) { new ShowErrorMessageSwingTask(element.hasAttribute("messageID") ? element.getAttribute("messageID") : null, element.getAttribute("message")).show(); return null; } /** * Handles a "setAI"-message. * * @param element The element (root element in a DOM-parsed XML tree) that * holds all the information. */ private Element setAI(Element element) { Player p = (Player) getGame().getFreeColGameObject(element.getAttribute("player")); p.setAI(Boolean.valueOf(element.getAttribute("ai")).booleanValue()); return null; } /** * Handles an "chooseFoundingFather"-request. * * @param element The element (root element in a DOM-parsed XML tree) that * holds all the information. */ private Element chooseFoundingFather(Element element) { final List<FoundingFather> possibleFoundingFathers = new ArrayList<FoundingFather>(); for (FoundingFatherType type : FoundingFatherType.values()) { String id = element.getAttribute(type.toString()); if (id != null) { possibleFoundingFathers.add(FreeCol.getSpecification().getFoundingFather(id)); } } FoundingFather foundingFather = new ShowSelectFoundingFatherSwingTask(possibleFoundingFathers).select(); Element reply = Message.createNewRootElement("chosenFoundingFather"); reply.setAttribute("foundingFather", foundingFather.getId()); getFreeColClient().getMyPlayer().setCurrentFather(foundingFather); return reply; } /** * Handles a "newConvert"-request. * * @param element The element (root element in a DOM-parsed XML * tree) that holds all the information. */ private Element newConvert(Element element) { Tile tile = (Tile) getGame().getFreeColGameObject(element.getAttribute("colony")); Colony colony = tile.getColony(); String nation = colony.getOwner().getNationAsString(); ModelMessage message = new ModelMessage(colony, "model.colony.newConvert", new String[][] { {"%nation%", nation}, {"%colony%", colony.getName()}}, ModelMessage.MessageType.UNIT_ADDED); getFreeColClient().getMyPlayer().addModelMessage(message); return null; } /** * Handles a "diplomaticTrade"-request. Returns either an "accept" * element, if the offer was accepted, or "null", if it was not. * * @param element The element (root element in a DOM-parsed XML * tree) that holds all the information. */ private Element diplomaticTrade(Element element) { Unit unit = (Unit) getGame().getFreeColGameObject(element.getAttribute("unit")); if (unit == null) { throw new IllegalArgumentException("Could not find 'Unit' with specified ID: " + element.getAttribute("unit")); } Direction direction = Enum.valueOf(Direction.class, element.getAttribute("direction")); Tile tile = getGame().getMap().getNeighbourOrNull(direction, unit.getTile()); if (tile == null) { throw new IllegalArgumentException("Could not find 'Tile' in direction " + direction); } Settlement settlement = tile.getSettlement(); if (settlement == null) { throw new IllegalArgumentException("No settlement on 'Tile' " + tile.getId()); } NodeList childElements = element.getChildNodes(); Element childElement = (Element) childElements.item(0); DiplomaticTrade proposal = new DiplomaticTrade(getGame(), childElement); if (proposal.isAccept()) { new ShowInformationMessageSwingTask("negotiationDialog.offerAccepted", new String[][] {{"%nation%", unit.getOwner().getNationAsString()}}).show(); proposal.makeTrade(); } else { DiplomaticTrade agreement = new ShowNegotiationDialogSwingTask(unit, settlement, proposal).select(); if (agreement != null) { Element diplomaticElement = Message.createNewRootElement("diplomaticTrade"); if (agreement.isAccept()) { diplomaticElement.setAttribute("accept", "accept"); } else { diplomaticElement.setAttribute("unit", unit.getId()); diplomaticElement.setAttribute("direction", String.valueOf(direction)); diplomaticElement.appendChild(agreement.toXMLElement(null, diplomaticElement.getOwnerDocument())); } return diplomaticElement; } } return null; } /** * Handles an "deliverGift"-request. * * @param element The element (root element in a DOM-parsed XML tree) that * holds all the information. */ private Element deliverGift(Element element) { Element unitElement = Message.getChildElement(element, Unit.getXMLElementTagName()); Unit unit = (Unit) getGame().getFreeColGameObject(unitElement.getAttribute("ID")); unit.readFromXMLElement(unitElement); Settlement settlement = (Settlement) getGame().getFreeColGameObject(element.getAttribute("settlement")); Goods goods = new Goods(getGame(), Message.getChildElement(element, Goods.getXMLElementTagName())); unit.deliverGift(settlement, goods); return null; } /** * Handles an "indianDemand"-request. * * @param element The element (root element in a DOM-parsed XML tree) that * holds all the information. */ private Element indianDemand(Element element) { Unit unit = (Unit) getGame().getFreeColGameObject(element.getAttribute("unit")); Colony colony = (Colony) getGame().getFreeColGameObject(element.getAttribute("colony")); int gold = 0; Goods goods = null; boolean accepted; Element unitElement = Message.getChildElement(element, Unit.getXMLElementTagName()); if (unitElement != null) { if (unit == null) { unit = new Unit(getGame(), unitElement); } else { unit.readFromXMLElement(unitElement); } } Element goodsElement = Message.getChildElement(element, Goods.getXMLElementTagName()); if (goodsElement == null) { gold = Integer.parseInt(element.getAttribute("gold")); accepted = new ShowConfirmDialogSwingTask("indianDemand.gold.text", "indianDemand.gold.yes", "indianDemand.gold.no", new String[][] { { "%nation%", unit.getOwner().getNationAsString() }, { "%colony%", colony.getName() }, { "%amount%", String.valueOf(gold) } }).confirm(); if (accepted) { colony.getOwner().modifyGold(-gold); } } else { goods = new Goods(getGame(), goodsElement); if (goods.getType() == Goods.FOOD) { accepted = new ShowConfirmDialogSwingTask("indianDemand.food.text", "indianDemand.food.yes", "indianDemand.food.no", new String[][] { { "%nation%", unit.getOwner().getNationAsString() }, { "%colony%", colony.getName() } }).confirm(); } else { accepted = new ShowConfirmDialogSwingTask("indianDemand.other.text", "indianDemand.other.yes", "indianDemand.other.no", new String[][] { { "%nation%", unit.getOwner().getNationAsString() }, { "%colony%", colony.getName() }, { "%amount%", String.valueOf(goods.getAmount()) }, { "%goods%", goods.getName() } }).confirm(); } if (accepted) { colony.getGoodsContainer().removeGoods(goods); } } element.setAttribute("accepted", String.valueOf(accepted)); return element; } /** * Handles a "monarchAction"-request. * * @param element The element (root element in a DOM-parsed XML tree) that * holds all the information. */ private Element monarchAction(Element element) { final FreeColClient freeColClient = getFreeColClient(); Player player = freeColClient.getMyPlayer(); Monarch monarch = player.getMonarch(); final int action = Integer.parseInt(element.getAttribute("action")); Element reply; switch (action) { case Monarch.RAISE_TAX: boolean force = Boolean.parseBoolean(element.getAttribute("force")); final int amount = new Integer(element.getAttribute("amount")).intValue(); if (force) { freeColClient.getMyPlayer().setTax(amount); player.addModelMessage(new ModelMessage(player, "model.monarch.forceTaxRaise", new String[][] { {"%replace%", String.valueOf(amount) }}, ModelMessage.MessageType.WARNING)); reply = null; } else { reply = Message.createNewRootElement("acceptTax"); String[][] replace = new String[][] { { "%replace%", element.getAttribute("amount") }, { "%goods%", element.getAttribute("goods") }, }; if (new ShowMonarchPanelSwingTask(action, replace).confirm()) { freeColClient.getMyPlayer().setTax(amount); reply.setAttribute("accepted", String.valueOf(true)); new UpdateMenuBarSwingTask().invokeLater(); } else { reply.setAttribute("accepted", String.valueOf(false)); } } return reply; case Monarch.ADD_TO_REF: Element additionElement = Message.getChildElement(element, "addition"); NodeList childElements = additionElement.getChildNodes(); ArrayList<AbstractUnit> units = new ArrayList<AbstractUnit>(); for (int index = 0; index < childElements.getLength(); index++) { AbstractUnit unit = new AbstractUnit(); unit.readFromXMLElement((Element) childElements.item(index)); units.add(unit); } monarch.addToREF(units); player.addModelMessage(new ModelMessage(player, "model.monarch.addToREF", new String[][] { { "%addition%", monarch.getName(units) }}, ModelMessage.MessageType.WARNING)); break; case Monarch.DECLARE_WAR: - Player enemy = (Player) getGame().getFreeColGameObject(element.getAttribute("nation")); + Player enemy = (Player) getGame().getFreeColGameObject(element.getAttribute("enemy")); player.setStance(enemy, Stance.WAR); player.addModelMessage(new ModelMessage(player, "model.monarch.declareWar", new String[][] { {"%nation%", enemy.getName()}}, ModelMessage.MessageType.WARNING)); break; case Monarch.SUPPORT_LAND: case Monarch.SUPPORT_SEA: case Monarch.ADD_UNITS: NodeList unitList = element.getChildNodes(); for (int i = 0; i < unitList.getLength(); i++) { Element unitElement = (Element) unitList.item(i); Unit newUnit = (Unit) getGame().getFreeColGameObject(unitElement.getAttribute("ID")); if (newUnit == null) { newUnit = new Unit(getGame(), unitElement); } else { newUnit.readFromXMLElement(unitElement); } player.getEurope().add(newUnit); } SwingUtilities.invokeLater(new Runnable() { public void run() { Canvas canvas = getFreeColClient().getCanvas(); if (!canvas.isShowingSubPanel() && (action == Monarch.ADD_UNITS || !canvas.showMonarchPanel(action, null))) { canvas.showEuropePanel(); } } }); break; case Monarch.OFFER_MERCENARIES: reply = Message.createNewRootElement("hireMercenaries"); Element mercenaryElement = Message.getChildElement(element, "mercenaries"); childElements = mercenaryElement.getChildNodes(); ArrayList<AbstractUnit> mercenaries = new ArrayList<AbstractUnit>(); for (int index = 0; index < childElements.getLength(); index++) { AbstractUnit unit = new AbstractUnit(); unit.readFromXMLElement((Element) childElements.item(index)); mercenaries.add(unit); } if (new ShowMonarchPanelSwingTask(action, new String[][] { { "%gold%", element.getAttribute("price") }, { "%mercenaries%", monarch.getName(mercenaries) } }).confirm()) { int price = new Integer(element.getAttribute("price")).intValue(); freeColClient.getMyPlayer().modifyGold(-price); SwingUtilities.invokeLater(new Runnable() { public void run() { freeColClient.getCanvas().updateGoldLabel(); } }); reply.setAttribute("accepted", String.valueOf(true)); } else { reply.setAttribute("accepted", String.valueOf(false)); } return reply; } return null; } /** * Handles a "setStance"-request. * * @param element The element (root element in a DOM-parsed XML tree) that * holds all the information. */ private Element setStance(Element element) { final FreeColClient freeColClient = getFreeColClient(); Player player = freeColClient.getMyPlayer(); Stance stance = Enum.valueOf(Stance.class, element.getAttribute("stance")); Player first = (Player) getGame().getFreeColGameObject(element.getAttribute("first")); Player second = (Player) getGame().getFreeColGameObject(element.getAttribute("second")); /* * War declared messages are sometimes not shown, because opponentAttack * message arrives before and when setStance message arrives the player * has the new stance. So not check stance is going to change. */ /* * if (first.getStance(second) == stance) { return null; } */ first.setStance(second, stance); if (stance == Stance.WAR) { if (player.equals(second)) { player.addModelMessage(new ModelMessage(first, "model.diplomacy.war.declared", new String[][] { {"%nation%", first.getNationAsString()}}, ModelMessage.MessageType.FOREIGN_DIPLOMACY)); } else { player.addModelMessage(new ModelMessage(first, "model.diplomacy.war.others", new String[][] { { "%attacker%", first.getNationAsString() }, { "%defender%", second.getNationAsString() } }, ModelMessage.MessageType.FOREIGN_DIPLOMACY)); } } return null; } /** * Handles a "giveIndependence"-request. * * @param element The element (root element in a DOM-parsed XML tree) that * holds all the information. */ private Element giveIndependence(Element element) { Player player = (Player) getGame().getFreeColGameObject(element.getAttribute("player")); player.giveIndependence(); return null; } /** * Handles a "marketElement"-request. * * @param element The element (root element in a DOM-parsed XML tree) that * holds all the information. */ private Element marketElement(Element element) { final Player player = getFreeColClient().getMyPlayer(); GoodsType type = FreeCol.getSpecification().getGoodsType(element.getAttribute("type")); int amount = Integer.parseInt(element.getAttribute("amount")); if (amount > 0) { player.getMarket().add(type, amount); } else { player.getMarket().remove(type, -amount); } return null; } /** * Handles a "removeGoods"-request. * * @param element The element (root element in a DOM-parsed XML tree) that * holds all the information. */ private Element removeGoods(Element element) { final FreeColClient freeColClient = getFreeColClient(); NodeList nodeList = element.getChildNodes(); Element goodsElement = (Element) nodeList.item(0); if (goodsElement == null) { // player has no colony or nothing to trade new ShowMonarchPanelSwingTask(Monarch.WAIVE_TAX, null).confirm(); } else { final Goods goods = new Goods(getGame(), goodsElement); final Colony colony = (Colony) goods.getLocation(); colony.removeGoods(goods); // JACOB_FUGGER does not protect against new boycotts freeColClient.getMyPlayer().setArrears(goods); String messageID = goods.getType().getId() + ".destroyed"; if (!Messages.containsKey(messageID)) { if (colony.isLandLocked()) { messageID = "model.monarch.colonyGoodsParty.landLocked"; } else { messageID = "model.monarch.colonyGoodsParty.harbour"; } } colony.getFeatureContainer().addModifier(Modifier .createTeaPartyModifier(getGame().getTurn())); new ShowModelMessageSwingTask(new ModelMessage(colony, ModelMessage.MessageType.WARNING, null, messageID, "%colony%", colony.getName(), "%amount%", String.valueOf(goods.getAmount()), "%goods%", goods.getName())).invokeLater(); } return null; } /** * Handles a "lostCityRumour"-request. * * @param element The element (root element in a DOM-parsed XML tree) that * holds all the information. */ private Element lostCityRumour(Element element) { final FreeColClient freeColClient = getFreeColClient(); final Player player = freeColClient.getMyPlayer(); int type = Integer.parseInt(element.getAttribute("type")); Unit unit = (Unit) getGame().getFreeColGameObject(element.getAttribute("unit")); if (unit == null) { throw new IllegalArgumentException("Unit is null."); } Tile tile = unit.getTile(); tile.setLostCityRumour(false); Unit newUnit; NodeList unitList; ModelMessage m; switch (type) { case LostCityRumour.BURIAL_GROUND: Player indianPlayer = tile.getOwner(); indianPlayer.modifyTension(player, Tension.Level.HATEFUL.getLimit()); m = new ModelMessage(unit, "lostCityRumour.BurialGround", new String[][] { { "%nation%", indianPlayer.getNationAsString() } }, ModelMessage.MessageType.LOST_CITY_RUMOUR); break; case LostCityRumour.EXPEDITION_VANISHES: m = new ModelMessage(unit, "lostCityRumour.ExpeditionVanishes", null, ModelMessage.MessageType.LOST_CITY_RUMOUR); unit.dispose(); break; case LostCityRumour.NOTHING: m = new ModelMessage(unit, "lostCityRumour.Nothing", null, ModelMessage.MessageType.LOST_CITY_RUMOUR); break; case LostCityRumour.LEARN: m = new ModelMessage(unit, "lostCityRumour.SeasonedScout", new String[][] { { "%unit%", unit.getName() } }, ModelMessage.MessageType.LOST_CITY_RUMOUR); unit.setType(FreeCol.getSpecification().getUnitType(element.getAttribute("unitType"))); break; case LostCityRumour.TRIBAL_CHIEF: String amount = element.getAttribute("amount"); m = new ModelMessage(unit, "lostCityRumour.TribalChief", new String[][] { { "%money%", amount } }, ModelMessage.MessageType.LOST_CITY_RUMOUR); player.modifyGold(Integer.parseInt(amount)); break; case LostCityRumour.COLONIST: m = new ModelMessage(unit, ModelMessage.MessageType.LOST_CITY_RUMOUR, null, "lostCityRumour.Colonist"); unitList = element.getChildNodes(); for (int i = 0; i < unitList.getLength(); i++) { Element unitElement = (Element) unitList.item(i); newUnit = (Unit) getGame().getFreeColGameObject(unitElement.getAttribute("ID")); if (newUnit == null) { newUnit = new Unit(getGame(), unitElement); } else { newUnit.readFromXMLElement(unitElement); } tile.add(newUnit); } break; case LostCityRumour.TREASURE: String treasure = element.getAttribute("amount"); m = new ModelMessage(unit, "lostCityRumour.TreasureTrain", new String[][] { { "%money%", treasure } }, ModelMessage.MessageType.LOST_CITY_RUMOUR); unitList = element.getChildNodes(); for (int i = 0; i < unitList.getLength(); i++) { Element unitElement = (Element) unitList.item(i); newUnit = (Unit) getGame().getFreeColGameObject(unitElement.getAttribute("ID")); if (newUnit == null) { newUnit = new Unit(getGame(), unitElement); } else { newUnit.readFromXMLElement(unitElement); } tile.add(newUnit); } break; case LostCityRumour.FOUNTAIN_OF_YOUTH: if (player.getEurope() == null) { m = new ModelMessage(player, "lostCityRumour.FountainOfYouthWithoutEurope", null, ModelMessage.MessageType.LOST_CITY_RUMOUR); } else { m = new ModelMessage(player.getEurope(), "lostCityRumour.FountainOfYouth", null, ModelMessage.MessageType.LOST_CITY_RUMOUR); if (player.hasAbility("model.ability.selectRecruit")) { final int emigrants = Integer.parseInt(element.getAttribute("emigrants")); SwingUtilities.invokeLater(new Runnable() { public void run() { for (int i = 0; i < emigrants; i++) { int slot = getFreeColClient().getCanvas().showEmigrationPanel(); Element selectElement = Message.createNewRootElement("selectFromFountainYouth"); selectElement.setAttribute("slot", Integer.toString(slot)); Element reply = freeColClient.getClient().ask(selectElement); Element unitElement = (Element) reply.getChildNodes().item(0); Unit unit = (Unit) getGame().getFreeColGameObject(unitElement.getAttribute("ID")); if (unit == null) { unit = new Unit(getGame(), unitElement); } else { unit.readFromXMLElement(unitElement); } player.getEurope().add(unit); String newRecruitableStr = reply.getAttribute("newRecruitable"); UnitType newRecruitable = FreeCol.getSpecification().getUnitType(newRecruitableStr); player.getEurope().setRecruitable(slot, newRecruitable); } } }); } else { unitList = element.getChildNodes(); for (int i = 0; i < unitList.getLength(); i++) { Element unitElement = (Element) unitList.item(i); newUnit = (Unit) getGame().getFreeColGameObject(unitElement.getAttribute("ID")); if (newUnit == null) { newUnit = new Unit(getGame(), unitElement); } else { newUnit.readFromXMLElement(unitElement); } player.getEurope().add(newUnit); } } } break; default: throw new IllegalStateException("No such rumour."); } player.addModelMessage(m); return null; } /** * This utility class is the base class for tasks that need to run in the * event dispatch thread. */ abstract static class SwingTask implements Runnable { private static final Logger taskLogger = Logger.getLogger(SwingTask.class.getName()); /** * Run the task and wait for it to complete. * * @return return value from {@link #doWork()}. * @throws InvocationTargetException on unexpected exceptions. */ public Object invokeAndWait() throws InvocationTargetException { verifyNotStarted(); markStarted(true); try { SwingUtilities.invokeAndWait(this); } catch (InterruptedException e) { throw new InvocationTargetException(e); } return _result; } /** * Run the task at some later time. Any exceptions will occur in the * event dispatch thread. The return value will be set, but at present * there is no good way to know if it is valid yet. */ public void invokeLater() { verifyNotStarted(); markStarted(false); SwingUtilities.invokeLater(this); } /** * Mark started and set the synchronous flag. * * @param synchronous The synch/asynch flag. */ private synchronized void markStarted(boolean synchronous) { _synchronous = synchronous; _started = true; } /** * Mark finished. */ private synchronized void markDone() { _started = false; } /** * Throw an exception if the task is started. */ private synchronized void verifyNotStarted() { if (_started) { throw new IllegalStateException("Swing task already started!"); } } /** * Check if the client is waiting. * * @return true if client is waiting for a result. */ private synchronized boolean isSynchronous() { return _synchronous; } /** * Run method, call {@link #doWork()} and save the return value. Also * catch any exceptions. In synchronous mode they will be rethrown to * the original thread, in asynchronous mode they will be logged and * ignored. Nothing is gained by crashing the event dispatch thread. */ public final void run() { try { if (taskLogger.isLoggable(Level.FINEST)) { taskLogger.log(Level.FINEST, "Running Swing task " + getClass().getName() + "..."); } setResult(doWork()); if (taskLogger.isLoggable(Level.FINEST)) { taskLogger.log(Level.FINEST, "Swing task " + getClass().getName() + " returned " + _result); } } catch (RuntimeException e) { taskLogger.log(Level.WARNING, "Swing task " + getClass().getName() + " failed!", e); // Let the exception bubble up if the calling thread is waiting if (isSynchronous()) { throw e; } } finally { markDone(); } } /** * Get the return vale from {@link #doWork()}. * * @return result. */ public synchronized Object getResult() { return _result; } /** * Save result. * * @param r The result. */ private synchronized void setResult(Object r) { _result = r; } /** * Override this method to do the actual work. * * @return result. */ protected abstract Object doWork(); private Object _result; private boolean _synchronous; private boolean _started; } /** * Base class for Swing tasks that need to do a simple update without return * value using the canvas. */ abstract class NoResultCanvasSwingTask extends SwingTask { protected Object doWork() { doWork(getFreeColClient().getCanvas()); return null; } abstract void doWork(Canvas canvas); } /** * This task refreshes the entire canvas. */ class RefreshCanvasSwingTask extends NoResultCanvasSwingTask { /** * Default constructor, simply refresh canvas. */ public RefreshCanvasSwingTask() { this(false); } /** * Constructor. * * @param requestFocus True to request focus after refresh. */ public RefreshCanvasSwingTask(boolean requestFocus) { _requestFocus = requestFocus; } protected void doWork(Canvas canvas) { canvas.refresh(); if (_requestFocus && !canvas.isShowingSubPanel()) { canvas.requestFocusInWindow(); } } private final boolean _requestFocus; } /** * This task plays an animation in the Canvas. */ class AnimateCanvasSwingTask extends NoResultCanvasSwingTask { private final Animation animation; private boolean bufferAnimation; /** * Constructor - animate canvas without frame buffer * @param animation The animation that will be played */ public AnimateCanvasSwingTask(Animation animation) { this(animation, false); } /** * Constructor * @param animation The animation that will be played * @param bufferAnimation If the animation should be buffered or not. */ public AnimateCanvasSwingTask(Animation animation, boolean bufferAnimation) { this.animation = animation; this.bufferAnimation = bufferAnimation; } protected void doWork(Canvas canvas) { animation.animate(bufferAnimation); canvas.refresh(); } } /** * This task plays an unit movement animation in the Canvas. */ class UnitMoveAnimationCanvasSwingTask extends NoResultCanvasSwingTask { private final Unit unit; private final Tile destinationTile; private boolean bufferAnimation; private boolean focus; /** * Constructor - Play the unit movement animation, focusing the unit * @param unit The unit that is moving * @param destinationTile The Tile where the unit will be moving to. */ public UnitMoveAnimationCanvasSwingTask(Unit unit, Tile destinationTile) { this(unit, destinationTile,false, true); } /** * Constructor - Play the unit movement animation, focusing the unit * @param unit The unit that is moving * @param direction The Direction in which the Unit will be moving. */ public UnitMoveAnimationCanvasSwingTask(Unit unit, Direction direction) { this(unit, unit.getGame().getMap().getNeighbourOrNull(direction, unit.getTile()),false, true); } /** * Constructor * @param unit The unit that is moving * @param focusPosition Position to set the focus of the screen. null for no focus * @param bufferAnimation If the animation should be buffered or not. * @param focus If before the animation the screen should focus the unit */ public UnitMoveAnimationCanvasSwingTask(Unit unit, Tile destinationTile, boolean bufferAnimation, boolean focus) { this.unit = unit; this.destinationTile = destinationTile; this.bufferAnimation = bufferAnimation; this.focus = focus; } protected void doWork(Canvas canvas) { if (focus) canvas.getGUI().setFocusImmediately(unit.getTile().getPosition()); Animation animation = new UnitMoveAnimation(canvas, unit, destinationTile); animation.animate(bufferAnimation); canvas.refresh(); } } /** * This task reconnects to the server. */ class ReconnectSwingTask extends SwingTask { protected Object doWork() { getFreeColClient().getConnectController().reconnect(); return null; } } /** * This task updates the menu bar. */ class UpdateMenuBarSwingTask extends NoResultCanvasSwingTask { protected void doWork(Canvas canvas) { canvas.updateJMenuBar(); } } /** * This task shows the victory panel. */ class ShowVictoryPanelSwingTask extends NoResultCanvasSwingTask { protected void doWork(Canvas canvas) { canvas.showVictoryPanel(); } } /** * This class shows a dialog and saves the answer (ok/cancel). */ class ShowConfirmDialogSwingTask extends SwingTask { /** * Constructor. * * @param text The key for the question. * @param okText The key for the OK button. * @param cancelText The key for the Cancel button. */ public ShowConfirmDialogSwingTask(String text, String okText, String cancelText) { this(text, okText, cancelText, null); } /** * Constructor. * * @param text The key for the question. * @param okText The key for the OK button. * @param cancelText The key for the Cancel button. * @param replace The replacement values. */ public ShowConfirmDialogSwingTask(String text, String okText, String cancelText, String[][] replace) { _text = text; _okText = okText; _cancelText = cancelText; _replace = replace; } /** * Show dialog and wait for selection. * * @return true if OK, false if Cancel. */ public boolean confirm() { try { Object result = invokeAndWait(); return ((Boolean) result).booleanValue(); } catch (InvocationTargetException e) { if (e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } else { throw new RuntimeException(e.getCause()); } } } protected Object doWork() { boolean choice = getFreeColClient().getCanvas().showConfirmDialog(_text, _okText, _cancelText, _replace); return Boolean.valueOf(choice); } private String _text; private String _okText; private String _cancelText; private String[][] _replace; } /** * Base class for dialog SwingTasks. */ abstract class ShowMessageSwingTask extends SwingTask { /** * Show dialog and wait for the user to dismiss it. */ public void show() { try { invokeAndWait(); } catch (InvocationTargetException e) { if (e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } else { throw new RuntimeException(e.getCause()); } } } } /** * This class shows a model message. */ class ShowModelMessageSwingTask extends ShowMessageSwingTask { /** * Constructor. * * @param modelMessage The model message to show. */ public ShowModelMessageSwingTask(ModelMessage modelMessage) { _modelMessage = modelMessage; } protected Object doWork() { getFreeColClient().getCanvas().showModelMessage(_modelMessage); return null; } private ModelMessage _modelMessage; } /** * This class shows an informational dialog. */ class ShowInformationMessageSwingTask extends ShowMessageSwingTask { /** * Constructor. * * @param messageId The key for the message. * @param replace The values to replace text with. */ public ShowInformationMessageSwingTask(String messageId, String[][] replace) { _messageId = messageId; _replace = replace; } protected Object doWork() { getFreeColClient().getCanvas().showInformationMessage(_messageId, _replace); return null; } private String _messageId; private String[][] _replace; } /** * This class shows an error dialog. */ class ShowErrorMessageSwingTask extends ShowMessageSwingTask { /** * Constructor. * * @param messageId The i18n-keyname of the error message to display. * @param message An alternative message to display if the resource * specified by <code>messageID</code> is unavailable. */ public ShowErrorMessageSwingTask(String messageId, String message) { _messageId = messageId; _message = message; } protected Object doWork() { getFreeColClient().getCanvas().errorMessage(_messageId, _message); return null; } private String _messageId; private String _message; } /** * This class displays a dialog that lets the player pick a Founding Father. */ abstract class ShowSelectSwingTask extends SwingTask { /** * Show dialog and wait for selection. * * @return selection. */ public int select() { try { Object result = invokeAndWait(); return ((Integer) result).intValue(); } catch (InvocationTargetException e) { if (e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } else { throw new RuntimeException(e.getCause()); } } } } /** * This class displays a dialog that lets the player pick a Founding Father. */ class ShowSelectFoundingFatherSwingTask extends SwingTask { private List<FoundingFather> choices; /** * Constructor. * * @param choices The possible founding fathers. */ public ShowSelectFoundingFatherSwingTask(List<FoundingFather> choices) { this.choices = choices; } protected Object doWork() { return getFreeColClient().getCanvas().showChooseFoundingFatherDialog(choices); } /** * Show dialog and wait for selection. * * @return selection. */ public FoundingFather select() { try { Object result = invokeAndWait(); return (FoundingFather) result; } catch (InvocationTargetException e) { if (e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } else { throw new RuntimeException(e.getCause()); } } } } /** * This class displays a negotiation dialog. */ class ShowNegotiationDialogSwingTask extends SwingTask { /** * Constructor. * * @param unit The unit which init the negotiation. * @param settlement The settlement where the unit has made the proposal * @param proposal The proposal made by unit's owner. */ public ShowNegotiationDialogSwingTask(Unit unit, Settlement settlement, DiplomaticTrade proposal) { this.unit = unit; this.settlement = settlement; this.proposal = proposal; } /** * Show dialog and wait for selection. * * @return selection. */ public DiplomaticTrade select() { try { Object result = invokeAndWait(); return (DiplomaticTrade) result; } catch (InvocationTargetException e) { if (e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } else { throw new RuntimeException(e.getCause()); } } } protected Object doWork() { return getFreeColClient().getCanvas().showNegotiationDialog(unit, settlement, proposal); } private Unit unit; private Settlement settlement; private DiplomaticTrade proposal; } /** * This class shows the monarch panel. */ class ShowMonarchPanelSwingTask extends SwingTask { /** * Constructor. * * @param action The action key. * @param replace The replacement values. */ public ShowMonarchPanelSwingTask(int action, String[][] replace) { _action = action; _replace = replace; } /** * Show dialog and wait for selection. * * @return true if OK, false if Cancel. */ public boolean confirm() { try { Object result = invokeAndWait(); return ((Boolean) result).booleanValue(); } catch (InvocationTargetException e) { if (e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } else { throw new RuntimeException(e.getCause()); } } } protected Object doWork() { boolean choice = getFreeColClient().getCanvas().showMonarchPanel(_action, _replace); return Boolean.valueOf(choice); } private int _action; private String[][] _replace; } }
true
true
private Element monarchAction(Element element) { final FreeColClient freeColClient = getFreeColClient(); Player player = freeColClient.getMyPlayer(); Monarch monarch = player.getMonarch(); final int action = Integer.parseInt(element.getAttribute("action")); Element reply; switch (action) { case Monarch.RAISE_TAX: boolean force = Boolean.parseBoolean(element.getAttribute("force")); final int amount = new Integer(element.getAttribute("amount")).intValue(); if (force) { freeColClient.getMyPlayer().setTax(amount); player.addModelMessage(new ModelMessage(player, "model.monarch.forceTaxRaise", new String[][] { {"%replace%", String.valueOf(amount) }}, ModelMessage.MessageType.WARNING)); reply = null; } else { reply = Message.createNewRootElement("acceptTax"); String[][] replace = new String[][] { { "%replace%", element.getAttribute("amount") }, { "%goods%", element.getAttribute("goods") }, }; if (new ShowMonarchPanelSwingTask(action, replace).confirm()) { freeColClient.getMyPlayer().setTax(amount); reply.setAttribute("accepted", String.valueOf(true)); new UpdateMenuBarSwingTask().invokeLater(); } else { reply.setAttribute("accepted", String.valueOf(false)); } } return reply; case Monarch.ADD_TO_REF: Element additionElement = Message.getChildElement(element, "addition"); NodeList childElements = additionElement.getChildNodes(); ArrayList<AbstractUnit> units = new ArrayList<AbstractUnit>(); for (int index = 0; index < childElements.getLength(); index++) { AbstractUnit unit = new AbstractUnit(); unit.readFromXMLElement((Element) childElements.item(index)); units.add(unit); } monarch.addToREF(units); player.addModelMessage(new ModelMessage(player, "model.monarch.addToREF", new String[][] { { "%addition%", monarch.getName(units) }}, ModelMessage.MessageType.WARNING)); break; case Monarch.DECLARE_WAR: Player enemy = (Player) getGame().getFreeColGameObject(element.getAttribute("nation")); player.setStance(enemy, Stance.WAR); player.addModelMessage(new ModelMessage(player, "model.monarch.declareWar", new String[][] { {"%nation%", enemy.getName()}}, ModelMessage.MessageType.WARNING)); break; case Monarch.SUPPORT_LAND: case Monarch.SUPPORT_SEA: case Monarch.ADD_UNITS: NodeList unitList = element.getChildNodes(); for (int i = 0; i < unitList.getLength(); i++) { Element unitElement = (Element) unitList.item(i); Unit newUnit = (Unit) getGame().getFreeColGameObject(unitElement.getAttribute("ID")); if (newUnit == null) { newUnit = new Unit(getGame(), unitElement); } else { newUnit.readFromXMLElement(unitElement); } player.getEurope().add(newUnit); } SwingUtilities.invokeLater(new Runnable() { public void run() { Canvas canvas = getFreeColClient().getCanvas(); if (!canvas.isShowingSubPanel() && (action == Monarch.ADD_UNITS || !canvas.showMonarchPanel(action, null))) { canvas.showEuropePanel(); } } }); break; case Monarch.OFFER_MERCENARIES: reply = Message.createNewRootElement("hireMercenaries"); Element mercenaryElement = Message.getChildElement(element, "mercenaries"); childElements = mercenaryElement.getChildNodes(); ArrayList<AbstractUnit> mercenaries = new ArrayList<AbstractUnit>(); for (int index = 0; index < childElements.getLength(); index++) { AbstractUnit unit = new AbstractUnit(); unit.readFromXMLElement((Element) childElements.item(index)); mercenaries.add(unit); } if (new ShowMonarchPanelSwingTask(action, new String[][] { { "%gold%", element.getAttribute("price") }, { "%mercenaries%", monarch.getName(mercenaries) } }).confirm()) { int price = new Integer(element.getAttribute("price")).intValue(); freeColClient.getMyPlayer().modifyGold(-price); SwingUtilities.invokeLater(new Runnable() { public void run() { freeColClient.getCanvas().updateGoldLabel(); } }); reply.setAttribute("accepted", String.valueOf(true)); } else { reply.setAttribute("accepted", String.valueOf(false)); } return reply; } return null; }
private Element monarchAction(Element element) { final FreeColClient freeColClient = getFreeColClient(); Player player = freeColClient.getMyPlayer(); Monarch monarch = player.getMonarch(); final int action = Integer.parseInt(element.getAttribute("action")); Element reply; switch (action) { case Monarch.RAISE_TAX: boolean force = Boolean.parseBoolean(element.getAttribute("force")); final int amount = new Integer(element.getAttribute("amount")).intValue(); if (force) { freeColClient.getMyPlayer().setTax(amount); player.addModelMessage(new ModelMessage(player, "model.monarch.forceTaxRaise", new String[][] { {"%replace%", String.valueOf(amount) }}, ModelMessage.MessageType.WARNING)); reply = null; } else { reply = Message.createNewRootElement("acceptTax"); String[][] replace = new String[][] { { "%replace%", element.getAttribute("amount") }, { "%goods%", element.getAttribute("goods") }, }; if (new ShowMonarchPanelSwingTask(action, replace).confirm()) { freeColClient.getMyPlayer().setTax(amount); reply.setAttribute("accepted", String.valueOf(true)); new UpdateMenuBarSwingTask().invokeLater(); } else { reply.setAttribute("accepted", String.valueOf(false)); } } return reply; case Monarch.ADD_TO_REF: Element additionElement = Message.getChildElement(element, "addition"); NodeList childElements = additionElement.getChildNodes(); ArrayList<AbstractUnit> units = new ArrayList<AbstractUnit>(); for (int index = 0; index < childElements.getLength(); index++) { AbstractUnit unit = new AbstractUnit(); unit.readFromXMLElement((Element) childElements.item(index)); units.add(unit); } monarch.addToREF(units); player.addModelMessage(new ModelMessage(player, "model.monarch.addToREF", new String[][] { { "%addition%", monarch.getName(units) }}, ModelMessage.MessageType.WARNING)); break; case Monarch.DECLARE_WAR: Player enemy = (Player) getGame().getFreeColGameObject(element.getAttribute("enemy")); player.setStance(enemy, Stance.WAR); player.addModelMessage(new ModelMessage(player, "model.monarch.declareWar", new String[][] { {"%nation%", enemy.getName()}}, ModelMessage.MessageType.WARNING)); break; case Monarch.SUPPORT_LAND: case Monarch.SUPPORT_SEA: case Monarch.ADD_UNITS: NodeList unitList = element.getChildNodes(); for (int i = 0; i < unitList.getLength(); i++) { Element unitElement = (Element) unitList.item(i); Unit newUnit = (Unit) getGame().getFreeColGameObject(unitElement.getAttribute("ID")); if (newUnit == null) { newUnit = new Unit(getGame(), unitElement); } else { newUnit.readFromXMLElement(unitElement); } player.getEurope().add(newUnit); } SwingUtilities.invokeLater(new Runnable() { public void run() { Canvas canvas = getFreeColClient().getCanvas(); if (!canvas.isShowingSubPanel() && (action == Monarch.ADD_UNITS || !canvas.showMonarchPanel(action, null))) { canvas.showEuropePanel(); } } }); break; case Monarch.OFFER_MERCENARIES: reply = Message.createNewRootElement("hireMercenaries"); Element mercenaryElement = Message.getChildElement(element, "mercenaries"); childElements = mercenaryElement.getChildNodes(); ArrayList<AbstractUnit> mercenaries = new ArrayList<AbstractUnit>(); for (int index = 0; index < childElements.getLength(); index++) { AbstractUnit unit = new AbstractUnit(); unit.readFromXMLElement((Element) childElements.item(index)); mercenaries.add(unit); } if (new ShowMonarchPanelSwingTask(action, new String[][] { { "%gold%", element.getAttribute("price") }, { "%mercenaries%", monarch.getName(mercenaries) } }).confirm()) { int price = new Integer(element.getAttribute("price")).intValue(); freeColClient.getMyPlayer().modifyGold(-price); SwingUtilities.invokeLater(new Runnable() { public void run() { freeColClient.getCanvas().updateGoldLabel(); } }); reply.setAttribute("accepted", String.valueOf(true)); } else { reply.setAttribute("accepted", String.valueOf(false)); } return reply; } return null; }
diff --git a/plugins/org.eclipse.jst.j2ee.core/mofj2ee/org/eclipse/jst/j2ee/internal/model/translator/common/BooleanTranslator.java b/plugins/org.eclipse.jst.j2ee.core/mofj2ee/org/eclipse/jst/j2ee/internal/model/translator/common/BooleanTranslator.java index f460b869a..27885a25e 100644 --- a/plugins/org.eclipse.jst.j2ee.core/mofj2ee/org/eclipse/jst/j2ee/internal/model/translator/common/BooleanTranslator.java +++ b/plugins/org.eclipse.jst.j2ee.core/mofj2ee/org/eclipse/jst/j2ee/internal/model/translator/common/BooleanTranslator.java @@ -1,57 +1,54 @@ /******************************************************************************* * Copyright (c) 2001, 2005 IBM Corporation and others. * 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 * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ /* * Created on Apr 21, 2003 * * To change the template for this generated file go to * Window>Preferences>Java>Code Generation>Code and Comments */ package org.eclipse.jst.j2ee.internal.model.translator.common; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.wst.common.internal.emf.resource.Translator; /** * @author administrator * * To change the template for this generated type comment go to * Window>Preferences>Java>Code Generation>Code and Comments */ public class BooleanTranslator extends Translator { /** * @param domNameAndPath * @param aFeature */ public BooleanTranslator(String domNameAndPath, EStructuralFeature aFeature) { super(domNameAndPath, aFeature, BOOLEAN_LOWERCASE); } /* (non-Javadoc) * @see com.ibm.etools.emf2xml.impl.Translator#convertStringToValue(java.lang.String, org.eclipse.emf.ecore.EObject) */ public Object convertStringToValue(String strValue, EObject owner) { if (strValue == null) return Boolean.FALSE; - if (!Boolean.valueOf(strValue).booleanValue()) { - if (strValue.toUpperCase().equals("1") || strValue.toUpperCase().equals("YES")) { - return Boolean.TRUE; - } - return Boolean.FALSE; - } - return Boolean.FALSE; + else if (strValue.toUpperCase().equals("1") || strValue.toUpperCase().equals("YES")) //$NON-NLS-1$ //$NON-NLS-2$ + return Boolean.TRUE; + else + return Boolean.valueOf(strValue); } }
true
true
public Object convertStringToValue(String strValue, EObject owner) { if (strValue == null) return Boolean.FALSE; if (!Boolean.valueOf(strValue).booleanValue()) { if (strValue.toUpperCase().equals("1") || strValue.toUpperCase().equals("YES")) { return Boolean.TRUE; } return Boolean.FALSE; } return Boolean.FALSE; }
public Object convertStringToValue(String strValue, EObject owner) { if (strValue == null) return Boolean.FALSE; else if (strValue.toUpperCase().equals("1") || strValue.toUpperCase().equals("YES")) //$NON-NLS-1$ //$NON-NLS-2$ return Boolean.TRUE; else return Boolean.valueOf(strValue); }
diff --git a/src/main/java/org/primefaces/component/selectbooleanbutton/SelectBooleanButtonRenderer.java b/src/main/java/org/primefaces/component/selectbooleanbutton/SelectBooleanButtonRenderer.java index 7a39d4afb..1512e009b 100644 --- a/src/main/java/org/primefaces/component/selectbooleanbutton/SelectBooleanButtonRenderer.java +++ b/src/main/java/org/primefaces/component/selectbooleanbutton/SelectBooleanButtonRenderer.java @@ -1,123 +1,123 @@ /* * Copyright 2009-2012 Prime Teknoloji. * * 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.primefaces.component.selectbooleanbutton; import java.io.IOException; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import org.primefaces.renderkit.InputRenderer; import org.primefaces.util.ComponentUtils; import org.primefaces.util.HTML; public class SelectBooleanButtonRenderer extends InputRenderer { @Override public void decode(FacesContext context, UIComponent component) { SelectBooleanButton button = (SelectBooleanButton) component; if(button.isDisabled()) { return; } decodeBehaviors(context, button); String clientId = button.getClientId(context); String submittedValue = (String) context.getExternalContext().getRequestParameterMap().get(clientId + "_input"); if(submittedValue != null && submittedValue.equalsIgnoreCase("on")) { button.setSubmittedValue("true"); } else { button.setSubmittedValue("false"); } } @Override public void encodeEnd(FacesContext context, UIComponent component) throws IOException { SelectBooleanButton button = (SelectBooleanButton) component; encodeMarkup(context, button); encodeScript(context, button); } protected void encodeMarkup(FacesContext context, SelectBooleanButton button) throws IOException { ResponseWriter writer = context.getResponseWriter(); String clientId = button.getClientId(context); boolean checked = Boolean.valueOf(ComponentUtils.getValueToRender(context, button)); boolean disabled = button.isDisabled(); String inputId = clientId + "_input"; String label = checked ? button.getOnLabel() : button.getOffLabel(); String icon = checked ? button.getOnIcon() : button.getOffIcon(); //button - writer.startElement("button", null); + writer.startElement("div", null); writer.writeAttribute("id", clientId, "id"); writer.writeAttribute("type", "button", null); writer.writeAttribute("class", button.resolveStyleClass(checked, disabled), null); if(disabled) writer.writeAttribute("disabled", "disabled", null); if(button.getTitle()!= null) writer.writeAttribute("title", button.getTitle(), null); if(button.getStyle() != null) writer.writeAttribute("style", button.getStyle(), "style"); //input writer.startElement("input", null); writer.writeAttribute("id", inputId, "id"); writer.writeAttribute("name", inputId, null); writer.writeAttribute("type", "checkbox", null); writer.writeAttribute("class", "ui-helper-hidden", null); if(checked) writer.writeAttribute("checked", "checked", null); if(disabled) writer.writeAttribute("disabled", "disabled", null); if(button.getOnchange() != null) writer.writeAttribute("onchange", button.getOnchange(), null); writer.endElement("input"); //icon if(icon != null) { writer.startElement("span", null); writer.writeAttribute("class", HTML.BUTTON_LEFT_ICON_CLASS + " " + icon, null); writer.endElement("span"); } //label writer.startElement("span", null); writer.writeAttribute("class", HTML.BUTTON_TEXT_CLASS, null); writer.writeText(label, "value"); writer.endElement("span"); - writer.endElement("button"); + writer.endElement("div"); } protected void encodeScript(FacesContext context, SelectBooleanButton button) throws IOException { ResponseWriter writer = context.getResponseWriter(); String clientId = button.getClientId(context); startScript(writer, clientId); writer.write("PrimeFaces.cw('SelectBooleanButton','" + button.resolveWidgetVar() + "',{"); writer.write("id:'" + clientId + "'"); writer.write(",onLabel:'" + button.getOnLabel() + "'"); writer.write(",offLabel:'" + button.getOffLabel() + "'"); if(button.getOnIcon() != null) writer.write(",onIcon:'" + button.getOnIcon() + "'"); if(button.getOffIcon() != null) writer.write(",offIcon:'" + button.getOffIcon() + "'"); encodeClientBehaviors(context, button); writer.write("});"); endScript(writer); } }
false
true
protected void encodeMarkup(FacesContext context, SelectBooleanButton button) throws IOException { ResponseWriter writer = context.getResponseWriter(); String clientId = button.getClientId(context); boolean checked = Boolean.valueOf(ComponentUtils.getValueToRender(context, button)); boolean disabled = button.isDisabled(); String inputId = clientId + "_input"; String label = checked ? button.getOnLabel() : button.getOffLabel(); String icon = checked ? button.getOnIcon() : button.getOffIcon(); //button writer.startElement("button", null); writer.writeAttribute("id", clientId, "id"); writer.writeAttribute("type", "button", null); writer.writeAttribute("class", button.resolveStyleClass(checked, disabled), null); if(disabled) writer.writeAttribute("disabled", "disabled", null); if(button.getTitle()!= null) writer.writeAttribute("title", button.getTitle(), null); if(button.getStyle() != null) writer.writeAttribute("style", button.getStyle(), "style"); //input writer.startElement("input", null); writer.writeAttribute("id", inputId, "id"); writer.writeAttribute("name", inputId, null); writer.writeAttribute("type", "checkbox", null); writer.writeAttribute("class", "ui-helper-hidden", null); if(checked) writer.writeAttribute("checked", "checked", null); if(disabled) writer.writeAttribute("disabled", "disabled", null); if(button.getOnchange() != null) writer.writeAttribute("onchange", button.getOnchange(), null); writer.endElement("input"); //icon if(icon != null) { writer.startElement("span", null); writer.writeAttribute("class", HTML.BUTTON_LEFT_ICON_CLASS + " " + icon, null); writer.endElement("span"); } //label writer.startElement("span", null); writer.writeAttribute("class", HTML.BUTTON_TEXT_CLASS, null); writer.writeText(label, "value"); writer.endElement("span"); writer.endElement("button"); }
protected void encodeMarkup(FacesContext context, SelectBooleanButton button) throws IOException { ResponseWriter writer = context.getResponseWriter(); String clientId = button.getClientId(context); boolean checked = Boolean.valueOf(ComponentUtils.getValueToRender(context, button)); boolean disabled = button.isDisabled(); String inputId = clientId + "_input"; String label = checked ? button.getOnLabel() : button.getOffLabel(); String icon = checked ? button.getOnIcon() : button.getOffIcon(); //button writer.startElement("div", null); writer.writeAttribute("id", clientId, "id"); writer.writeAttribute("type", "button", null); writer.writeAttribute("class", button.resolveStyleClass(checked, disabled), null); if(disabled) writer.writeAttribute("disabled", "disabled", null); if(button.getTitle()!= null) writer.writeAttribute("title", button.getTitle(), null); if(button.getStyle() != null) writer.writeAttribute("style", button.getStyle(), "style"); //input writer.startElement("input", null); writer.writeAttribute("id", inputId, "id"); writer.writeAttribute("name", inputId, null); writer.writeAttribute("type", "checkbox", null); writer.writeAttribute("class", "ui-helper-hidden", null); if(checked) writer.writeAttribute("checked", "checked", null); if(disabled) writer.writeAttribute("disabled", "disabled", null); if(button.getOnchange() != null) writer.writeAttribute("onchange", button.getOnchange(), null); writer.endElement("input"); //icon if(icon != null) { writer.startElement("span", null); writer.writeAttribute("class", HTML.BUTTON_LEFT_ICON_CLASS + " " + icon, null); writer.endElement("span"); } //label writer.startElement("span", null); writer.writeAttribute("class", HTML.BUTTON_TEXT_CLASS, null); writer.writeText(label, "value"); writer.endElement("span"); writer.endElement("div"); }
diff --git a/plugin/src/main/java/com/quartercode/quarterbukkit/api/query/ServerModsAPIQuery.java b/plugin/src/main/java/com/quartercode/quarterbukkit/api/query/ServerModsAPIQuery.java index 92bc902..0719391 100644 --- a/plugin/src/main/java/com/quartercode/quarterbukkit/api/query/ServerModsAPIQuery.java +++ b/plugin/src/main/java/com/quartercode/quarterbukkit/api/query/ServerModsAPIQuery.java @@ -1,136 +1,137 @@ /* * This file is part of QuarterBukkit-Plugin. * Copyright (c) 2012 QuarterCode <http://www.quartercode.com/> * * QuarterBukkit-Plugin 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. * * QuarterBukkit-Plugin 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 QuarterBukkit-Plugin. If not, see <http://www.gnu.org/licenses/>. */ package com.quartercode.quarterbukkit.api.query; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import org.json.simple.JSONArray; import org.json.simple.JSONValue; import com.quartercode.quarterbukkit.QuarterBukkit; import com.quartercode.quarterbukkit.api.query.QueryException.QueryExceptionType; /** * A server mods api query can be used to query the official server mods api (https://api.curseforge.com/servermods). * For example, it is used by the {@link Updater} class. */ public class ServerModsAPIQuery { private static final String HOST = "https://api.curseforge.com/servermods/"; private static final String USER_AGENT = "QuarterBukkit/" + ServerModsAPIQuery.class.getSimpleName(); private static final int CONNECTION_TIMEOUT = 5 * 1000; private final String query; /** * Creates a new query whose GET request {@link URL} is made out of the given query string attached to {@code https://api.curseforge.com/servermods/}. * * @param query The query string for the server mods api to process. */ public ServerModsAPIQuery(String query) { this.query = query; } /** * Returns the query string which is used by the {@link #execute()} method to build the request {@link URL}. * * @return The query string for the server mods api to process. */ public String getQuery() { return query; } /** * Executes the stored query and returns the result as a {@link JSONArray}. * The query string ({@link #getQuery()}) is attached to {@code https://api.curseforge.com/servermods/}. * The GET response of that {@link URL} is then parsed to a {@link JSONArray}. * * @return The response of the server mods api. * @throws QueryException Something goes wrong while querying the server mods api. */ public JSONArray execute() throws QueryException { // Build request url using the query URL requestUrl = null; try { requestUrl = new URL(HOST + query); } catch (MalformedURLException e) { throw new QueryException(QueryExceptionType.MALFORMED_URL, this, HOST + query, e); } // Open connection to request url URLConnection request = null; try { request = requestUrl.openConnection(); } catch (IOException e) { throw new QueryException(QueryExceptionType.CANNOT_OPEN_CONNECTION, this, requestUrl.toExternalForm(), e); } // Set connection timeout request.setConnectTimeout(CONNECTION_TIMEOUT); // Set user agent request.addRequestProperty("User-Agent", USER_AGENT); // Set api key (if provided) String apiKey = QuarterBukkit.getPlugin().getConfig().getString("server-mods-api-key"); if (apiKey != null && !apiKey.isEmpty()) { request.addRequestProperty("X-API-Key", apiKey); } // We want to read the results request.setDoOutput(true); // Read first line from the response BufferedReader reader = null; String response = null; try { reader = new BufferedReader(new InputStreamReader(request.getInputStream())); response = reader.readLine(); } catch (IOException e) { if (e.getMessage().contains("HTTP response code: 403")) { throw new QueryException(QueryExceptionType.INVALID_API_KEY, this, requestUrl.toExternalForm(), e); } else { throw new QueryException(QueryExceptionType.CANNOT_READ_RESPONSE, this, requestUrl.toExternalForm(), e); } } finally { - // Can't be null because we return in that case (see the catch block) - try { - reader.close(); - } catch (IOException e) { - throw new QueryException(QueryExceptionType.CANNOT_CLOSE_RESPONSE_STREAM, this, requestUrl.toExternalForm(), e); + if (reader != null) { + try { + reader.close(); + } catch (IOException e) { + throw new QueryException(QueryExceptionType.CANNOT_CLOSE_RESPONSE_STREAM, this, requestUrl.toExternalForm(), e); + } } } // Parse the response Object jsonResponse = JSONValue.parse(response); if (jsonResponse instanceof JSONArray) { return (JSONArray) jsonResponse; } else { throw new QueryException(QueryExceptionType.INVALID_RESPONSE, this, requestUrl.toExternalForm()); } } }
true
true
public JSONArray execute() throws QueryException { // Build request url using the query URL requestUrl = null; try { requestUrl = new URL(HOST + query); } catch (MalformedURLException e) { throw new QueryException(QueryExceptionType.MALFORMED_URL, this, HOST + query, e); } // Open connection to request url URLConnection request = null; try { request = requestUrl.openConnection(); } catch (IOException e) { throw new QueryException(QueryExceptionType.CANNOT_OPEN_CONNECTION, this, requestUrl.toExternalForm(), e); } // Set connection timeout request.setConnectTimeout(CONNECTION_TIMEOUT); // Set user agent request.addRequestProperty("User-Agent", USER_AGENT); // Set api key (if provided) String apiKey = QuarterBukkit.getPlugin().getConfig().getString("server-mods-api-key"); if (apiKey != null && !apiKey.isEmpty()) { request.addRequestProperty("X-API-Key", apiKey); } // We want to read the results request.setDoOutput(true); // Read first line from the response BufferedReader reader = null; String response = null; try { reader = new BufferedReader(new InputStreamReader(request.getInputStream())); response = reader.readLine(); } catch (IOException e) { if (e.getMessage().contains("HTTP response code: 403")) { throw new QueryException(QueryExceptionType.INVALID_API_KEY, this, requestUrl.toExternalForm(), e); } else { throw new QueryException(QueryExceptionType.CANNOT_READ_RESPONSE, this, requestUrl.toExternalForm(), e); } } finally { // Can't be null because we return in that case (see the catch block) try { reader.close(); } catch (IOException e) { throw new QueryException(QueryExceptionType.CANNOT_CLOSE_RESPONSE_STREAM, this, requestUrl.toExternalForm(), e); } } // Parse the response Object jsonResponse = JSONValue.parse(response); if (jsonResponse instanceof JSONArray) { return (JSONArray) jsonResponse; } else { throw new QueryException(QueryExceptionType.INVALID_RESPONSE, this, requestUrl.toExternalForm()); } }
public JSONArray execute() throws QueryException { // Build request url using the query URL requestUrl = null; try { requestUrl = new URL(HOST + query); } catch (MalformedURLException e) { throw new QueryException(QueryExceptionType.MALFORMED_URL, this, HOST + query, e); } // Open connection to request url URLConnection request = null; try { request = requestUrl.openConnection(); } catch (IOException e) { throw new QueryException(QueryExceptionType.CANNOT_OPEN_CONNECTION, this, requestUrl.toExternalForm(), e); } // Set connection timeout request.setConnectTimeout(CONNECTION_TIMEOUT); // Set user agent request.addRequestProperty("User-Agent", USER_AGENT); // Set api key (if provided) String apiKey = QuarterBukkit.getPlugin().getConfig().getString("server-mods-api-key"); if (apiKey != null && !apiKey.isEmpty()) { request.addRequestProperty("X-API-Key", apiKey); } // We want to read the results request.setDoOutput(true); // Read first line from the response BufferedReader reader = null; String response = null; try { reader = new BufferedReader(new InputStreamReader(request.getInputStream())); response = reader.readLine(); } catch (IOException e) { if (e.getMessage().contains("HTTP response code: 403")) { throw new QueryException(QueryExceptionType.INVALID_API_KEY, this, requestUrl.toExternalForm(), e); } else { throw new QueryException(QueryExceptionType.CANNOT_READ_RESPONSE, this, requestUrl.toExternalForm(), e); } } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { throw new QueryException(QueryExceptionType.CANNOT_CLOSE_RESPONSE_STREAM, this, requestUrl.toExternalForm(), e); } } } // Parse the response Object jsonResponse = JSONValue.parse(response); if (jsonResponse instanceof JSONArray) { return (JSONArray) jsonResponse; } else { throw new QueryException(QueryExceptionType.INVALID_RESPONSE, this, requestUrl.toExternalForm()); } }
diff --git a/plugins/org.eclipse.emf.codegen.ecore/src/org/eclipse/emf/codegen/ecore/templates/model/PackageClass.java b/plugins/org.eclipse.emf.codegen.ecore/src/org/eclipse/emf/codegen/ecore/templates/model/PackageClass.java index 379285058..0441f7ac0 100644 --- a/plugins/org.eclipse.emf.codegen.ecore/src/org/eclipse/emf/codegen/ecore/templates/model/PackageClass.java +++ b/plugins/org.eclipse.emf.codegen.ecore/src/org/eclipse/emf/codegen/ecore/templates/model/PackageClass.java @@ -1,2112 +1,2112 @@ package org.eclipse.emf.codegen.ecore.templates.model; import java.util.*; import org.eclipse.emf.ecore.*; import org.eclipse.emf.ecore.util.EcoreUtil; import org.eclipse.emf.codegen.ecore.genmodel.*; import org.eclipse.emf.codegen.ecore.genmodel.impl.Literals; public class PackageClass { protected static String nl; public static synchronized PackageClass create(String lineSeparator) { nl = lineSeparator; PackageClass result = new PackageClass(); nl = null; return result; } public final String NL = nl == null ? (System.getProperties().getProperty("line.separator")) : nl; protected final String TEXT_1 = ""; protected final String TEXT_2 = "/**"; protected final String TEXT_3 = NL + " * "; protected final String TEXT_4 = NL + " * <copyright>" + NL + " * </copyright>"; protected final String TEXT_5 = NL + " *" + NL + " * "; protected final String TEXT_6 = "Id"; protected final String TEXT_7 = NL + " */"; protected final String TEXT_8 = NL + "package "; protected final String TEXT_9 = ";"; protected final String TEXT_10 = NL + "package "; protected final String TEXT_11 = ";"; protected final String TEXT_12 = NL; protected final String TEXT_13 = NL + NL + "/**" + NL + " * <!-- begin-user-doc -->" + NL + " * The <b>Package</b> for the model." + NL + " * It contains accessors for the meta objects to represent" + NL + " * <ul>" + NL + " * <li>each class,</li>" + NL + " * <li>each feature of each class,</li>" + NL + " * <li>each enum,</li>" + NL + " * <li>and each data type</li>" + NL + " * </ul>" + NL + " * <!-- end-user-doc -->"; protected final String TEXT_14 = NL + " * <!-- begin-model-doc -->" + NL + " * "; protected final String TEXT_15 = NL + " * <!-- end-model-doc -->"; protected final String TEXT_16 = NL + " * @see "; protected final String TEXT_17 = NL + " * @model "; protected final String TEXT_18 = NL + " * "; protected final String TEXT_19 = NL + " * @model"; protected final String TEXT_20 = NL + " * @generated" + NL + " */"; protected final String TEXT_21 = NL + NL + "/**" + NL + " * <!-- begin-user-doc -->" + NL + " * An implementation of the model <b>Package</b>." + NL + " * <!-- end-user-doc -->" + NL + " * @generated" + NL + " */"; protected final String TEXT_22 = NL + "public class "; protected final String TEXT_23 = " extends "; protected final String TEXT_24 = " implements "; protected final String TEXT_25 = NL + "public interface "; protected final String TEXT_26 = " extends "; protected final String TEXT_27 = NL + "{"; protected final String TEXT_28 = NL + "\t/**" + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\t"; protected final String TEXT_29 = " copyright = "; protected final String TEXT_30 = ";"; protected final String TEXT_31 = NL; protected final String TEXT_32 = NL + "\t/**" + NL + "\t * The package name." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\t"; protected final String TEXT_33 = " eNAME = \""; protected final String TEXT_34 = "\";"; protected final String TEXT_35 = NL + NL + "\t/**" + NL + "\t * The package namespace URI." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\t"; protected final String TEXT_36 = " eNS_URI = \""; protected final String TEXT_37 = "\";"; protected final String TEXT_38 = NL + NL + "\t/**" + NL + "\t * The package namespace name." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\t"; protected final String TEXT_39 = " eNS_PREFIX = \""; protected final String TEXT_40 = "\";"; protected final String TEXT_41 = NL + NL + "\t/**" + NL + "\t * The package content type ID." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\t"; protected final String TEXT_42 = " eCONTENT_TYPE = \""; protected final String TEXT_43 = "\";"; protected final String TEXT_44 = NL + NL + "\t/**" + NL + "\t * The singleton instance of the package." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\t"; protected final String TEXT_45 = " eINSTANCE = "; protected final String TEXT_46 = ".init();" + NL; protected final String TEXT_47 = NL + "\t/**"; protected final String TEXT_48 = NL + "\t * The meta object id for the '{@link "; protected final String TEXT_49 = " <em>"; protected final String TEXT_50 = "</em>}' class." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @see "; protected final String TEXT_51 = NL + "\t * The meta object id for the '{@link "; protected final String TEXT_52 = " <em>"; protected final String TEXT_53 = "</em>}' class." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @see "; protected final String TEXT_54 = NL + "\t * The meta object id for the '{@link "; protected final String TEXT_55 = " <em>"; protected final String TEXT_56 = "</em>}' enum." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @see "; protected final String TEXT_57 = NL + "\t * The meta object id for the '<em>"; protected final String TEXT_58 = "</em>' data type." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->"; protected final String TEXT_59 = NL + "\t * @see "; protected final String TEXT_60 = NL + "\t * @see "; protected final String TEXT_61 = "#get"; protected final String TEXT_62 = "()" + NL + "\t * @generated" + NL + "\t */" + NL + "\t"; protected final String TEXT_63 = "int "; protected final String TEXT_64 = " = "; protected final String TEXT_65 = ";" + NL; protected final String TEXT_66 = NL + "\t/**" + NL + "\t * The feature id for the '<em><b>"; protected final String TEXT_67 = "</b></em>' "; protected final String TEXT_68 = "." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t * @ordered" + NL + "\t */" + NL + "\t"; protected final String TEXT_69 = "int "; protected final String TEXT_70 = " = "; protected final String TEXT_71 = ";" + NL; protected final String TEXT_72 = NL + "\t/**" + NL + "\t * The number of structural features of the '<em>"; protected final String TEXT_73 = "</em>' class." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t * @ordered" + NL + "\t */" + NL + "\t"; protected final String TEXT_74 = "int "; protected final String TEXT_75 = " = "; protected final String TEXT_76 = ";" + NL; protected final String TEXT_77 = NL + "\t/**" + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tprotected String packageFilename = \""; protected final String TEXT_78 = "\";"; protected final String TEXT_79 = NL; protected final String TEXT_80 = NL + "\t/**" + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tprivate "; protected final String TEXT_81 = " "; protected final String TEXT_82 = " = null;" + NL; protected final String TEXT_83 = NL + "\t/**" + NL + "\t * Creates an instance of the model <b>Package</b>, registered with" + NL + "\t * {@link org.eclipse.emf.ecore.EPackage.Registry EPackage.Registry} by the package" + NL + "\t * package URI value." + NL + "\t * <p>Note: the correct way to create the package is via the static" + NL + "\t * factory method {@link #init init()}, which also performs" + NL + "\t * initialization of the package, or returns the registered package," + NL + "\t * if one already exists." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @see org.eclipse.emf.ecore.EPackage.Registry" + NL + "\t * @see "; protected final String TEXT_84 = "#eNS_URI" + NL + "\t * @see #init()" + NL + "\t * @generated" + NL + "\t */" + NL + "\tprivate "; protected final String TEXT_85 = "()" + NL + "\t{" + NL + "\t\tsuper(eNS_URI, "; protected final String TEXT_86 = ");" + NL + "\t}" + NL + "" + NL + "\t/**" + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tprivate static boolean isInited = false;" + NL + "" + NL + "\t/**" + NL + "\t * Creates, registers, and initializes the <b>Package</b> for this" + NL + "\t * model, and for any others upon which it depends. Simple" + NL + "\t * dependencies are satisfied by calling this method on all" + NL + "\t * dependent packages before doing anything else. This method drives" + NL + "\t * initialization for interdependent packages directly, in parallel" + NL + "\t * with this package, itself." + NL + "\t * <p>Of this package and its interdependencies, all packages which" + NL + "\t * have not yet been registered by their URI values are first created" + NL + "\t * and registered. The packages are then initialized in two steps:" + NL + "\t * meta-model objects for all of the packages are created before any" + NL + "\t * are initialized, since one package's meta-model objects may refer to" + NL + "\t * those of another." + NL + "\t * <p>Invocation of this method will not affect any packages that have" + NL + "\t * already been initialized." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @see #eNS_URI"; protected final String TEXT_87 = NL + "\t * @see #createPackageContents()" + NL + "\t * @see #initializePackageContents()"; protected final String TEXT_88 = NL + "\t * @generated" + NL + "\t */" + NL + "\tpublic static "; protected final String TEXT_89 = " init()" + NL + "\t{" + NL + "\t\tif (isInited) return ("; protected final String TEXT_90 = ")"; protected final String TEXT_91 = ".Registry.INSTANCE.getEPackage("; protected final String TEXT_92 = ".eNS_URI);" + NL + "" + NL + "\t\t// Obtain or create and register package" + NL + "\t\t"; protected final String TEXT_93 = " the"; protected final String TEXT_94 = " = ("; protected final String TEXT_95 = ")("; protected final String TEXT_96 = ".Registry.INSTANCE.getEPackage(eNS_URI) instanceof "; protected final String TEXT_97 = " ? "; protected final String TEXT_98 = ".Registry.INSTANCE.getEPackage(eNS_URI) : new "; protected final String TEXT_99 = "());" + NL + "" + NL + "\t\tisInited = true;" + NL; protected final String TEXT_100 = NL + "\t\t// Initialize simple dependencies"; protected final String TEXT_101 = NL + "\t\t"; protected final String TEXT_102 = ".eINSTANCE.eClass();"; protected final String TEXT_103 = NL; protected final String TEXT_104 = NL + "\t\t// Obtain or create and register interdependencies"; protected final String TEXT_105 = NL + "\t\t"; protected final String TEXT_106 = " "; protected final String TEXT_107 = " = ("; protected final String TEXT_108 = ")("; protected final String TEXT_109 = ".Registry.INSTANCE.getEPackage("; protected final String TEXT_110 = ".eNS_URI) instanceof "; protected final String TEXT_111 = " ? "; protected final String TEXT_112 = ".Registry.INSTANCE.getEPackage("; protected final String TEXT_113 = ".eNS_URI) : "; protected final String TEXT_114 = ".eINSTANCE);"; protected final String TEXT_115 = NL; protected final String TEXT_116 = NL + "\t\t// Load packages"; protected final String TEXT_117 = NL + "\t\tthe"; protected final String TEXT_118 = ".loadPackage();"; protected final String TEXT_119 = NL + "\t\t"; protected final String TEXT_120 = ".loadPackage();"; protected final String TEXT_121 = NL; protected final String TEXT_122 = NL + "\t\t// Create package meta-data objects"; protected final String TEXT_123 = NL + "\t\tthe"; protected final String TEXT_124 = ".createPackageContents();"; protected final String TEXT_125 = NL + "\t\t"; protected final String TEXT_126 = ".createPackageContents();"; protected final String TEXT_127 = NL + NL + "\t\t// Initialize created meta-data"; protected final String TEXT_128 = NL + "\t\tthe"; protected final String TEXT_129 = ".initializePackageContents();"; protected final String TEXT_130 = NL + "\t\t"; protected final String TEXT_131 = ".initializePackageContents();"; protected final String TEXT_132 = NL; protected final String TEXT_133 = NL + "\t\t// Fix loaded packages"; protected final String TEXT_134 = NL + "\t\tthe"; protected final String TEXT_135 = ".fixPackageContents();"; protected final String TEXT_136 = NL + "\t\t"; protected final String TEXT_137 = ".fixPackageContents();"; protected final String TEXT_138 = NL; protected final String TEXT_139 = NL + "\t\t// Register package validator" + NL + "\t\t"; protected final String TEXT_140 = ".Registry.INSTANCE.put" + NL + "\t\t\t(the"; protected final String TEXT_141 = ", " + NL + "\t\t\t new "; protected final String TEXT_142 = ".Descriptor()" + NL + "\t\t\t {" + NL + "\t\t\t\t public "; protected final String TEXT_143 = " getEValidator()" + NL + "\t\t\t\t {" + NL + "\t\t\t\t\t return "; protected final String TEXT_144 = ".INSTANCE;" + NL + "\t\t\t\t }" + NL + "\t\t\t });" + NL; protected final String TEXT_145 = NL + "\t\t// Mark meta-data to indicate it can't be changed" + NL + "\t\tthe"; protected final String TEXT_146 = ".freeze();" + NL; protected final String TEXT_147 = NL + "\t\treturn the"; protected final String TEXT_148 = ";" + NL + "\t}" + NL; protected final String TEXT_149 = NL; protected final String TEXT_150 = NL + "\t/**"; protected final String TEXT_151 = NL + "\t * Returns the meta object for class '{@link "; protected final String TEXT_152 = " <em>"; protected final String TEXT_153 = "</em>}'." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @return the meta object for class '<em>"; protected final String TEXT_154 = "</em>'." + NL + "\t * @see "; protected final String TEXT_155 = NL + "\t * @model "; protected final String TEXT_156 = NL + "\t * "; protected final String TEXT_157 = NL + "\t * @model"; protected final String TEXT_158 = NL + "\t * Returns the meta object for enum '{@link "; protected final String TEXT_159 = " <em>"; protected final String TEXT_160 = "</em>}'." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @return the meta object for enum '<em>"; protected final String TEXT_161 = "</em>'." + NL + "\t * @see "; protected final String TEXT_162 = NL + "\t * Returns the meta object for data type '<em>"; protected final String TEXT_163 = "</em>'."; protected final String TEXT_164 = NL + "\t * Returns the meta object for data type '{@link "; protected final String TEXT_165 = " <em>"; protected final String TEXT_166 = "</em>}'."; protected final String TEXT_167 = NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @return the meta object for data type '<em>"; protected final String TEXT_168 = "</em>'."; protected final String TEXT_169 = NL + "\t * @see "; protected final String TEXT_170 = NL + "\t * @model "; protected final String TEXT_171 = NL + "\t * "; protected final String TEXT_172 = NL + "\t * @model"; protected final String TEXT_173 = NL + "\t * @generated" + NL + "\t */"; protected final String TEXT_174 = NL + "\t/**" + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */"; protected final String TEXT_175 = NL + "\tpublic "; protected final String TEXT_176 = " get"; protected final String TEXT_177 = "()" + NL + "\t{"; protected final String TEXT_178 = NL + "\t\tif ("; protected final String TEXT_179 = " == null)" + NL + "\t\t{" + NL + "\t\t\t"; protected final String TEXT_180 = " = ("; protected final String TEXT_181 = ")"; protected final String TEXT_182 = ".Registry.INSTANCE.getEPackage("; protected final String TEXT_183 = ".eNS_URI).getEClassifiers().get("; protected final String TEXT_184 = ");" + NL + "\t\t}"; protected final String TEXT_185 = NL + "\t\treturn "; protected final String TEXT_186 = ";" + NL + "\t}" + NL; protected final String TEXT_187 = NL + "\t"; protected final String TEXT_188 = " get"; protected final String TEXT_189 = "();" + NL; protected final String TEXT_190 = NL + "\t/**" + NL + "\t * Returns the meta object for the "; protected final String TEXT_191 = " '{@link "; protected final String TEXT_192 = "#"; protected final String TEXT_193 = " <em>"; protected final String TEXT_194 = "</em>}'." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @return the meta object for the "; protected final String TEXT_195 = " '<em>"; protected final String TEXT_196 = "</em>'." + NL + "\t * @see "; protected final String TEXT_197 = "#"; protected final String TEXT_198 = "()"; protected final String TEXT_199 = NL + "\t * @see #get"; protected final String TEXT_200 = "()" + NL + "\t * @generated" + NL + "\t */"; protected final String TEXT_201 = NL + "\t/**" + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */"; protected final String TEXT_202 = NL + "\tpublic "; protected final String TEXT_203 = " get"; protected final String TEXT_204 = "()" + NL + "\t{"; protected final String TEXT_205 = NL + "\t\treturn ("; protected final String TEXT_206 = ")"; protected final String TEXT_207 = ".getEStructuralFeatures().get("; protected final String TEXT_208 = ");"; protected final String TEXT_209 = NL + " return ("; protected final String TEXT_210 = ")get"; protected final String TEXT_211 = "().getEStructuralFeatures().get("; protected final String TEXT_212 = ");"; protected final String TEXT_213 = NL + "\t}"; protected final String TEXT_214 = NL + "\t"; protected final String TEXT_215 = " get"; protected final String TEXT_216 = "();"; protected final String TEXT_217 = NL; protected final String TEXT_218 = NL + "\t/**" + NL + "\t * Returns the factory that creates the instances of the model." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @return the factory that creates the instances of the model." + NL + "\t * @generated" + NL + "\t */"; protected final String TEXT_219 = NL + "\t/**" + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */"; protected final String TEXT_220 = NL + "\tpublic "; protected final String TEXT_221 = " get"; protected final String TEXT_222 = "()" + NL + "\t{" + NL + "\t\treturn ("; protected final String TEXT_223 = ")getEFactoryInstance();" + NL + "\t}"; protected final String TEXT_224 = NL + "\t"; protected final String TEXT_225 = " get"; protected final String TEXT_226 = "();"; protected final String TEXT_227 = NL; protected final String TEXT_228 = NL + "\t/**" + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tprivate boolean isCreated = false;" + NL + "" + NL + "\t/**" + NL + "\t * Creates the meta-model objects for the package. This method is" + NL + "\t * guarded to have no affect on any invocation but its first." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tpublic void createPackageContents()" + NL + "\t{" + NL + "\t\tif (isCreated) return;" + NL + "\t\tisCreated = true;"; protected final String TEXT_229 = NL + NL + "\t\t// Create classes and their features"; protected final String TEXT_230 = NL + "\t\t"; protected final String TEXT_231 = " = create"; protected final String TEXT_232 = "("; protected final String TEXT_233 = ");"; protected final String TEXT_234 = NL + "\t\tcreate"; protected final String TEXT_235 = "("; protected final String TEXT_236 = ", "; protected final String TEXT_237 = ");"; protected final String TEXT_238 = NL; protected final String TEXT_239 = NL + NL + "\t\t// Create enums"; protected final String TEXT_240 = NL + "\t\t"; protected final String TEXT_241 = " = createEEnum("; protected final String TEXT_242 = ");"; protected final String TEXT_243 = NL + NL + "\t\t// Create data types"; protected final String TEXT_244 = NL + "\t\t"; protected final String TEXT_245 = " = createEDataType("; protected final String TEXT_246 = ");"; protected final String TEXT_247 = NL + "\t}" + NL + "" + NL + "\t/**" + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tprivate boolean isInitialized = false;" + NL; protected final String TEXT_248 = NL + "\t/**" + NL + "\t * Complete the initialization of the package and its meta-model. This" + NL + "\t * method is guarded to have no affect on any invocation but its first." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tpublic void initializePackageContents()" + NL + "\t{" + NL + "\t\tif (isInitialized) return;" + NL + "\t\tisInitialized = true;" + NL + "" + NL + "\t\t// Initialize package" + NL + "\t\tsetName(eNAME);" + NL + "\t\tsetNsPrefix(eNS_PREFIX);" + NL + "\t\tsetNsURI(eNS_URI);"; protected final String TEXT_249 = NL + NL + "\t\t// Obtain other dependent packages"; protected final String TEXT_250 = NL + "\t\t"; protected final String TEXT_251 = " "; protected final String TEXT_252 = " = ("; protected final String TEXT_253 = ")"; protected final String TEXT_254 = ".Registry.INSTANCE.getEPackage("; protected final String TEXT_255 = ".eNS_URI);"; protected final String TEXT_256 = NL + NL + "\t\t// Add subpackages"; protected final String TEXT_257 = NL + "\t\tgetESubpackages().add("; protected final String TEXT_258 = ");"; protected final String TEXT_259 = NL + NL + "\t\t// Create type parameters"; protected final String TEXT_260 = NL + "\t\t"; protected final String TEXT_261 = " "; protected final String TEXT_262 = "_"; protected final String TEXT_263 = " = addETypeParameter("; protected final String TEXT_264 = ", \""; protected final String TEXT_265 = "\");"; protected final String TEXT_266 = NL + "\t\taddETypeParameter("; protected final String TEXT_267 = ", \""; protected final String TEXT_268 = "\");"; protected final String TEXT_269 = NL + NL + "\t\t// Set bounds for type parameters"; protected final String TEXT_270 = NL + "\t\t"; protected final String TEXT_271 = "g"; protected final String TEXT_272 = " = createEGenericType("; protected final String TEXT_273 = ");"; protected final String TEXT_274 = NL + "\t\tg"; protected final String TEXT_275 = "."; protected final String TEXT_276 = "(g"; protected final String TEXT_277 = ");"; protected final String TEXT_278 = NL + "\t\t"; protected final String TEXT_279 = "_"; protected final String TEXT_280 = ".getEBounds().add(g1);"; protected final String TEXT_281 = NL + NL + "\t\t// Add supertypes to classes"; protected final String TEXT_282 = NL + "\t\t"; protected final String TEXT_283 = ".getESuperTypes().add("; protected final String TEXT_284 = ".get"; protected final String TEXT_285 = "());"; protected final String TEXT_286 = NL + "\t\t"; protected final String TEXT_287 = "g"; protected final String TEXT_288 = " = createEGenericType("; protected final String TEXT_289 = ");"; protected final String TEXT_290 = NL + "\t\tg"; protected final String TEXT_291 = "."; protected final String TEXT_292 = "(g"; protected final String TEXT_293 = ");"; protected final String TEXT_294 = NL + "\t\t"; protected final String TEXT_295 = ".getEGenericSuperTypes().add(g1);"; protected final String TEXT_296 = NL + NL + "\t\t// Initialize classes and features; add operations and parameters"; protected final String TEXT_297 = NL + "\t\tinitEClass("; protected final String TEXT_298 = ", "; protected final String TEXT_299 = "null"; protected final String TEXT_300 = ".class"; protected final String TEXT_301 = ", \""; protected final String TEXT_302 = "\", "; protected final String TEXT_303 = ", "; protected final String TEXT_304 = ", "; protected final String TEXT_305 = ", \""; protected final String TEXT_306 = "\""; protected final String TEXT_307 = ");"; protected final String TEXT_308 = NL + "\t\t"; protected final String TEXT_309 = "g"; protected final String TEXT_310 = " = createEGenericType("; protected final String TEXT_311 = ");"; protected final String TEXT_312 = NL + "\t\tg"; protected final String TEXT_313 = "."; protected final String TEXT_314 = "(g"; protected final String TEXT_315 = ");"; protected final String TEXT_316 = NL + "\t\tinitEReference(get"; protected final String TEXT_317 = "(), "; protected final String TEXT_318 = "g1"; protected final String TEXT_319 = ".get"; protected final String TEXT_320 = "()"; protected final String TEXT_321 = ", "; protected final String TEXT_322 = ", \""; protected final String TEXT_323 = "\", "; protected final String TEXT_324 = ", "; protected final String TEXT_325 = ", "; protected final String TEXT_326 = ", "; protected final String TEXT_327 = ", "; protected final String TEXT_328 = ", "; protected final String TEXT_329 = ", "; protected final String TEXT_330 = ", "; protected final String TEXT_331 = ", "; protected final String TEXT_332 = ", "; protected final String TEXT_333 = ", "; protected final String TEXT_334 = ", "; protected final String TEXT_335 = ", "; protected final String TEXT_336 = ");"; protected final String TEXT_337 = NL + "\t\tget"; protected final String TEXT_338 = "().getEKeys().add("; protected final String TEXT_339 = ".get"; protected final String TEXT_340 = "());"; protected final String TEXT_341 = NL + "\t\tinitEAttribute(get"; protected final String TEXT_342 = "(), "; protected final String TEXT_343 = "g1"; protected final String TEXT_344 = ".get"; protected final String TEXT_345 = "()"; protected final String TEXT_346 = ", \""; protected final String TEXT_347 = "\", "; protected final String TEXT_348 = ", "; protected final String TEXT_349 = ", "; protected final String TEXT_350 = ", "; protected final String TEXT_351 = ", "; protected final String TEXT_352 = ", "; protected final String TEXT_353 = ", "; protected final String TEXT_354 = ", "; protected final String TEXT_355 = ", "; protected final String TEXT_356 = ", "; protected final String TEXT_357 = ", "; protected final String TEXT_358 = ", "; protected final String TEXT_359 = ");"; protected final String TEXT_360 = NL; protected final String TEXT_361 = NL + "\t\t"; protected final String TEXT_362 = "addEOperation("; protected final String TEXT_363 = ", "; protected final String TEXT_364 = "null"; protected final String TEXT_365 = ".get"; protected final String TEXT_366 = "()"; protected final String TEXT_367 = ", \""; protected final String TEXT_368 = "\", "; protected final String TEXT_369 = ", "; protected final String TEXT_370 = ", "; protected final String TEXT_371 = ", "; protected final String TEXT_372 = ");"; protected final String TEXT_373 = NL + "\t\t"; protected final String TEXT_374 = "addEOperation("; protected final String TEXT_375 = ", "; protected final String TEXT_376 = ".get"; protected final String TEXT_377 = "(), \""; protected final String TEXT_378 = "\", "; protected final String TEXT_379 = ", "; protected final String TEXT_380 = ", "; protected final String TEXT_381 = ", "; protected final String TEXT_382 = ");"; protected final String TEXT_383 = NL + "\t\t"; protected final String TEXT_384 = "addEOperation("; protected final String TEXT_385 = ", "; protected final String TEXT_386 = ".get"; protected final String TEXT_387 = "(), \""; protected final String TEXT_388 = "\", "; protected final String TEXT_389 = ", "; protected final String TEXT_390 = ");"; protected final String TEXT_391 = NL + "\t\t"; protected final String TEXT_392 = "addEOperation("; protected final String TEXT_393 = ", null, \""; protected final String TEXT_394 = "\");"; protected final String TEXT_395 = NL + "\t\t"; protected final String TEXT_396 = "addETypeParameter(op, \""; protected final String TEXT_397 = "\");"; protected final String TEXT_398 = NL + "\t\t"; protected final String TEXT_399 = "g"; protected final String TEXT_400 = " = createEGenericType("; protected final String TEXT_401 = ");"; protected final String TEXT_402 = NL + "\t\tg"; protected final String TEXT_403 = "."; protected final String TEXT_404 = "(g"; protected final String TEXT_405 = ");"; protected final String TEXT_406 = NL + "\t\tt"; protected final String TEXT_407 = ".getEBounds().add(g1);"; protected final String TEXT_408 = NL + "\t\t"; protected final String TEXT_409 = "g"; protected final String TEXT_410 = " = createEGenericType("; protected final String TEXT_411 = ");"; protected final String TEXT_412 = NL + "\t\tg"; protected final String TEXT_413 = "."; protected final String TEXT_414 = "(g"; protected final String TEXT_415 = ");"; protected final String TEXT_416 = NL + "\t\taddEParameter(op, "; protected final String TEXT_417 = "g1"; protected final String TEXT_418 = ".get"; protected final String TEXT_419 = "()"; protected final String TEXT_420 = ", \""; protected final String TEXT_421 = "\", "; protected final String TEXT_422 = ", "; protected final String TEXT_423 = ", "; protected final String TEXT_424 = ", "; protected final String TEXT_425 = ");"; protected final String TEXT_426 = NL + "\t\taddEParameter(op, "; protected final String TEXT_427 = "g1"; protected final String TEXT_428 = ".get"; protected final String TEXT_429 = "()"; protected final String TEXT_430 = ", \""; protected final String TEXT_431 = "\", "; protected final String TEXT_432 = ", "; protected final String TEXT_433 = ", "; protected final String TEXT_434 = ", "; protected final String TEXT_435 = ");"; protected final String TEXT_436 = NL + "\t\taddEParameter(op, "; protected final String TEXT_437 = "g1"; protected final String TEXT_438 = ".get"; protected final String TEXT_439 = "()"; protected final String TEXT_440 = ", \""; protected final String TEXT_441 = "\", "; protected final String TEXT_442 = ", "; protected final String TEXT_443 = ");"; protected final String TEXT_444 = NL + "\t\t"; protected final String TEXT_445 = "g"; protected final String TEXT_446 = " = createEGenericType("; protected final String TEXT_447 = ");"; protected final String TEXT_448 = NL + "\t\tg"; protected final String TEXT_449 = "."; protected final String TEXT_450 = "(g"; protected final String TEXT_451 = ");"; protected final String TEXT_452 = NL + "\t\taddEException(op, g"; protected final String TEXT_453 = ");"; protected final String TEXT_454 = NL + "\t\taddEException(op, "; protected final String TEXT_455 = ".get"; protected final String TEXT_456 = "());"; protected final String TEXT_457 = NL + "\t\t"; protected final String TEXT_458 = "g"; protected final String TEXT_459 = " = createEGenericType("; protected final String TEXT_460 = ");"; protected final String TEXT_461 = NL + "\t\tg"; protected final String TEXT_462 = "."; protected final String TEXT_463 = "(g"; protected final String TEXT_464 = ");"; protected final String TEXT_465 = NL + "\t\tinitEOperation(op, g1);"; protected final String TEXT_466 = NL; protected final String TEXT_467 = NL + NL + "\t\t// Initialize enums and add enum literals"; protected final String TEXT_468 = NL + "\t\tinitEEnum("; protected final String TEXT_469 = ", "; protected final String TEXT_470 = ".class, \""; protected final String TEXT_471 = "\");"; protected final String TEXT_472 = NL + "\t\taddEEnumLiteral("; protected final String TEXT_473 = ", "; protected final String TEXT_474 = "."; protected final String TEXT_475 = ");"; protected final String TEXT_476 = NL; protected final String TEXT_477 = NL + NL + "\t\t// Initialize data types"; protected final String TEXT_478 = NL + "\t\tinitEDataType("; protected final String TEXT_479 = ", "; protected final String TEXT_480 = ".class, \""; protected final String TEXT_481 = "\", "; protected final String TEXT_482 = ", "; protected final String TEXT_483 = ", \""; protected final String TEXT_484 = "\""; protected final String TEXT_485 = ");"; protected final String TEXT_486 = NL + NL + "\t\t// Create resource" + NL + "\t\tcreateResource(eNS_URI);"; protected final String TEXT_487 = NL + NL + "\t\t// Create annotations"; protected final String TEXT_488 = NL + "\t\t// "; protected final String TEXT_489 = NL + "\t\tcreate"; protected final String TEXT_490 = "Annotations();"; protected final String TEXT_491 = NL + "\t}" + NL; protected final String TEXT_492 = NL + "\t/**" + NL + "\t * Initializes the annotations for <b>"; protected final String TEXT_493 = "</b>." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tprotected void create"; protected final String TEXT_494 = "Annotations()" + NL + "\t{" + NL + "\t\tString source = "; protected final String TEXT_495 = "null;"; protected final String TEXT_496 = "\""; protected final String TEXT_497 = "\";"; protected final String TEXT_498 = "\t"; protected final String TEXT_499 = "\t" + NL + "\t\taddAnnotation" + NL + "\t\t ("; protected final String TEXT_500 = ", " + NL + "\t\t source, " + NL + "\t\t new String[] " + NL + "\t\t {"; protected final String TEXT_501 = NL + "\t\t\t "; protected final String TEXT_502 = ", "; protected final String TEXT_503 = NL + "\t\t });"; protected final String TEXT_504 = NL + "\t\taddAnnotation" + NL + "\t\t ("; protected final String TEXT_505 = ", " + NL + "\t\t "; protected final String TEXT_506 = "," + NL + "\t\t "; protected final String TEXT_507 = "null,"; protected final String TEXT_508 = "\""; protected final String TEXT_509 = "\","; protected final String TEXT_510 = NL + "\t\t new String[] " + NL + "\t\t {"; protected final String TEXT_511 = NL + "\t\t "; protected final String TEXT_512 = ", "; protected final String TEXT_513 = NL + "\t\t });"; protected final String TEXT_514 = NL + "\t\taddAnnotation" + NL + "\t\t ("; protected final String TEXT_515 = ", " + NL + "\t\t "; protected final String TEXT_516 = "," + NL + "\t\t "; protected final String TEXT_517 = "null,"; protected final String TEXT_518 = "\""; protected final String TEXT_519 = "\","; protected final String TEXT_520 = NL + "\t\t new String[] " + NL + "\t\t {"; protected final String TEXT_521 = NL + "\t\t "; protected final String TEXT_522 = ", "; protected final String TEXT_523 = NL + "\t\t });"; protected final String TEXT_524 = NL + "\t}" + NL; protected final String TEXT_525 = NL + "\t/**" + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tprivate boolean isLoaded = false;" + NL + "" + NL + "\t/**" + NL + "\t * Laods the package and any sub-packages from their serialized form." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tpublic void loadPackage()" + NL + "\t{" + NL + "\t\tif (isLoaded) return;" + NL + "\t\tisLoaded = true;" + NL + "" + NL + "\t\t"; protected final String TEXT_526 = " url = getClass().getResource(packageFilename);" + NL + "\t\tif (url == null)" + NL + "\t\t{" + NL + "\t\t\tthrow new RuntimeException(\"Missing serialized package: \" + packageFilename);"; protected final String TEXT_527 = NL + "\t\t}" + NL + "\t\t"; protected final String TEXT_528 = " uri = "; protected final String TEXT_529 = ".createURI(url.toString());" + NL + "\t\t"; protected final String TEXT_530 = " resource = new "; protected final String TEXT_531 = "().createResource(uri);" + NL + "\t\ttry" + NL + "\t\t{" + NL + "\t\t\tresource.load(null);" + NL + "\t\t}" + NL + "\t\tcatch ("; protected final String TEXT_532 = " exception)" + NL + "\t\t{" + NL + "\t\t\tthrow new "; protected final String TEXT_533 = "(exception);" + NL + "\t\t}" + NL + "\t\tinitializeFromLoadedEPackage(this, ("; protected final String TEXT_534 = ")resource.getContents().get(0));" + NL + "\t\tcreateResource(eNS_URI);" + NL + "\t}" + NL; protected final String TEXT_535 = NL + NL + "\t/**" + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tprivate boolean isFixed = false;" + NL + "" + NL + "\t/**" + NL + "\t * Fixes up the loaded package, to make it appear as if it had been programmatically built." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tpublic void fixPackageContents()" + NL + "\t{" + NL + "\t\tif (isFixed) return;" + NL + "\t\tisFixed = true;" + NL + "\t\tfixEClassifiers();" + NL + "\t}" + NL + "" + NL + "\t/**" + NL + "\t * Sets the instance class on the given classifier." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */"; protected final String TEXT_536 = NL + "\t@Override"; protected final String TEXT_537 = NL + "\tprotected void fixInstanceClass("; protected final String TEXT_538 = " eClassifier)" + NL + "\t{" + NL + "\t\tif (eClassifier.getInstanceClassName() == null)" + NL + "\t\t{"; protected final String TEXT_539 = NL + "\t\t\teClassifier.setInstanceClassName(\""; protected final String TEXT_540 = ".\" + eClassifier.getName());"; protected final String TEXT_541 = NL + "\t\t\tsetGeneratedClassName(eClassifier);"; protected final String TEXT_542 = NL + "\t\t\tswitch (eClassifier.getClassifierID())" + NL + "\t\t\t{"; protected final String TEXT_543 = NL + "\t\t\t\tcase "; protected final String TEXT_544 = ":"; protected final String TEXT_545 = NL + "\t\t\t\t{" + NL + "\t\t\t\t\tbreak;" + NL + "\t\t\t\t}" + NL + "\t\t\t\tdefault:" + NL + "\t\t\t\t{" + NL + "\t\t\t\t\teClassifier.setInstanceClassName(\""; protected final String TEXT_546 = ".\" + eClassifier.getName());"; protected final String TEXT_547 = NL + "\t\t\t\t\tsetGeneratedClassName(eClassifier);" + NL + "\t\t\t\t\tbreak;" + NL + "\t\t\t\t}" + NL + "\t\t\t}"; protected final String TEXT_548 = NL + "\t\t}" + NL + "\t}" + NL; protected final String TEXT_549 = NL + "\t/**" + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tprotected "; protected final String TEXT_550 = " addEOperation("; protected final String TEXT_551 = " owner, "; protected final String TEXT_552 = " type, String name, int lowerBound, int upperBound, boolean isUnique, boolean isOrdered)" + NL + "\t{" + NL + "\t\t"; protected final String TEXT_553 = " o = addEOperation(owner, type, name, lowerBound, upperBound);" + NL + "\t\to.setUnique(isUnique);" + NL + "\t\to.setOrdered(isOrdered);" + NL + "\t\treturn o;" + NL + "\t}" + NL + "\t"; protected final String TEXT_554 = NL + "\t/**" + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tprotected "; protected final String TEXT_555 = " addEParameter("; protected final String TEXT_556 = " owner, "; protected final String TEXT_557 = " type, String name, int lowerBound, int upperBound, boolean isUnique, boolean isOrdered)" + NL + "\t{" + NL + "\t\t"; protected final String TEXT_558 = " p = ecoreFactory.createEParameter();" + NL + "\t\tp.setEType(type);" + NL + "\t\tp.setName(name);" + NL + "\t\tp.setLowerBound(lowerBound);" + NL + "\t\tp.setUpperBound(upperBound);" + NL + "\t\tp.setUnique(isUnique);" + NL + "\t\tp.setOrdered(isOrdered);" + NL + "\t\towner.getEParameters().add(p);" + NL + "\t\treturn p;" + NL + "\t}" + NL + "\t"; protected final String TEXT_559 = NL + "\t/**" + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * Defines literals for the meta objects that represent" + NL + "\t * <ul>" + NL + "\t * <li>each class,</li>" + NL + "\t * <li>each feature of each class,</li>" + NL + "\t * <li>each enum,</li>" + NL + "\t * <li>and each data type</li>" + NL + "\t * </ul>" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\t"; protected final String TEXT_560 = "public "; protected final String TEXT_561 = "interface Literals" + NL + "\t{"; protected final String TEXT_562 = NL + "\t\t/**"; protected final String TEXT_563 = NL + "\t\t * The meta object literal for the '{@link "; protected final String TEXT_564 = " <em>"; protected final String TEXT_565 = "</em>}' class." + NL + "\t\t * <!-- begin-user-doc -->" + NL + "\t\t * <!-- end-user-doc -->" + NL + "\t\t * @see "; protected final String TEXT_566 = NL + "\t\t * The meta object literal for the '{@link "; protected final String TEXT_567 = " <em>"; protected final String TEXT_568 = "</em>}' class." + NL + "\t\t * <!-- begin-user-doc -->" + NL + "\t\t * <!-- end-user-doc -->" + NL + "\t\t * @see "; protected final String TEXT_569 = NL + "\t\t * The meta object literal for the '{@link "; protected final String TEXT_570 = " <em>"; protected final String TEXT_571 = "</em>}' enum." + NL + "\t\t * <!-- begin-user-doc -->" + NL + "\t\t * <!-- end-user-doc -->" + NL + "\t\t * @see "; protected final String TEXT_572 = NL + "\t\t * The meta object literal for the '<em>"; protected final String TEXT_573 = "</em>' data type." + NL + "\t\t * <!-- begin-user-doc -->" + NL + "\t\t * <!-- end-user-doc -->"; protected final String TEXT_574 = NL + "\t\t * @see "; protected final String TEXT_575 = NL + "\t\t * @see "; protected final String TEXT_576 = "#get"; protected final String TEXT_577 = "()" + NL + "\t\t * @generated" + NL + "\t\t */" + NL + "\t\t"; protected final String TEXT_578 = " "; protected final String TEXT_579 = " = eINSTANCE.get"; protected final String TEXT_580 = "();" + NL; protected final String TEXT_581 = NL + "\t\t/**" + NL + "\t\t * The meta object literal for the '<em><b>"; protected final String TEXT_582 = "</b></em>' "; protected final String TEXT_583 = " feature." + NL + "\t\t * <!-- begin-user-doc -->" + NL + "\t\t * <!-- end-user-doc -->" + NL + "\t\t * @generated" + NL + "\t\t */" + NL + "\t\t"; protected final String TEXT_584 = " "; protected final String TEXT_585 = " = eINSTANCE.get"; protected final String TEXT_586 = "();" + NL; protected final String TEXT_587 = NL + "\t}" + NL; protected final String TEXT_588 = NL + "} //"; protected final String TEXT_589 = NL; public String generate(Object argument) { final StringBuffer stringBuffer = new StringBuffer(); /** * <copyright> * * Copyright (c) 2002-2006 IBM Corporation and others. * 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 * * Contributors: * IBM - Initial API and implementation * * </copyright> */ final GenPackage genPackage = (GenPackage)((Object[])argument)[0]; final GenModel genModel=genPackage.getGenModel(); boolean isInterface = Boolean.TRUE.equals(((Object[])argument)[1]); boolean isImplementation = Boolean.TRUE.equals(((Object[])argument)[2]); String publicStaticFinalFlag = isImplementation ? "public static final " : ""; boolean needsAddEOperation = false; boolean needsAddEParameter = false; stringBuffer.append(TEXT_1); stringBuffer.append(TEXT_2); {GenBase copyrightHolder = argument instanceof GenBase ? (GenBase)argument : argument instanceof Object[] && ((Object[])argument)[0] instanceof GenBase ? (GenBase)((Object[])argument)[0] : null; if (copyrightHolder != null && copyrightHolder.hasCopyright()) { stringBuffer.append(TEXT_3); stringBuffer.append(copyrightHolder.getCopyright(copyrightHolder.getGenModel().getIndentation(stringBuffer))); } else { stringBuffer.append(TEXT_4); }} stringBuffer.append(TEXT_5); stringBuffer.append("$"); stringBuffer.append(TEXT_6); stringBuffer.append("$"); stringBuffer.append(TEXT_7); if (isImplementation && !genModel.isSuppressInterfaces()) { stringBuffer.append(TEXT_8); stringBuffer.append(genPackage.getClassPackageName()); stringBuffer.append(TEXT_9); } else { stringBuffer.append(TEXT_10); stringBuffer.append(genPackage.getReflectionPackageName()); stringBuffer.append(TEXT_11); } stringBuffer.append(TEXT_12); genModel.markImportLocation(stringBuffer, genPackage); if (isImplementation) { genModel.addPseudoImport("org.eclipse.emf.ecore.EPackage.Registry"); genModel.addPseudoImport("org.eclipse.emf.ecore.EPackage.Descriptor"); if (genPackage.isLiteralsInterface()) { genModel.addPseudoImport(genPackage.getQualifiedPackageInterfaceName() + ".Literals"); } for (GenClassifier genClassifier : genPackage.getOrderedGenClassifiers()) genModel.addPseudoImport(genPackage.getQualifiedPackageInterfaceName() + "." + genPackage.getClassifierID(genClassifier)); } if (isInterface) { stringBuffer.append(TEXT_13); if (genPackage.hasDocumentation()) { stringBuffer.append(TEXT_14); stringBuffer.append(genPackage.getDocumentation(genModel.getIndentation(stringBuffer))); stringBuffer.append(TEXT_15); } stringBuffer.append(TEXT_16); stringBuffer.append(genPackage.getQualifiedFactoryInterfaceName()); if (!genModel.isSuppressEMFModelTags()) { boolean first = true; for (StringTokenizer stringTokenizer = new StringTokenizer(genPackage.getModelInfo(), "\n\r"); stringTokenizer.hasMoreTokens(); ) { String modelInfo = stringTokenizer.nextToken(); if (first) { first = false; stringBuffer.append(TEXT_17); stringBuffer.append(modelInfo); } else { stringBuffer.append(TEXT_18); stringBuffer.append(modelInfo); }} if (first) { stringBuffer.append(TEXT_19); }} stringBuffer.append(TEXT_20); } else { stringBuffer.append(TEXT_21); } if (isImplementation) { stringBuffer.append(TEXT_22); stringBuffer.append(genPackage.getPackageClassName()); stringBuffer.append(TEXT_23); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.impl.EPackageImpl")); if (!isInterface){ stringBuffer.append(TEXT_24); stringBuffer.append(genPackage.getImportedPackageInterfaceName()); } } else { stringBuffer.append(TEXT_25); stringBuffer.append(genPackage.getPackageInterfaceName()); stringBuffer.append(TEXT_26); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EPackage")); } stringBuffer.append(TEXT_27); if (genModel.hasCopyrightField()) { stringBuffer.append(TEXT_28); stringBuffer.append(publicStaticFinalFlag); stringBuffer.append(genModel.getImportedName("java.lang.String")); stringBuffer.append(TEXT_29); stringBuffer.append(genModel.getCopyrightFieldLiteral()); stringBuffer.append(TEXT_30); stringBuffer.append(genModel.getNonNLS()); stringBuffer.append(TEXT_31); } if (isInterface) { stringBuffer.append(TEXT_32); stringBuffer.append(publicStaticFinalFlag); stringBuffer.append(genModel.getImportedName("java.lang.String")); stringBuffer.append(TEXT_33); stringBuffer.append(genPackage.getPackageName()); stringBuffer.append(TEXT_34); stringBuffer.append(genModel.getNonNLS()); stringBuffer.append(TEXT_35); stringBuffer.append(publicStaticFinalFlag); stringBuffer.append(genModel.getImportedName("java.lang.String")); stringBuffer.append(TEXT_36); stringBuffer.append(genPackage.getNSURI()); stringBuffer.append(TEXT_37); stringBuffer.append(genModel.getNonNLS()); stringBuffer.append(TEXT_38); stringBuffer.append(publicStaticFinalFlag); stringBuffer.append(genModel.getImportedName("java.lang.String")); stringBuffer.append(TEXT_39); stringBuffer.append(genPackage.getNSName()); stringBuffer.append(TEXT_40); stringBuffer.append(genModel.getNonNLS()); if (genPackage.isContentType()) { stringBuffer.append(TEXT_41); stringBuffer.append(publicStaticFinalFlag); stringBuffer.append(genModel.getImportedName("java.lang.String")); stringBuffer.append(TEXT_42); stringBuffer.append(genPackage.getContentTypeIdentifier()); stringBuffer.append(TEXT_43); stringBuffer.append(genModel.getNonNLS()); } stringBuffer.append(TEXT_44); stringBuffer.append(publicStaticFinalFlag); stringBuffer.append(genPackage.getPackageInterfaceName()); stringBuffer.append(TEXT_45); stringBuffer.append(genPackage.getQualifiedPackageClassName()); stringBuffer.append(TEXT_46); for (GenClassifier genClassifier : genPackage.getOrderedGenClassifiers()) { stringBuffer.append(TEXT_47); if (genClassifier instanceof GenClass) { GenClass genClass = (GenClass)genClassifier; if (!genClass.isInterface()) { stringBuffer.append(TEXT_48); stringBuffer.append(genClass.getQualifiedClassName()); stringBuffer.append(TEXT_49); stringBuffer.append(genClass.getFormattedName()); stringBuffer.append(TEXT_50); stringBuffer.append(genClass.getQualifiedClassName()); } else { stringBuffer.append(TEXT_51); stringBuffer.append(genClass.getQualifiedInterfaceName()); stringBuffer.append(TEXT_52); stringBuffer.append(genClass.getFormattedName()); stringBuffer.append(TEXT_53); stringBuffer.append(genClass.getQualifiedInterfaceName()); } } else if (genClassifier instanceof GenEnum) { GenEnum genEnum = (GenEnum)genClassifier; stringBuffer.append(TEXT_54); stringBuffer.append(genEnum.getQualifiedName()); stringBuffer.append(TEXT_55); stringBuffer.append(genEnum.getFormattedName()); stringBuffer.append(TEXT_56); stringBuffer.append(genEnum.getQualifiedName()); } else if (genClassifier instanceof GenDataType) { GenDataType genDataType = (GenDataType)genClassifier; stringBuffer.append(TEXT_57); stringBuffer.append(genDataType.getFormattedName()); stringBuffer.append(TEXT_58); if (!genDataType.isPrimitiveType() && !genDataType.isArrayType()) { stringBuffer.append(TEXT_59); stringBuffer.append(genDataType.getRawInstanceClassName()); } } stringBuffer.append(TEXT_60); stringBuffer.append(genPackage.getQualifiedPackageClassName()); stringBuffer.append(TEXT_61); stringBuffer.append(genClassifier.getClassifierAccessorName()); stringBuffer.append(TEXT_62); stringBuffer.append(publicStaticFinalFlag); stringBuffer.append(TEXT_63); stringBuffer.append(genPackage.getClassifierID(genClassifier)); stringBuffer.append(TEXT_64); stringBuffer.append(genPackage.getClassifierValue(genClassifier)); stringBuffer.append(TEXT_65); if (genClassifier instanceof GenClass) { GenClass genClass = (GenClass)genClassifier; for (GenFeature genFeature : genClass.getAllGenFeatures()) { stringBuffer.append(TEXT_66); stringBuffer.append(genFeature.getFormattedName()); stringBuffer.append(TEXT_67); stringBuffer.append(genFeature.getFeatureKind()); stringBuffer.append(TEXT_68); stringBuffer.append(publicStaticFinalFlag); stringBuffer.append(TEXT_69); stringBuffer.append(genClass.getFeatureID(genFeature)); stringBuffer.append(TEXT_70); stringBuffer.append(genClass.getFeatureValue(genFeature)); stringBuffer.append(TEXT_71); } stringBuffer.append(TEXT_72); stringBuffer.append(genClass.getFormattedName()); stringBuffer.append(TEXT_73); stringBuffer.append(publicStaticFinalFlag); stringBuffer.append(TEXT_74); stringBuffer.append(genClass.getFeatureCountID()); stringBuffer.append(TEXT_75); stringBuffer.append(genClass.getFeatureCountValue()); stringBuffer.append(TEXT_76); } } } if (isImplementation) { if (genPackage.isLoadingInitialization()) { stringBuffer.append(TEXT_77); stringBuffer.append(genPackage.getSerializedPackageFilename()); stringBuffer.append(TEXT_78); stringBuffer.append(genModel.getNonNLS()); stringBuffer.append(TEXT_79); } for (GenClassifier genClassifier : genPackage.getGenClassifiers()) { stringBuffer.append(TEXT_80); stringBuffer.append(genClassifier.getImportedMetaType()); stringBuffer.append(TEXT_81); stringBuffer.append(genClassifier.getClassifierInstanceName()); stringBuffer.append(TEXT_82); } stringBuffer.append(TEXT_83); stringBuffer.append(genPackage.getQualifiedPackageInterfaceName()); stringBuffer.append(TEXT_84); stringBuffer.append(genPackage.getPackageClassName()); stringBuffer.append(TEXT_85); stringBuffer.append(genPackage.getQualifiedEFactoryInstanceAccessor()); stringBuffer.append(TEXT_86); if (!genPackage.isLoadedInitialization()) { stringBuffer.append(TEXT_87); } stringBuffer.append(TEXT_88); stringBuffer.append(genPackage.getImportedPackageInterfaceName()); stringBuffer.append(TEXT_89); stringBuffer.append(genPackage.getImportedPackageInterfaceName()); stringBuffer.append(TEXT_90); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EPackage")); stringBuffer.append(TEXT_91); stringBuffer.append(genPackage.getImportedPackageInterfaceName()); stringBuffer.append(TEXT_92); stringBuffer.append(genPackage.getPackageClassName()); stringBuffer.append(TEXT_93); - stringBuffer.append(genPackage.getPackageInterfaceName()); + stringBuffer.append(genPackage.getBasicPackageName()); stringBuffer.append(TEXT_94); stringBuffer.append(genPackage.getPackageClassName()); stringBuffer.append(TEXT_95); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EPackage")); stringBuffer.append(TEXT_96); stringBuffer.append(genPackage.getPackageClassName()); stringBuffer.append(TEXT_97); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EPackage")); stringBuffer.append(TEXT_98); stringBuffer.append(genPackage.getPackageClassName()); stringBuffer.append(TEXT_99); if (!genPackage.getPackageSimpleDependencies().isEmpty()) { stringBuffer.append(TEXT_100); for (GenPackage dep : genPackage.getPackageSimpleDependencies()) { stringBuffer.append(TEXT_101); stringBuffer.append(dep.getImportedPackageInterfaceName()); stringBuffer.append(TEXT_102); } stringBuffer.append(TEXT_103); } if (!genPackage.getPackageInterDependencies().isEmpty()) { stringBuffer.append(TEXT_104); for (GenPackage interdep : genPackage.getPackageInterDependencies()) { stringBuffer.append(TEXT_105); stringBuffer.append(interdep.getImportedPackageClassName()); stringBuffer.append(TEXT_106); stringBuffer.append(genPackage.getPackageInstanceVariable(interdep)); stringBuffer.append(TEXT_107); stringBuffer.append(interdep.getImportedPackageClassName()); stringBuffer.append(TEXT_108); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EPackage")); stringBuffer.append(TEXT_109); stringBuffer.append(interdep.getImportedPackageInterfaceName()); stringBuffer.append(TEXT_110); stringBuffer.append(interdep.getImportedPackageClassName()); stringBuffer.append(TEXT_111); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EPackage")); stringBuffer.append(TEXT_112); stringBuffer.append(interdep.getImportedPackageInterfaceName()); stringBuffer.append(TEXT_113); stringBuffer.append(interdep.getImportedPackageInterfaceName()); stringBuffer.append(TEXT_114); } stringBuffer.append(TEXT_115); } if (genPackage.isLoadedInitialization() || !genPackage.getPackageLoadInterDependencies().isEmpty()) { stringBuffer.append(TEXT_116); if (genPackage.isLoadingInitialization()) { stringBuffer.append(TEXT_117); - stringBuffer.append(genPackage.getPackageInterfaceName()); + stringBuffer.append(genPackage.getBasicPackageName()); stringBuffer.append(TEXT_118); } for (GenPackage interdep : genPackage.getPackageLoadInterDependencies()) { if (interdep.isLoadingInitialization()) { stringBuffer.append(TEXT_119); stringBuffer.append(genPackage.getPackageInstanceVariable(interdep)); stringBuffer.append(TEXT_120); } } stringBuffer.append(TEXT_121); } if (!genPackage.isLoadedInitialization() || !genPackage.getPackageBuildInterDependencies().isEmpty()) { stringBuffer.append(TEXT_122); if (!genPackage.isLoadedInitialization()) { stringBuffer.append(TEXT_123); - stringBuffer.append(genPackage.getPackageInterfaceName()); + stringBuffer.append(genPackage.getBasicPackageName()); stringBuffer.append(TEXT_124); } for (GenPackage interdep : genPackage.getPackageBuildInterDependencies()) { stringBuffer.append(TEXT_125); stringBuffer.append(genPackage.getPackageInstanceVariable(interdep)); stringBuffer.append(TEXT_126); } stringBuffer.append(TEXT_127); if (!genPackage.isLoadedInitialization()) { stringBuffer.append(TEXT_128); - stringBuffer.append(genPackage.getPackageInterfaceName()); + stringBuffer.append(genPackage.getBasicPackageName()); stringBuffer.append(TEXT_129); } for (GenPackage interdep : genPackage.getPackageBuildInterDependencies()) { stringBuffer.append(TEXT_130); stringBuffer.append(genPackage.getPackageInstanceVariable(interdep)); stringBuffer.append(TEXT_131); } stringBuffer.append(TEXT_132); } if (genPackage.isLoadedInitialization() || !genPackage.getPackageLoadInterDependencies().isEmpty()) { stringBuffer.append(TEXT_133); if (genPackage.isLoadedInitialization()) { stringBuffer.append(TEXT_134); - stringBuffer.append(genPackage.getPackageInterfaceName()); + stringBuffer.append(genPackage.getBasicPackageName()); stringBuffer.append(TEXT_135); } for (GenPackage interdep : genPackage.getPackageLoadInterDependencies()) { stringBuffer.append(TEXT_136); stringBuffer.append(genPackage.getPackageInstanceVariable(interdep)); stringBuffer.append(TEXT_137); } stringBuffer.append(TEXT_138); } if (genPackage.hasConstraints()) { stringBuffer.append(TEXT_139); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EValidator")); stringBuffer.append(TEXT_140); - stringBuffer.append(genPackage.getPackageInterfaceName()); + stringBuffer.append(genPackage.getBasicPackageName()); stringBuffer.append(TEXT_141); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EValidator")); stringBuffer.append(TEXT_142); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EValidator")); stringBuffer.append(TEXT_143); stringBuffer.append(genPackage.getImportedValidatorClassName()); stringBuffer.append(TEXT_144); } if (!genPackage.isEcorePackage()) { stringBuffer.append(TEXT_145); - stringBuffer.append(genPackage.getPackageInterfaceName()); + stringBuffer.append(genPackage.getBasicPackageName()); stringBuffer.append(TEXT_146); } stringBuffer.append(TEXT_147); - stringBuffer.append(genPackage.getPackageInterfaceName()); + stringBuffer.append(genPackage.getBasicPackageName()); stringBuffer.append(TEXT_148); } if (isInterface) { // TODO REMOVE THIS BOGUS EMPTY LINE stringBuffer.append(TEXT_149); } for (GenClassifier genClassifier : genPackage.getGenClassifiers()) { if (isInterface) { stringBuffer.append(TEXT_150); if (genClassifier instanceof GenClass) { GenClass genClass = (GenClass)genClassifier; stringBuffer.append(TEXT_151); stringBuffer.append(genClass.getQualifiedInterfaceName()); stringBuffer.append(TEXT_152); stringBuffer.append(genClass.getFormattedName()); stringBuffer.append(TEXT_153); stringBuffer.append(genClass.getFormattedName()); stringBuffer.append(TEXT_154); stringBuffer.append(genClass.getQualifiedInterfaceName()); if (!genModel.isSuppressEMFModelTags() && (genClass.isExternalInterface() || genClass.isDynamic())) { boolean first = true; for (StringTokenizer stringTokenizer = new StringTokenizer(genClass.getModelInfo(), "\n\r"); stringTokenizer.hasMoreTokens(); ) { String modelInfo = stringTokenizer.nextToken(); if (first) { first = false; stringBuffer.append(TEXT_155); stringBuffer.append(modelInfo); } else { stringBuffer.append(TEXT_156); stringBuffer.append(modelInfo); }} if (first) { stringBuffer.append(TEXT_157); }} } else if (genClassifier instanceof GenEnum) { GenEnum genEnum = (GenEnum)genClassifier; stringBuffer.append(TEXT_158); stringBuffer.append(genEnum.getQualifiedName()); stringBuffer.append(TEXT_159); stringBuffer.append(genEnum.getFormattedName()); stringBuffer.append(TEXT_160); stringBuffer.append(genEnum.getFormattedName()); stringBuffer.append(TEXT_161); stringBuffer.append(genEnum.getQualifiedName()); } else if (genClassifier instanceof GenDataType) { GenDataType genDataType = (GenDataType)genClassifier; if (genDataType.isPrimitiveType() || genDataType.isArrayType()) { stringBuffer.append(TEXT_162); stringBuffer.append(genDataType.getFormattedName()); stringBuffer.append(TEXT_163); } else { stringBuffer.append(TEXT_164); stringBuffer.append(genDataType.getRawInstanceClassName()); stringBuffer.append(TEXT_165); stringBuffer.append(genDataType.getFormattedName()); stringBuffer.append(TEXT_166); } stringBuffer.append(TEXT_167); stringBuffer.append(genDataType.getFormattedName()); stringBuffer.append(TEXT_168); if (!genDataType.isPrimitiveType() && !genDataType.isArrayType()) { stringBuffer.append(TEXT_169); stringBuffer.append(genDataType.getRawInstanceClassName()); } if (!genModel.isSuppressEMFModelTags()) {boolean first = true; for (StringTokenizer stringTokenizer = new StringTokenizer(genDataType.getModelInfo(), "\n\r"); stringTokenizer.hasMoreTokens(); ) { String modelInfo = stringTokenizer.nextToken(); if (first) { first = false; stringBuffer.append(TEXT_170); stringBuffer.append(modelInfo); } else { stringBuffer.append(TEXT_171); stringBuffer.append(modelInfo); }} if (first) { stringBuffer.append(TEXT_172); }} } stringBuffer.append(TEXT_173); } else { stringBuffer.append(TEXT_174); } if (isImplementation) { stringBuffer.append(TEXT_175); stringBuffer.append(genClassifier.getImportedMetaType()); stringBuffer.append(TEXT_176); stringBuffer.append(genClassifier.getClassifierAccessorName()); stringBuffer.append(TEXT_177); if (genPackage.isLoadedInitialization()) { stringBuffer.append(TEXT_178); stringBuffer.append(genClassifier.getClassifierInstanceName()); stringBuffer.append(TEXT_179); stringBuffer.append(genClassifier.getClassifierInstanceName()); stringBuffer.append(TEXT_180); stringBuffer.append(genClassifier.getImportedMetaType()); stringBuffer.append(TEXT_181); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EPackage")); stringBuffer.append(TEXT_182); stringBuffer.append(genPackage.getImportedPackageInterfaceName()); stringBuffer.append(TEXT_183); stringBuffer.append(genPackage.getLocalClassifierIndex(genClassifier)); stringBuffer.append(TEXT_184); } stringBuffer.append(TEXT_185); stringBuffer.append(genClassifier.getClassifierInstanceName()); stringBuffer.append(TEXT_186); } else { stringBuffer.append(TEXT_187); stringBuffer.append(genClassifier.getImportedMetaType()); stringBuffer.append(TEXT_188); stringBuffer.append(genClassifier.getClassifierAccessorName()); stringBuffer.append(TEXT_189); } if (genClassifier instanceof GenClass) { GenClass genClass = (GenClass)genClassifier; for (GenFeature genFeature : genClass.getGenFeatures()) { if (isInterface) { stringBuffer.append(TEXT_190); stringBuffer.append(genFeature.getFeatureKind()); stringBuffer.append(TEXT_191); stringBuffer.append(genClass.getQualifiedInterfaceName()); if (!genClass.isMapEntry() && !genFeature.isSuppressedGetVisibility()) { stringBuffer.append(TEXT_192); stringBuffer.append(genFeature.getGetAccessor()); } stringBuffer.append(TEXT_193); stringBuffer.append(genFeature.getFormattedName()); stringBuffer.append(TEXT_194); stringBuffer.append(genFeature.getFeatureKind()); stringBuffer.append(TEXT_195); stringBuffer.append(genFeature.getFormattedName()); stringBuffer.append(TEXT_196); stringBuffer.append(genClass.getQualifiedInterfaceName()); if (!genClass.isMapEntry() && !genFeature.isSuppressedGetVisibility()) { stringBuffer.append(TEXT_197); stringBuffer.append(genFeature.getGetAccessor()); stringBuffer.append(TEXT_198); } stringBuffer.append(TEXT_199); stringBuffer.append(genClass.getClassifierAccessorName()); stringBuffer.append(TEXT_200); } else { stringBuffer.append(TEXT_201); } if (isImplementation) { stringBuffer.append(TEXT_202); stringBuffer.append(genFeature.getImportedMetaType()); stringBuffer.append(TEXT_203); stringBuffer.append(genFeature.getFeatureAccessorName()); stringBuffer.append(TEXT_204); if (!genPackage.isLoadedInitialization()) { stringBuffer.append(TEXT_205); stringBuffer.append(genFeature.getImportedMetaType()); stringBuffer.append(TEXT_206); stringBuffer.append(genClass.getClassifierInstanceName()); stringBuffer.append(TEXT_207); stringBuffer.append(genClass.getLocalFeatureIndex(genFeature)); stringBuffer.append(TEXT_208); } else { stringBuffer.append(TEXT_209); stringBuffer.append(genFeature.getImportedMetaType()); stringBuffer.append(TEXT_210); stringBuffer.append(genClassifier.getClassifierAccessorName()); stringBuffer.append(TEXT_211); stringBuffer.append(genClass.getLocalFeatureIndex(genFeature)); stringBuffer.append(TEXT_212); } stringBuffer.append(TEXT_213); } else { stringBuffer.append(TEXT_214); stringBuffer.append(genFeature.getImportedMetaType()); stringBuffer.append(TEXT_215); stringBuffer.append(genFeature.getFeatureAccessorName()); stringBuffer.append(TEXT_216); } stringBuffer.append(TEXT_217); } } } if (isInterface) { stringBuffer.append(TEXT_218); } else { stringBuffer.append(TEXT_219); } if (isImplementation) { stringBuffer.append(TEXT_220); stringBuffer.append(genPackage.getImportedFactoryInterfaceName()); stringBuffer.append(TEXT_221); - stringBuffer.append(genPackage.getFactoryInterfaceName()); + stringBuffer.append(genPackage.getFactoryName()); stringBuffer.append(TEXT_222); stringBuffer.append(genPackage.getImportedFactoryInterfaceName()); stringBuffer.append(TEXT_223); } else { stringBuffer.append(TEXT_224); stringBuffer.append(genPackage.getFactoryInterfaceName()); stringBuffer.append(TEXT_225); - stringBuffer.append(genPackage.getFactoryInterfaceName()); + stringBuffer.append(genPackage.getFactoryName()); stringBuffer.append(TEXT_226); } stringBuffer.append(TEXT_227); if (isImplementation) { if (!genPackage.isLoadedInitialization()) { stringBuffer.append(TEXT_228); if (!genPackage.getGenClasses().isEmpty()) { stringBuffer.append(TEXT_229); for (Iterator<GenClass> c=genPackage.getGenClasses().iterator(); c.hasNext();) { GenClass genClass = c.next(); stringBuffer.append(TEXT_230); stringBuffer.append(genClass.getClassifierInstanceName()); stringBuffer.append(TEXT_231); stringBuffer.append(genClass.getMetaType()); stringBuffer.append(TEXT_232); stringBuffer.append(genClass.getClassifierID()); stringBuffer.append(TEXT_233); for (GenFeature genFeature : genClass.getGenFeatures()) { stringBuffer.append(TEXT_234); stringBuffer.append(genFeature.getMetaType()); stringBuffer.append(TEXT_235); stringBuffer.append(genClass.getClassifierInstanceName()); stringBuffer.append(TEXT_236); stringBuffer.append(genClass.getFeatureID(genFeature)); stringBuffer.append(TEXT_237); } if (c.hasNext()) { stringBuffer.append(TEXT_238); } } } if (!genPackage.getGenEnums().isEmpty()) { stringBuffer.append(TEXT_239); for (GenEnum genEnum : genPackage.getGenEnums()) { stringBuffer.append(TEXT_240); stringBuffer.append(genEnum.getClassifierInstanceName()); stringBuffer.append(TEXT_241); stringBuffer.append(genEnum.getClassifierID()); stringBuffer.append(TEXT_242); } } if (!genPackage.getGenDataTypes().isEmpty()) { stringBuffer.append(TEXT_243); for (GenDataType genDataType : genPackage.getGenDataTypes()) { stringBuffer.append(TEXT_244); stringBuffer.append(genDataType.getClassifierInstanceName()); stringBuffer.append(TEXT_245); stringBuffer.append(genDataType.getClassifierID()); stringBuffer.append(TEXT_246); } } stringBuffer.append(TEXT_247); /////////////////////// class Information { @SuppressWarnings("unused") EGenericType eGenericType; int depth; String type; String accessor; } class InformationIterator { Iterator<?> iterator; InformationIterator(EGenericType eGenericType) { iterator = EcoreUtil.getAllContents(Collections.singleton(eGenericType)); } boolean hasNext() { return iterator.hasNext(); } Information next() { Information information = new Information(); EGenericType eGenericType = information.eGenericType = (EGenericType)iterator.next(); for (EObject container = eGenericType.eContainer(); container instanceof EGenericType; container = container.eContainer()) { ++information.depth; } if (eGenericType.getEClassifier() != null ) { GenClassifier genClassifier = genModel.findGenClassifier(eGenericType.getEClassifier()); information.type = genPackage.getPackageInstanceVariable(genClassifier.getGenPackage()) + ".get" + genClassifier.getClassifierAccessorName() + "()"; } else if (eGenericType.getETypeParameter() != null) { ETypeParameter eTypeParameter = eGenericType.getETypeParameter(); if (eTypeParameter.eContainer() instanceof EClass) { information.type = genModel.findGenClassifier((EClass)eTypeParameter.eContainer()).getClassifierInstanceName() + "_" + eGenericType.getETypeParameter().getName(); } else { information.type = "t" + (((EOperation)eTypeParameter.eContainer()).getETypeParameters().indexOf(eTypeParameter) + 1); } } else { information.type =""; } if (information.depth > 0) { if (eGenericType.eContainmentFeature().isMany()) { information.accessor = "getE" + eGenericType.eContainmentFeature().getName().substring(1) + "().add"; } else { information.accessor = "setE" + eGenericType.eContainmentFeature().getName().substring(1); } } return information; } } /////////////////////// int maxGenericTypeAssignment = 0; stringBuffer.append(TEXT_248); if (!genPackage.getPackageInitializationDependencies().isEmpty()) { stringBuffer.append(TEXT_249); for (GenPackage dep : genPackage.getPackageInitializationDependencies()) { stringBuffer.append(TEXT_250); stringBuffer.append(dep.getImportedPackageInterfaceName()); stringBuffer.append(TEXT_251); stringBuffer.append(genPackage.getPackageInstanceVariable(dep)); stringBuffer.append(TEXT_252); stringBuffer.append(dep.getImportedPackageInterfaceName()); stringBuffer.append(TEXT_253); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EPackage")); stringBuffer.append(TEXT_254); stringBuffer.append(dep.getImportedPackageInterfaceName()); stringBuffer.append(TEXT_255); } } if (!genPackage.getSubGenPackages().isEmpty()) { stringBuffer.append(TEXT_256); for (GenPackage sub : genPackage.getSubGenPackages()) { stringBuffer.append(TEXT_257); stringBuffer.append(genPackage.getPackageInstanceVariable(sub)); stringBuffer.append(TEXT_258); } } if (!genPackage.getGenClasses().isEmpty()) { boolean firstOperationAssignment = true; int maxTypeParameterAssignment = 0; if (genModel.useGenerics()) { stringBuffer.append(TEXT_259); for (GenClassifier genClassifier : genPackage.getGenClassifiers()) { for (GenTypeParameter genTypeParameter : genClassifier.getGenTypeParameters()) { if (!genTypeParameter.getEcoreTypeParameter().getEBounds().isEmpty() || genTypeParameter.isUsed()) { stringBuffer.append(TEXT_260); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.ETypeParameter")); stringBuffer.append(TEXT_261); stringBuffer.append(genClassifier.getClassifierInstanceName()); stringBuffer.append(TEXT_262); stringBuffer.append(genTypeParameter.getName()); stringBuffer.append(TEXT_263); stringBuffer.append(genClassifier.getClassifierInstanceName()); stringBuffer.append(TEXT_264); stringBuffer.append(genTypeParameter.getName()); stringBuffer.append(TEXT_265); stringBuffer.append(genModel.getNonNLS()); } else { stringBuffer.append(TEXT_266); stringBuffer.append(genClassifier.getClassifierInstanceName()); stringBuffer.append(TEXT_267); stringBuffer.append(genTypeParameter.getName()); stringBuffer.append(TEXT_268); stringBuffer.append(genModel.getNonNLS()); } } } } if (genModel.useGenerics()) { stringBuffer.append(TEXT_269); for (GenClassifier genClassifier : genPackage.getGenClassifiers()) { for (GenTypeParameter genTypeParameter : genClassifier.getGenTypeParameters()) { for (EGenericType bound : genTypeParameter.getEcoreTypeParameter().getEBounds()) { for (InformationIterator i=new InformationIterator(bound); i.hasNext(); ) { Information info = i.next(); String prefix = ""; if (maxGenericTypeAssignment <= info.depth) { ++maxGenericTypeAssignment; prefix = genModel.getImportedName("org.eclipse.emf.ecore.EGenericType") + " "; } stringBuffer.append(TEXT_270); stringBuffer.append(prefix); stringBuffer.append(TEXT_271); stringBuffer.append(info.depth + 1); stringBuffer.append(TEXT_272); stringBuffer.append(info.type); stringBuffer.append(TEXT_273); if (info.depth > 0) { stringBuffer.append(TEXT_274); stringBuffer.append(info.depth); stringBuffer.append(TEXT_275); stringBuffer.append(info.accessor); stringBuffer.append(TEXT_276); stringBuffer.append(info.depth + 1); stringBuffer.append(TEXT_277); } } stringBuffer.append(TEXT_278); stringBuffer.append(genClassifier.getClassifierInstanceName()); stringBuffer.append(TEXT_279); stringBuffer.append(genTypeParameter.getName()); stringBuffer.append(TEXT_280); } } } } stringBuffer.append(TEXT_281); for (GenClass genClass : genPackage.getGenClasses()) { if (!genClass.hasGenericSuperTypes()) { for (GenClass baseGenClass : genClass.getBaseGenClasses()) { stringBuffer.append(TEXT_282); stringBuffer.append(genClass.getClassifierInstanceName()); stringBuffer.append(TEXT_283); stringBuffer.append(genPackage.getPackageInstanceVariable(baseGenClass.getGenPackage())); stringBuffer.append(TEXT_284); stringBuffer.append(baseGenClass.getClassifierAccessorName()); stringBuffer.append(TEXT_285); } } else { for (EGenericType superType : genClass.getEcoreClass().getEGenericSuperTypes()) { for (InformationIterator i=new InformationIterator(superType); i.hasNext(); ) { Information info = i.next(); String prefix = ""; if (maxGenericTypeAssignment <= info.depth) { ++maxGenericTypeAssignment; prefix = genModel.getImportedName("org.eclipse.emf.ecore.EGenericType") + " "; } stringBuffer.append(TEXT_286); stringBuffer.append(prefix); stringBuffer.append(TEXT_287); stringBuffer.append(info.depth + 1); stringBuffer.append(TEXT_288); stringBuffer.append(info.type); stringBuffer.append(TEXT_289); if (info.depth > 0) { stringBuffer.append(TEXT_290); stringBuffer.append(info.depth); stringBuffer.append(TEXT_291); stringBuffer.append(info.accessor); stringBuffer.append(TEXT_292); stringBuffer.append(info.depth + 1); stringBuffer.append(TEXT_293); } } stringBuffer.append(TEXT_294); stringBuffer.append(genClass.getClassifierInstanceName()); stringBuffer.append(TEXT_295); } } } stringBuffer.append(TEXT_296); for (Iterator<GenClass> c=genPackage.getGenClasses().iterator(); c.hasNext();) { GenClass genClass = c.next(); boolean hasInstanceTypeName = genModel.useGenerics() && genClass.getEcoreClass().getInstanceTypeName() != null && genClass.getEcoreClass().getInstanceTypeName().contains("<"); stringBuffer.append(TEXT_297); stringBuffer.append(genClass.getClassifierInstanceName()); stringBuffer.append(TEXT_298); if (genClass.isDynamic()) { stringBuffer.append(TEXT_299); } else { stringBuffer.append(genClass.getRawImportedInterfaceName()); stringBuffer.append(TEXT_300); } stringBuffer.append(TEXT_301); stringBuffer.append(genClass.getName()); stringBuffer.append(TEXT_302); stringBuffer.append(genClass.getAbstractFlag()); stringBuffer.append(TEXT_303); stringBuffer.append(genClass.getInterfaceFlag()); stringBuffer.append(TEXT_304); stringBuffer.append(genClass.getGeneratedInstanceClassFlag()); if (hasInstanceTypeName) { stringBuffer.append(TEXT_305); stringBuffer.append(genClass.getEcoreClass().getInstanceTypeName()); stringBuffer.append(TEXT_306); } stringBuffer.append(TEXT_307); stringBuffer.append(genModel.getNonNLS()); if (hasInstanceTypeName) { stringBuffer.append(genModel.getNonNLS(2)); } for (GenFeature genFeature : genClass.getGenFeatures()) { if (genFeature.hasGenericType()) { for (InformationIterator i=new InformationIterator(genFeature.getEcoreFeature().getEGenericType()); i.hasNext(); ) { Information info = i.next(); String prefix = ""; if (maxGenericTypeAssignment <= info.depth) { ++maxGenericTypeAssignment; prefix = genModel.getImportedName("org.eclipse.emf.ecore.EGenericType") + " "; } stringBuffer.append(TEXT_308); stringBuffer.append(prefix); stringBuffer.append(TEXT_309); stringBuffer.append(info.depth + 1); stringBuffer.append(TEXT_310); stringBuffer.append(info.type); stringBuffer.append(TEXT_311); if (info.depth > 0) { stringBuffer.append(TEXT_312); stringBuffer.append(info.depth); stringBuffer.append(TEXT_313); stringBuffer.append(info.accessor); stringBuffer.append(TEXT_314); stringBuffer.append(info.depth + 1); stringBuffer.append(TEXT_315); } } } if (genFeature.isReferenceType()) { GenFeature reverseGenFeature = genFeature.getReverse(); String reverse = reverseGenFeature == null ? "null" : genPackage.getPackageInstanceVariable(reverseGenFeature.getGenPackage()) + ".get" + reverseGenFeature.getFeatureAccessorName() + "()"; stringBuffer.append(TEXT_316); stringBuffer.append(genFeature.getFeatureAccessorName()); stringBuffer.append(TEXT_317); if (genFeature.hasGenericType()) { stringBuffer.append(TEXT_318); } else { stringBuffer.append(genPackage.getPackageInstanceVariable(genFeature.getTypeGenPackage())); stringBuffer.append(TEXT_319); stringBuffer.append(genFeature.getTypeClassifierAccessorName()); stringBuffer.append(TEXT_320); } stringBuffer.append(TEXT_321); stringBuffer.append(reverse); stringBuffer.append(TEXT_322); stringBuffer.append(genFeature.getName()); stringBuffer.append(TEXT_323); stringBuffer.append(genFeature.getDefaultValue()); stringBuffer.append(TEXT_324); stringBuffer.append(genFeature.getLowerBound()); stringBuffer.append(TEXT_325); stringBuffer.append(genFeature.getUpperBound()); stringBuffer.append(TEXT_326); stringBuffer.append(genFeature.getContainerClass()); stringBuffer.append(TEXT_327); stringBuffer.append(genFeature.getTransientFlag()); stringBuffer.append(TEXT_328); stringBuffer.append(genFeature.getVolatileFlag()); stringBuffer.append(TEXT_329); stringBuffer.append(genFeature.getChangeableFlag()); stringBuffer.append(TEXT_330); stringBuffer.append(genFeature.getContainmentFlag()); stringBuffer.append(TEXT_331); stringBuffer.append(genFeature.getResolveProxiesFlag()); stringBuffer.append(TEXT_332); stringBuffer.append(genFeature.getUnsettableFlag()); stringBuffer.append(TEXT_333); stringBuffer.append(genFeature.getUniqueFlag()); stringBuffer.append(TEXT_334); stringBuffer.append(genFeature.getDerivedFlag()); stringBuffer.append(TEXT_335); stringBuffer.append(genFeature.getOrderedFlag()); stringBuffer.append(TEXT_336); stringBuffer.append(genModel.getNonNLS()); stringBuffer.append(genModel.getNonNLS(genFeature.getDefaultValue(), 2)); for (GenFeature keyFeature : genFeature.getKeys()) { stringBuffer.append(TEXT_337); stringBuffer.append(genFeature.getFeatureAccessorName()); stringBuffer.append(TEXT_338); stringBuffer.append(genPackage.getPackageInstanceVariable(keyFeature.getGenPackage())); stringBuffer.append(TEXT_339); stringBuffer.append(keyFeature.getFeatureAccessorName()); stringBuffer.append(TEXT_340); } } else { stringBuffer.append(TEXT_341); stringBuffer.append(genFeature.getFeatureAccessorName()); stringBuffer.append(TEXT_342); if (genFeature.hasGenericType()) { stringBuffer.append(TEXT_343); } else { stringBuffer.append(genPackage.getPackageInstanceVariable(genFeature.getTypeGenPackage())); stringBuffer.append(TEXT_344); stringBuffer.append(genFeature.getTypeClassifierAccessorName()); stringBuffer.append(TEXT_345); } stringBuffer.append(TEXT_346); stringBuffer.append(genFeature.getName()); stringBuffer.append(TEXT_347); stringBuffer.append(genFeature.getDefaultValue()); stringBuffer.append(TEXT_348); stringBuffer.append(genFeature.getLowerBound()); stringBuffer.append(TEXT_349); stringBuffer.append(genFeature.getUpperBound()); stringBuffer.append(TEXT_350); stringBuffer.append(genFeature.getContainerClass()); stringBuffer.append(TEXT_351); stringBuffer.append(genFeature.getTransientFlag()); stringBuffer.append(TEXT_352); stringBuffer.append(genFeature.getVolatileFlag()); stringBuffer.append(TEXT_353); stringBuffer.append(genFeature.getChangeableFlag()); stringBuffer.append(TEXT_354); stringBuffer.append(genFeature.getUnsettableFlag()); stringBuffer.append(TEXT_355); stringBuffer.append(genFeature.getIDFlag()); stringBuffer.append(TEXT_356); stringBuffer.append(genFeature.getUniqueFlag()); stringBuffer.append(TEXT_357); stringBuffer.append(genFeature.getDerivedFlag()); stringBuffer.append(TEXT_358); stringBuffer.append(genFeature.getOrderedFlag()); stringBuffer.append(TEXT_359); stringBuffer.append(genModel.getNonNLS()); stringBuffer.append(genModel.getNonNLS(genFeature.getDefaultValue(), 2)); } } for (GenOperation genOperation : genClass.getGenOperations()) {String prefix = ""; if (genOperation.hasGenericType() || !genOperation.getGenParameters().isEmpty() || !genOperation.getGenExceptions().isEmpty() || !genOperation.getGenTypeParameters().isEmpty()) { if (firstOperationAssignment) { firstOperationAssignment = false; prefix = genModel.getImportedName("org.eclipse.emf.ecore.EOperation") + " op = "; } else { prefix = "op = "; }} stringBuffer.append(TEXT_360); if (genModel.useGenerics()) { stringBuffer.append(TEXT_361); stringBuffer.append(prefix); stringBuffer.append(TEXT_362); stringBuffer.append(genClass.getClassifierInstanceName()); stringBuffer.append(TEXT_363); if (genOperation.isVoid() || genOperation.hasGenericType()) { stringBuffer.append(TEXT_364); } else { stringBuffer.append(genPackage.getPackageInstanceVariable(genOperation.getTypeGenPackage())); stringBuffer.append(TEXT_365); stringBuffer.append(genOperation.getTypeClassifierAccessorName()); stringBuffer.append(TEXT_366); } stringBuffer.append(TEXT_367); stringBuffer.append(genOperation.getName()); stringBuffer.append(TEXT_368); stringBuffer.append(genOperation.getLowerBound()); stringBuffer.append(TEXT_369); stringBuffer.append(genOperation.getUpperBound()); stringBuffer.append(TEXT_370); stringBuffer.append(genOperation.getUniqueFlag()); stringBuffer.append(TEXT_371); stringBuffer.append(genOperation.getOrderedFlag()); stringBuffer.append(TEXT_372); stringBuffer.append(genModel.getNonNLS()); } else if (!genOperation.isVoid()) { if (!genOperation.getEcoreOperation().isOrdered() || !genOperation.getEcoreOperation().isUnique()) { needsAddEOperation = true; stringBuffer.append(TEXT_373); stringBuffer.append(prefix); stringBuffer.append(TEXT_374); stringBuffer.append(genClass.getClassifierInstanceName()); stringBuffer.append(TEXT_375); stringBuffer.append(genPackage.getPackageInstanceVariable(genOperation.getTypeGenPackage())); stringBuffer.append(TEXT_376); stringBuffer.append(genOperation.getTypeClassifierAccessorName()); stringBuffer.append(TEXT_377); stringBuffer.append(genOperation.getName()); stringBuffer.append(TEXT_378); stringBuffer.append(genOperation.getLowerBound()); stringBuffer.append(TEXT_379); stringBuffer.append(genOperation.getUpperBound()); stringBuffer.append(TEXT_380); stringBuffer.append(genOperation.getUniqueFlag()); stringBuffer.append(TEXT_381); stringBuffer.append(genOperation.getOrderedFlag()); stringBuffer.append(TEXT_382); stringBuffer.append(genModel.getNonNLS()); } else { stringBuffer.append(TEXT_383); stringBuffer.append(prefix); stringBuffer.append(TEXT_384); stringBuffer.append(genClass.getClassifierInstanceName()); stringBuffer.append(TEXT_385); stringBuffer.append(genPackage.getPackageInstanceVariable(genOperation.getTypeGenPackage())); stringBuffer.append(TEXT_386); stringBuffer.append(genOperation.getTypeClassifierAccessorName()); stringBuffer.append(TEXT_387); stringBuffer.append(genOperation.getName()); stringBuffer.append(TEXT_388); stringBuffer.append(genOperation.getLowerBound()); stringBuffer.append(TEXT_389); stringBuffer.append(genOperation.getUpperBound()); stringBuffer.append(TEXT_390); stringBuffer.append(genModel.getNonNLS()); } } else { stringBuffer.append(TEXT_391); stringBuffer.append(prefix); stringBuffer.append(TEXT_392); stringBuffer.append(genClass.getClassifierInstanceName()); stringBuffer.append(TEXT_393); stringBuffer.append(genOperation.getName()); stringBuffer.append(TEXT_394); stringBuffer.append(genModel.getNonNLS()); } if (genModel.useGenerics()) { for (ListIterator<GenTypeParameter> t=genOperation.getGenTypeParameters().listIterator(); t.hasNext(); ) { GenTypeParameter genTypeParameter = t.next(); String typeParameterVariable = ""; if (!genTypeParameter.getEcoreTypeParameter().getEBounds().isEmpty() || genTypeParameter.isUsed()) { if (maxTypeParameterAssignment <= t.previousIndex()) { ++maxTypeParameterAssignment; typeParameterVariable = genModel.getImportedName("org.eclipse.emf.ecore.ETypeParameter") + " t" + t.nextIndex() + " = "; } else { typeParameterVariable = "t" + t.nextIndex() + " = "; }} stringBuffer.append(TEXT_395); stringBuffer.append(typeParameterVariable); stringBuffer.append(TEXT_396); stringBuffer.append(genTypeParameter.getName()); stringBuffer.append(TEXT_397); stringBuffer.append(genModel.getNonNLS()); for (EGenericType typeParameter : genTypeParameter.getEcoreTypeParameter().getEBounds()) { for (InformationIterator i=new InformationIterator(typeParameter); i.hasNext(); ) { Information info = i.next(); String typePrefix = ""; if (maxGenericTypeAssignment <= info.depth) { ++maxGenericTypeAssignment; typePrefix = genModel.getImportedName("org.eclipse.emf.ecore.EGenericType") + " "; } stringBuffer.append(TEXT_398); stringBuffer.append(typePrefix); stringBuffer.append(TEXT_399); stringBuffer.append(info.depth + 1); stringBuffer.append(TEXT_400); stringBuffer.append(info.type); stringBuffer.append(TEXT_401); if (info.depth > 0) { stringBuffer.append(TEXT_402); stringBuffer.append(info.depth); stringBuffer.append(TEXT_403); stringBuffer.append(info.accessor); stringBuffer.append(TEXT_404); stringBuffer.append(info.depth + 1); stringBuffer.append(TEXT_405); } } stringBuffer.append(TEXT_406); stringBuffer.append(t.nextIndex()); stringBuffer.append(TEXT_407); } } } for (GenParameter genParameter : genOperation.getGenParameters()) { if (genParameter.hasGenericType()) { for (InformationIterator i=new InformationIterator(genParameter.getEcoreParameter().getEGenericType()); i.hasNext(); ) { Information info = i.next(); String typePrefix = ""; if (maxGenericTypeAssignment <= info.depth) { ++maxGenericTypeAssignment; typePrefix = genModel.getImportedName("org.eclipse.emf.ecore.EGenericType") + " "; } stringBuffer.append(TEXT_408); stringBuffer.append(typePrefix); stringBuffer.append(TEXT_409); stringBuffer.append(info.depth + 1); stringBuffer.append(TEXT_410); stringBuffer.append(info.type); stringBuffer.append(TEXT_411); if (info.depth > 0) { stringBuffer.append(TEXT_412); stringBuffer.append(info.depth); stringBuffer.append(TEXT_413); stringBuffer.append(info.accessor); stringBuffer.append(TEXT_414); stringBuffer.append(info.depth + 1); stringBuffer.append(TEXT_415); } } } if (genModel.useGenerics()) { stringBuffer.append(TEXT_416); if (genParameter.hasGenericType()){ stringBuffer.append(TEXT_417); } else { stringBuffer.append(genPackage.getPackageInstanceVariable(genParameter.getTypeGenPackage())); stringBuffer.append(TEXT_418); stringBuffer.append(genParameter.getTypeClassifierAccessorName()); stringBuffer.append(TEXT_419); } stringBuffer.append(TEXT_420); stringBuffer.append(genParameter.getName()); stringBuffer.append(TEXT_421); stringBuffer.append(genParameter.getLowerBound()); stringBuffer.append(TEXT_422); stringBuffer.append(genParameter.getUpperBound()); stringBuffer.append(TEXT_423); stringBuffer.append(genParameter.getUniqueFlag()); stringBuffer.append(TEXT_424); stringBuffer.append(genParameter.getOrderedFlag()); stringBuffer.append(TEXT_425); stringBuffer.append(genModel.getNonNLS()); } else if (!genParameter.getEcoreParameter().isOrdered() || !genParameter.getEcoreParameter().isUnique()) { needsAddEParameter = true; stringBuffer.append(TEXT_426); if (genParameter.hasGenericType()){ stringBuffer.append(TEXT_427); } else { stringBuffer.append(genPackage.getPackageInstanceVariable(genParameter.getTypeGenPackage())); stringBuffer.append(TEXT_428); stringBuffer.append(genParameter.getTypeClassifierAccessorName()); stringBuffer.append(TEXT_429); } stringBuffer.append(TEXT_430); stringBuffer.append(genParameter.getName()); stringBuffer.append(TEXT_431); stringBuffer.append(genParameter.getLowerBound()); stringBuffer.append(TEXT_432); stringBuffer.append(genParameter.getUpperBound()); stringBuffer.append(TEXT_433); stringBuffer.append(genParameter.getUniqueFlag()); stringBuffer.append(TEXT_434); stringBuffer.append(genParameter.getOrderedFlag()); stringBuffer.append(TEXT_435); stringBuffer.append(genModel.getNonNLS()); } else { stringBuffer.append(TEXT_436); if (genParameter.hasGenericType()){ stringBuffer.append(TEXT_437); } else { stringBuffer.append(genPackage.getPackageInstanceVariable(genParameter.getTypeGenPackage())); stringBuffer.append(TEXT_438); stringBuffer.append(genParameter.getTypeClassifierAccessorName()); stringBuffer.append(TEXT_439); } stringBuffer.append(TEXT_440); stringBuffer.append(genParameter.getName()); stringBuffer.append(TEXT_441); stringBuffer.append(genParameter.getLowerBound()); stringBuffer.append(TEXT_442); stringBuffer.append(genParameter.getUpperBound()); stringBuffer.append(TEXT_443); stringBuffer.append(genModel.getNonNLS()); } } if (genOperation.hasGenericExceptions()) { for (EGenericType genericExceptions : genOperation.getEcoreOperation().getEGenericExceptions()) { for (InformationIterator i=new InformationIterator(genericExceptions); i.hasNext(); ) { Information info = i.next(); String typePrefix = ""; if (maxGenericTypeAssignment <= info.depth) { ++maxGenericTypeAssignment; typePrefix = genModel.getImportedName("org.eclipse.emf.ecore.EGenericType") + " "; } stringBuffer.append(TEXT_444); stringBuffer.append(typePrefix); stringBuffer.append(TEXT_445); stringBuffer.append(info.depth + 1); stringBuffer.append(TEXT_446); stringBuffer.append(info.type); stringBuffer.append(TEXT_447); if (info.depth > 0) { stringBuffer.append(TEXT_448); stringBuffer.append(info.depth); stringBuffer.append(TEXT_449); stringBuffer.append(info.accessor); stringBuffer.append(TEXT_450); stringBuffer.append(info.depth + 1); stringBuffer.append(TEXT_451); } stringBuffer.append(TEXT_452); stringBuffer.append(info.depth + 1); stringBuffer.append(TEXT_453); } } } else { for (GenClassifier genException : genOperation.getGenExceptions()) { stringBuffer.append(TEXT_454); stringBuffer.append(genPackage.getPackageInstanceVariable(genException.getGenPackage())); stringBuffer.append(TEXT_455); stringBuffer.append(genException.getClassifierAccessorName()); stringBuffer.append(TEXT_456); } } if (!genOperation.isVoid() && genOperation.hasGenericType()) { for (InformationIterator i=new InformationIterator(genOperation.getEcoreOperation().getEGenericType()); i.hasNext(); ) { Information info = i.next(); String typePrefix = ""; if (maxGenericTypeAssignment <= info.depth) { ++maxGenericTypeAssignment; typePrefix = genModel.getImportedName("org.eclipse.emf.ecore.EGenericType") + " "; } stringBuffer.append(TEXT_457); stringBuffer.append(typePrefix); stringBuffer.append(TEXT_458); stringBuffer.append(info.depth + 1); stringBuffer.append(TEXT_459); stringBuffer.append(info.type); stringBuffer.append(TEXT_460); if (info.depth > 0) { stringBuffer.append(TEXT_461); stringBuffer.append(info.depth); stringBuffer.append(TEXT_462); stringBuffer.append(info.accessor); stringBuffer.append(TEXT_463); stringBuffer.append(info.depth + 1); stringBuffer.append(TEXT_464); } } stringBuffer.append(TEXT_465); } } if (c.hasNext()) { stringBuffer.append(TEXT_466); } } } if (!genPackage.getGenEnums().isEmpty()) { stringBuffer.append(TEXT_467); for (Iterator<GenEnum> e=genPackage.getGenEnums().iterator(); e.hasNext();) { GenEnum genEnum = e.next(); stringBuffer.append(TEXT_468); stringBuffer.append(genEnum.getClassifierInstanceName()); stringBuffer.append(TEXT_469); stringBuffer.append(genEnum.getImportedName()); stringBuffer.append(TEXT_470); stringBuffer.append(genEnum.getName()); stringBuffer.append(TEXT_471); stringBuffer.append(genModel.getNonNLS()); for (GenEnumLiteral genEnumLiteral : genEnum.getGenEnumLiterals()) { stringBuffer.append(TEXT_472); stringBuffer.append(genEnum.getClassifierInstanceName()); stringBuffer.append(TEXT_473); stringBuffer.append(genEnum.getImportedName().equals(genEnum.getClassifierID()) ? genEnum.getQualifiedName() : genEnum.getImportedName()); stringBuffer.append(TEXT_474); stringBuffer.append(genEnumLiteral.getEnumLiteralInstanceConstantName()); stringBuffer.append(TEXT_475); } if (e.hasNext()) { stringBuffer.append(TEXT_476); } } } if (!genPackage.getGenDataTypes().isEmpty()) { stringBuffer.append(TEXT_477); for (GenDataType genDataType : genPackage.getGenDataTypes()) {boolean hasInstanceTypeName = genModel.useGenerics() && genDataType.getEcoreDataType().getInstanceTypeName() != null && genDataType.getEcoreDataType().getInstanceTypeName().contains("<"); stringBuffer.append(TEXT_478); stringBuffer.append(genDataType.getClassifierInstanceName()); stringBuffer.append(TEXT_479); stringBuffer.append(genDataType.getRawImportedInstanceClassName()); stringBuffer.append(TEXT_480); stringBuffer.append(genDataType.getName()); stringBuffer.append(TEXT_481); stringBuffer.append(genDataType.getSerializableFlag()); stringBuffer.append(TEXT_482); stringBuffer.append(genDataType.getGeneratedInstanceClassFlag()); if (hasInstanceTypeName) { stringBuffer.append(TEXT_483); stringBuffer.append(genDataType.getEcoreDataType().getInstanceTypeName()); stringBuffer.append(TEXT_484); } stringBuffer.append(TEXT_485); stringBuffer.append(genModel.getNonNLS()); if (hasInstanceTypeName) { stringBuffer.append(genModel.getNonNLS(2)); } } } if (genPackage.getSuperGenPackage() == null) { stringBuffer.append(TEXT_486); } if (!genPackage.isEcorePackage() && !genPackage.getAnnotationSources().isEmpty()) { stringBuffer.append(TEXT_487); for (String annotationSource : genPackage.getAnnotationSources()) { stringBuffer.append(TEXT_488); stringBuffer.append(annotationSource); stringBuffer.append(TEXT_489); stringBuffer.append(genPackage.getAnnotationSourceIdentifier(annotationSource)); stringBuffer.append(TEXT_490); } } stringBuffer.append(TEXT_491); for (String annotationSource : genPackage.getAnnotationSources()) { stringBuffer.append(TEXT_492); stringBuffer.append(annotationSource); stringBuffer.append(TEXT_493); stringBuffer.append(genPackage.getAnnotationSourceIdentifier(annotationSource)); stringBuffer.append(TEXT_494); if (annotationSource == null) { stringBuffer.append(TEXT_495); } else { stringBuffer.append(TEXT_496); stringBuffer.append(annotationSource); stringBuffer.append(TEXT_497); stringBuffer.append(genModel.getNonNLS()); } for (EAnnotation eAnnotation : genPackage.getAllAnnotations()) { stringBuffer.append(TEXT_498); if (annotationSource == null ? eAnnotation.getSource() == null : annotationSource.equals(eAnnotation.getSource())) { stringBuffer.append(TEXT_499); stringBuffer.append(genPackage.getAnnotatedModelElementAccessor(eAnnotation)); stringBuffer.append(TEXT_500); for (Iterator<Map.Entry<String, String>> k = eAnnotation.getDetails().iterator(); k.hasNext();) { Map.Entry<String, String> detail = k.next(); String key = Literals.toStringLiteral(detail.getKey(), genModel); String value = Literals.toStringLiteral(detail.getValue(), genModel); stringBuffer.append(TEXT_501); stringBuffer.append(key); stringBuffer.append(TEXT_502); stringBuffer.append(value); stringBuffer.append(k.hasNext() ? "," : ""); stringBuffer.append(genModel.getNonNLS(key + value)); } stringBuffer.append(TEXT_503); } for (EAnnotation nestedEAnnotation : genPackage.getAllNestedAnnotations(eAnnotation)) {String nestedAnnotationSource = nestedEAnnotation.getSource(); int depth = 1; for (EObject eContainer = nestedEAnnotation.eContainer(); eContainer != eAnnotation; eContainer = eContainer.eContainer()) { ++depth; } stringBuffer.append(TEXT_504); stringBuffer.append(genPackage.getAnnotatedModelElementAccessor(eAnnotation)); stringBuffer.append(TEXT_505); stringBuffer.append(depth); stringBuffer.append(TEXT_506); if (nestedAnnotationSource == null) { stringBuffer.append(TEXT_507); } else { stringBuffer.append(TEXT_508); stringBuffer.append(nestedAnnotationSource); stringBuffer.append(TEXT_509); stringBuffer.append(genModel.getNonNLS()); } stringBuffer.append(TEXT_510); for (Iterator<Map.Entry<String, String>> l = nestedEAnnotation.getDetails().iterator(); l.hasNext();) { Map.Entry<String, String> detail = l.next(); String key = Literals.toStringLiteral(detail.getKey(), genModel); String value = Literals.toStringLiteral(detail.getValue(), genModel); stringBuffer.append(TEXT_511); stringBuffer.append(key); stringBuffer.append(TEXT_512); stringBuffer.append(value); stringBuffer.append(l.hasNext() ? "," : ""); stringBuffer.append(genModel.getNonNLS(key + value)); } stringBuffer.append(TEXT_513); } for (EAnnotation nestedEAnnotation : genPackage.getAllNestedAnnotations(eAnnotation)) {String nestedAnnotationSource = nestedEAnnotation.getSource(); int depth = 1; for (EObject eContainer = nestedEAnnotation.eContainer(); eContainer != eAnnotation; eContainer = eContainer.eContainer()) { ++depth; } stringBuffer.append(TEXT_514); stringBuffer.append(genPackage.getAnnotatedModelElementAccessor(eAnnotation)); stringBuffer.append(TEXT_515); stringBuffer.append(depth); stringBuffer.append(TEXT_516); if (nestedAnnotationSource == null) { stringBuffer.append(TEXT_517); } else { stringBuffer.append(TEXT_518); stringBuffer.append(nestedAnnotationSource); stringBuffer.append(TEXT_519); stringBuffer.append(genModel.getNonNLS()); } stringBuffer.append(TEXT_520); for (Iterator<Map.Entry<String, String>> l = nestedEAnnotation.getDetails().iterator(); l.hasNext();) { Map.Entry<String, String> detail = l.next(); String key = Literals.toStringLiteral(detail.getKey(), genModel); String value = Literals.toStringLiteral(detail.getValue(), genModel); stringBuffer.append(TEXT_521); stringBuffer.append(key); stringBuffer.append(TEXT_522); stringBuffer.append(value); stringBuffer.append(l.hasNext() ? "," : ""); stringBuffer.append(genModel.getNonNLS(key + value)); } stringBuffer.append(TEXT_523); } } stringBuffer.append(TEXT_524); } } else { if (genPackage.isLoadingInitialization()) { stringBuffer.append(TEXT_525); stringBuffer.append(genModel.getImportedName("java.net.URL")); stringBuffer.append(TEXT_526); stringBuffer.append(genModel.getNonNLS()); stringBuffer.append(TEXT_527); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.common.util.URI")); stringBuffer.append(TEXT_528); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.common.util.URI")); stringBuffer.append(TEXT_529); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.resource.Resource")); stringBuffer.append(TEXT_530); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.xmi.impl.EcoreResourceFactoryImpl")); stringBuffer.append(TEXT_531); stringBuffer.append(genModel.getImportedName("java.io.IOException")); stringBuffer.append(TEXT_532); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.common.util.WrappedException")); stringBuffer.append(TEXT_533); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EPackage")); stringBuffer.append(TEXT_534); } stringBuffer.append(TEXT_535); if (genModel.useClassOverrideAnnotation()) { stringBuffer.append(TEXT_536); } stringBuffer.append(TEXT_537); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EClassifier")); stringBuffer.append(TEXT_538); ArrayList<GenClass> dynamicGenClasses = new ArrayList<GenClass>(); for (GenClass genClass : genPackage.getGenClasses()) { if (genClass.isDynamic()) { dynamicGenClasses.add(genClass); } } if (dynamicGenClasses.isEmpty()) { stringBuffer.append(TEXT_539); stringBuffer.append(genPackage.getInterfacePackageName()); stringBuffer.append(TEXT_540); stringBuffer.append(genModel.getNonNLS()); stringBuffer.append(TEXT_541); } else { stringBuffer.append(TEXT_542); for (GenClass genClass : dynamicGenClasses) { if (genClass.isDynamic()) { stringBuffer.append(TEXT_543); stringBuffer.append(genPackage.getClassifierID(genClass)); stringBuffer.append(TEXT_544); } } stringBuffer.append(TEXT_545); stringBuffer.append(genPackage.getInterfacePackageName()); stringBuffer.append(TEXT_546); stringBuffer.append(genModel.getNonNLS()); stringBuffer.append(TEXT_547); } stringBuffer.append(TEXT_548); } if (needsAddEOperation) { stringBuffer.append(TEXT_549); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EOperation")); stringBuffer.append(TEXT_550); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EClass")); stringBuffer.append(TEXT_551); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EClassifier")); stringBuffer.append(TEXT_552); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EOperation")); stringBuffer.append(TEXT_553); } if (needsAddEParameter) { stringBuffer.append(TEXT_554); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EParameter")); stringBuffer.append(TEXT_555); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EOperation")); stringBuffer.append(TEXT_556); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EClassifier")); stringBuffer.append(TEXT_557); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EParameter")); stringBuffer.append(TEXT_558); } } if (isInterface && genPackage.isLiteralsInterface()) { stringBuffer.append(TEXT_559); if (isImplementation) { stringBuffer.append(TEXT_560); } stringBuffer.append(TEXT_561); for (GenClassifier genClassifier : genPackage.getGenClassifiers()) { stringBuffer.append(TEXT_562); if (genClassifier instanceof GenClass) { GenClass genClass = (GenClass)genClassifier; if (!genClass.isInterface()) { stringBuffer.append(TEXT_563); stringBuffer.append(genClass.getQualifiedClassName()); stringBuffer.append(TEXT_564); stringBuffer.append(genClass.getFormattedName()); stringBuffer.append(TEXT_565); stringBuffer.append(genClass.getQualifiedClassName()); } else { stringBuffer.append(TEXT_566); stringBuffer.append(genClass.getQualifiedInterfaceName()); stringBuffer.append(TEXT_567); stringBuffer.append(genClass.getFormattedName()); stringBuffer.append(TEXT_568); stringBuffer.append(genClass.getQualifiedInterfaceName()); } } else if (genClassifier instanceof GenEnum) { GenEnum genEnum = (GenEnum)genClassifier; stringBuffer.append(TEXT_569); stringBuffer.append(genEnum.getQualifiedName()); stringBuffer.append(TEXT_570); stringBuffer.append(genEnum.getFormattedName()); stringBuffer.append(TEXT_571); stringBuffer.append(genEnum.getQualifiedName()); } else if (genClassifier instanceof GenDataType) { GenDataType genDataType = (GenDataType)genClassifier; stringBuffer.append(TEXT_572); stringBuffer.append(genDataType.getFormattedName()); stringBuffer.append(TEXT_573); if (!genDataType.isPrimitiveType() && !genDataType.isArrayType()) { stringBuffer.append(TEXT_574); stringBuffer.append(genDataType.getRawInstanceClassName()); } } stringBuffer.append(TEXT_575); stringBuffer.append(genPackage.getQualifiedPackageClassName()); stringBuffer.append(TEXT_576); stringBuffer.append(genClassifier.getClassifierAccessorName()); stringBuffer.append(TEXT_577); stringBuffer.append(publicStaticFinalFlag); stringBuffer.append(genClassifier.getImportedMetaType()); stringBuffer.append(TEXT_578); stringBuffer.append(genPackage.getClassifierID(genClassifier)); stringBuffer.append(TEXT_579); stringBuffer.append(genClassifier.getClassifierAccessorName()); stringBuffer.append(TEXT_580); if (genClassifier instanceof GenClass) { GenClass genClass = (GenClass)genClassifier; for (GenFeature genFeature : genClass.getGenFeatures()) { stringBuffer.append(TEXT_581); stringBuffer.append(genFeature.getFormattedName()); stringBuffer.append(TEXT_582); stringBuffer.append(genFeature.getFeatureKind()); stringBuffer.append(TEXT_583); stringBuffer.append(publicStaticFinalFlag); stringBuffer.append(genFeature.getImportedMetaType()); stringBuffer.append(TEXT_584); stringBuffer.append(genClass.getFeatureID(genFeature)); stringBuffer.append(TEXT_585); stringBuffer.append(genFeature.getFeatureAccessorName()); stringBuffer.append(TEXT_586); } } } stringBuffer.append(TEXT_587); } stringBuffer.append(TEXT_588); stringBuffer.append(isInterface ? genPackage.getPackageInterfaceName() : genPackage.getPackageClassName()); genModel.emitSortedImports(); stringBuffer.append(TEXT_589); return stringBuffer.toString(); } }
false
true
public String generate(Object argument) { final StringBuffer stringBuffer = new StringBuffer(); /** * <copyright> * * Copyright (c) 2002-2006 IBM Corporation and others. * 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 * * Contributors: * IBM - Initial API and implementation * * </copyright> */ final GenPackage genPackage = (GenPackage)((Object[])argument)[0]; final GenModel genModel=genPackage.getGenModel(); boolean isInterface = Boolean.TRUE.equals(((Object[])argument)[1]); boolean isImplementation = Boolean.TRUE.equals(((Object[])argument)[2]); String publicStaticFinalFlag = isImplementation ? "public static final " : ""; boolean needsAddEOperation = false; boolean needsAddEParameter = false; stringBuffer.append(TEXT_1); stringBuffer.append(TEXT_2); {GenBase copyrightHolder = argument instanceof GenBase ? (GenBase)argument : argument instanceof Object[] && ((Object[])argument)[0] instanceof GenBase ? (GenBase)((Object[])argument)[0] : null; if (copyrightHolder != null && copyrightHolder.hasCopyright()) { stringBuffer.append(TEXT_3); stringBuffer.append(copyrightHolder.getCopyright(copyrightHolder.getGenModel().getIndentation(stringBuffer))); } else { stringBuffer.append(TEXT_4); }} stringBuffer.append(TEXT_5); stringBuffer.append("$"); stringBuffer.append(TEXT_6); stringBuffer.append("$"); stringBuffer.append(TEXT_7); if (isImplementation && !genModel.isSuppressInterfaces()) { stringBuffer.append(TEXT_8); stringBuffer.append(genPackage.getClassPackageName()); stringBuffer.append(TEXT_9); } else { stringBuffer.append(TEXT_10); stringBuffer.append(genPackage.getReflectionPackageName()); stringBuffer.append(TEXT_11); } stringBuffer.append(TEXT_12); genModel.markImportLocation(stringBuffer, genPackage); if (isImplementation) { genModel.addPseudoImport("org.eclipse.emf.ecore.EPackage.Registry"); genModel.addPseudoImport("org.eclipse.emf.ecore.EPackage.Descriptor"); if (genPackage.isLiteralsInterface()) { genModel.addPseudoImport(genPackage.getQualifiedPackageInterfaceName() + ".Literals"); } for (GenClassifier genClassifier : genPackage.getOrderedGenClassifiers()) genModel.addPseudoImport(genPackage.getQualifiedPackageInterfaceName() + "." + genPackage.getClassifierID(genClassifier)); } if (isInterface) { stringBuffer.append(TEXT_13); if (genPackage.hasDocumentation()) { stringBuffer.append(TEXT_14); stringBuffer.append(genPackage.getDocumentation(genModel.getIndentation(stringBuffer))); stringBuffer.append(TEXT_15); } stringBuffer.append(TEXT_16); stringBuffer.append(genPackage.getQualifiedFactoryInterfaceName()); if (!genModel.isSuppressEMFModelTags()) { boolean first = true; for (StringTokenizer stringTokenizer = new StringTokenizer(genPackage.getModelInfo(), "\n\r"); stringTokenizer.hasMoreTokens(); ) { String modelInfo = stringTokenizer.nextToken(); if (first) { first = false; stringBuffer.append(TEXT_17); stringBuffer.append(modelInfo); } else { stringBuffer.append(TEXT_18); stringBuffer.append(modelInfo); }} if (first) { stringBuffer.append(TEXT_19); }} stringBuffer.append(TEXT_20); } else { stringBuffer.append(TEXT_21); } if (isImplementation) { stringBuffer.append(TEXT_22); stringBuffer.append(genPackage.getPackageClassName()); stringBuffer.append(TEXT_23); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.impl.EPackageImpl")); if (!isInterface){ stringBuffer.append(TEXT_24); stringBuffer.append(genPackage.getImportedPackageInterfaceName()); } } else { stringBuffer.append(TEXT_25); stringBuffer.append(genPackage.getPackageInterfaceName()); stringBuffer.append(TEXT_26); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EPackage")); } stringBuffer.append(TEXT_27); if (genModel.hasCopyrightField()) { stringBuffer.append(TEXT_28); stringBuffer.append(publicStaticFinalFlag); stringBuffer.append(genModel.getImportedName("java.lang.String")); stringBuffer.append(TEXT_29); stringBuffer.append(genModel.getCopyrightFieldLiteral()); stringBuffer.append(TEXT_30); stringBuffer.append(genModel.getNonNLS()); stringBuffer.append(TEXT_31); } if (isInterface) { stringBuffer.append(TEXT_32); stringBuffer.append(publicStaticFinalFlag); stringBuffer.append(genModel.getImportedName("java.lang.String")); stringBuffer.append(TEXT_33); stringBuffer.append(genPackage.getPackageName()); stringBuffer.append(TEXT_34); stringBuffer.append(genModel.getNonNLS()); stringBuffer.append(TEXT_35); stringBuffer.append(publicStaticFinalFlag); stringBuffer.append(genModel.getImportedName("java.lang.String")); stringBuffer.append(TEXT_36); stringBuffer.append(genPackage.getNSURI()); stringBuffer.append(TEXT_37); stringBuffer.append(genModel.getNonNLS()); stringBuffer.append(TEXT_38); stringBuffer.append(publicStaticFinalFlag); stringBuffer.append(genModel.getImportedName("java.lang.String")); stringBuffer.append(TEXT_39); stringBuffer.append(genPackage.getNSName()); stringBuffer.append(TEXT_40); stringBuffer.append(genModel.getNonNLS()); if (genPackage.isContentType()) { stringBuffer.append(TEXT_41); stringBuffer.append(publicStaticFinalFlag); stringBuffer.append(genModel.getImportedName("java.lang.String")); stringBuffer.append(TEXT_42); stringBuffer.append(genPackage.getContentTypeIdentifier()); stringBuffer.append(TEXT_43); stringBuffer.append(genModel.getNonNLS()); } stringBuffer.append(TEXT_44); stringBuffer.append(publicStaticFinalFlag); stringBuffer.append(genPackage.getPackageInterfaceName()); stringBuffer.append(TEXT_45); stringBuffer.append(genPackage.getQualifiedPackageClassName()); stringBuffer.append(TEXT_46); for (GenClassifier genClassifier : genPackage.getOrderedGenClassifiers()) { stringBuffer.append(TEXT_47); if (genClassifier instanceof GenClass) { GenClass genClass = (GenClass)genClassifier; if (!genClass.isInterface()) { stringBuffer.append(TEXT_48); stringBuffer.append(genClass.getQualifiedClassName()); stringBuffer.append(TEXT_49); stringBuffer.append(genClass.getFormattedName()); stringBuffer.append(TEXT_50); stringBuffer.append(genClass.getQualifiedClassName()); } else { stringBuffer.append(TEXT_51); stringBuffer.append(genClass.getQualifiedInterfaceName()); stringBuffer.append(TEXT_52); stringBuffer.append(genClass.getFormattedName()); stringBuffer.append(TEXT_53); stringBuffer.append(genClass.getQualifiedInterfaceName()); } } else if (genClassifier instanceof GenEnum) { GenEnum genEnum = (GenEnum)genClassifier; stringBuffer.append(TEXT_54); stringBuffer.append(genEnum.getQualifiedName()); stringBuffer.append(TEXT_55); stringBuffer.append(genEnum.getFormattedName()); stringBuffer.append(TEXT_56); stringBuffer.append(genEnum.getQualifiedName()); } else if (genClassifier instanceof GenDataType) { GenDataType genDataType = (GenDataType)genClassifier; stringBuffer.append(TEXT_57); stringBuffer.append(genDataType.getFormattedName()); stringBuffer.append(TEXT_58); if (!genDataType.isPrimitiveType() && !genDataType.isArrayType()) { stringBuffer.append(TEXT_59); stringBuffer.append(genDataType.getRawInstanceClassName()); } } stringBuffer.append(TEXT_60); stringBuffer.append(genPackage.getQualifiedPackageClassName()); stringBuffer.append(TEXT_61); stringBuffer.append(genClassifier.getClassifierAccessorName()); stringBuffer.append(TEXT_62); stringBuffer.append(publicStaticFinalFlag); stringBuffer.append(TEXT_63); stringBuffer.append(genPackage.getClassifierID(genClassifier)); stringBuffer.append(TEXT_64); stringBuffer.append(genPackage.getClassifierValue(genClassifier)); stringBuffer.append(TEXT_65); if (genClassifier instanceof GenClass) { GenClass genClass = (GenClass)genClassifier; for (GenFeature genFeature : genClass.getAllGenFeatures()) { stringBuffer.append(TEXT_66); stringBuffer.append(genFeature.getFormattedName()); stringBuffer.append(TEXT_67); stringBuffer.append(genFeature.getFeatureKind()); stringBuffer.append(TEXT_68); stringBuffer.append(publicStaticFinalFlag); stringBuffer.append(TEXT_69); stringBuffer.append(genClass.getFeatureID(genFeature)); stringBuffer.append(TEXT_70); stringBuffer.append(genClass.getFeatureValue(genFeature)); stringBuffer.append(TEXT_71); } stringBuffer.append(TEXT_72); stringBuffer.append(genClass.getFormattedName()); stringBuffer.append(TEXT_73); stringBuffer.append(publicStaticFinalFlag); stringBuffer.append(TEXT_74); stringBuffer.append(genClass.getFeatureCountID()); stringBuffer.append(TEXT_75); stringBuffer.append(genClass.getFeatureCountValue()); stringBuffer.append(TEXT_76); } } } if (isImplementation) { if (genPackage.isLoadingInitialization()) { stringBuffer.append(TEXT_77); stringBuffer.append(genPackage.getSerializedPackageFilename()); stringBuffer.append(TEXT_78); stringBuffer.append(genModel.getNonNLS()); stringBuffer.append(TEXT_79); } for (GenClassifier genClassifier : genPackage.getGenClassifiers()) { stringBuffer.append(TEXT_80); stringBuffer.append(genClassifier.getImportedMetaType()); stringBuffer.append(TEXT_81); stringBuffer.append(genClassifier.getClassifierInstanceName()); stringBuffer.append(TEXT_82); } stringBuffer.append(TEXT_83); stringBuffer.append(genPackage.getQualifiedPackageInterfaceName()); stringBuffer.append(TEXT_84); stringBuffer.append(genPackage.getPackageClassName()); stringBuffer.append(TEXT_85); stringBuffer.append(genPackage.getQualifiedEFactoryInstanceAccessor()); stringBuffer.append(TEXT_86); if (!genPackage.isLoadedInitialization()) { stringBuffer.append(TEXT_87); } stringBuffer.append(TEXT_88); stringBuffer.append(genPackage.getImportedPackageInterfaceName()); stringBuffer.append(TEXT_89); stringBuffer.append(genPackage.getImportedPackageInterfaceName()); stringBuffer.append(TEXT_90); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EPackage")); stringBuffer.append(TEXT_91); stringBuffer.append(genPackage.getImportedPackageInterfaceName()); stringBuffer.append(TEXT_92); stringBuffer.append(genPackage.getPackageClassName()); stringBuffer.append(TEXT_93); stringBuffer.append(genPackage.getPackageInterfaceName()); stringBuffer.append(TEXT_94); stringBuffer.append(genPackage.getPackageClassName()); stringBuffer.append(TEXT_95); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EPackage")); stringBuffer.append(TEXT_96); stringBuffer.append(genPackage.getPackageClassName()); stringBuffer.append(TEXT_97); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EPackage")); stringBuffer.append(TEXT_98); stringBuffer.append(genPackage.getPackageClassName()); stringBuffer.append(TEXT_99); if (!genPackage.getPackageSimpleDependencies().isEmpty()) { stringBuffer.append(TEXT_100); for (GenPackage dep : genPackage.getPackageSimpleDependencies()) { stringBuffer.append(TEXT_101); stringBuffer.append(dep.getImportedPackageInterfaceName()); stringBuffer.append(TEXT_102); } stringBuffer.append(TEXT_103); } if (!genPackage.getPackageInterDependencies().isEmpty()) { stringBuffer.append(TEXT_104); for (GenPackage interdep : genPackage.getPackageInterDependencies()) { stringBuffer.append(TEXT_105); stringBuffer.append(interdep.getImportedPackageClassName()); stringBuffer.append(TEXT_106); stringBuffer.append(genPackage.getPackageInstanceVariable(interdep)); stringBuffer.append(TEXT_107); stringBuffer.append(interdep.getImportedPackageClassName()); stringBuffer.append(TEXT_108); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EPackage")); stringBuffer.append(TEXT_109); stringBuffer.append(interdep.getImportedPackageInterfaceName()); stringBuffer.append(TEXT_110); stringBuffer.append(interdep.getImportedPackageClassName()); stringBuffer.append(TEXT_111); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EPackage")); stringBuffer.append(TEXT_112); stringBuffer.append(interdep.getImportedPackageInterfaceName()); stringBuffer.append(TEXT_113); stringBuffer.append(interdep.getImportedPackageInterfaceName()); stringBuffer.append(TEXT_114); } stringBuffer.append(TEXT_115); } if (genPackage.isLoadedInitialization() || !genPackage.getPackageLoadInterDependencies().isEmpty()) { stringBuffer.append(TEXT_116); if (genPackage.isLoadingInitialization()) { stringBuffer.append(TEXT_117); stringBuffer.append(genPackage.getPackageInterfaceName()); stringBuffer.append(TEXT_118); } for (GenPackage interdep : genPackage.getPackageLoadInterDependencies()) { if (interdep.isLoadingInitialization()) { stringBuffer.append(TEXT_119); stringBuffer.append(genPackage.getPackageInstanceVariable(interdep)); stringBuffer.append(TEXT_120); } } stringBuffer.append(TEXT_121); } if (!genPackage.isLoadedInitialization() || !genPackage.getPackageBuildInterDependencies().isEmpty()) { stringBuffer.append(TEXT_122); if (!genPackage.isLoadedInitialization()) { stringBuffer.append(TEXT_123); stringBuffer.append(genPackage.getPackageInterfaceName()); stringBuffer.append(TEXT_124); } for (GenPackage interdep : genPackage.getPackageBuildInterDependencies()) { stringBuffer.append(TEXT_125); stringBuffer.append(genPackage.getPackageInstanceVariable(interdep)); stringBuffer.append(TEXT_126); } stringBuffer.append(TEXT_127); if (!genPackage.isLoadedInitialization()) { stringBuffer.append(TEXT_128); stringBuffer.append(genPackage.getPackageInterfaceName()); stringBuffer.append(TEXT_129); } for (GenPackage interdep : genPackage.getPackageBuildInterDependencies()) { stringBuffer.append(TEXT_130); stringBuffer.append(genPackage.getPackageInstanceVariable(interdep)); stringBuffer.append(TEXT_131); } stringBuffer.append(TEXT_132); } if (genPackage.isLoadedInitialization() || !genPackage.getPackageLoadInterDependencies().isEmpty()) { stringBuffer.append(TEXT_133); if (genPackage.isLoadedInitialization()) { stringBuffer.append(TEXT_134); stringBuffer.append(genPackage.getPackageInterfaceName()); stringBuffer.append(TEXT_135); } for (GenPackage interdep : genPackage.getPackageLoadInterDependencies()) { stringBuffer.append(TEXT_136); stringBuffer.append(genPackage.getPackageInstanceVariable(interdep)); stringBuffer.append(TEXT_137); } stringBuffer.append(TEXT_138); } if (genPackage.hasConstraints()) { stringBuffer.append(TEXT_139); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EValidator")); stringBuffer.append(TEXT_140); stringBuffer.append(genPackage.getPackageInterfaceName()); stringBuffer.append(TEXT_141); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EValidator")); stringBuffer.append(TEXT_142); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EValidator")); stringBuffer.append(TEXT_143); stringBuffer.append(genPackage.getImportedValidatorClassName()); stringBuffer.append(TEXT_144); } if (!genPackage.isEcorePackage()) { stringBuffer.append(TEXT_145); stringBuffer.append(genPackage.getPackageInterfaceName()); stringBuffer.append(TEXT_146); } stringBuffer.append(TEXT_147); stringBuffer.append(genPackage.getPackageInterfaceName()); stringBuffer.append(TEXT_148); } if (isInterface) { // TODO REMOVE THIS BOGUS EMPTY LINE stringBuffer.append(TEXT_149); } for (GenClassifier genClassifier : genPackage.getGenClassifiers()) { if (isInterface) { stringBuffer.append(TEXT_150); if (genClassifier instanceof GenClass) { GenClass genClass = (GenClass)genClassifier; stringBuffer.append(TEXT_151); stringBuffer.append(genClass.getQualifiedInterfaceName()); stringBuffer.append(TEXT_152); stringBuffer.append(genClass.getFormattedName()); stringBuffer.append(TEXT_153); stringBuffer.append(genClass.getFormattedName()); stringBuffer.append(TEXT_154); stringBuffer.append(genClass.getQualifiedInterfaceName()); if (!genModel.isSuppressEMFModelTags() && (genClass.isExternalInterface() || genClass.isDynamic())) { boolean first = true; for (StringTokenizer stringTokenizer = new StringTokenizer(genClass.getModelInfo(), "\n\r"); stringTokenizer.hasMoreTokens(); ) { String modelInfo = stringTokenizer.nextToken(); if (first) { first = false; stringBuffer.append(TEXT_155); stringBuffer.append(modelInfo); } else { stringBuffer.append(TEXT_156); stringBuffer.append(modelInfo); }} if (first) { stringBuffer.append(TEXT_157); }} } else if (genClassifier instanceof GenEnum) { GenEnum genEnum = (GenEnum)genClassifier; stringBuffer.append(TEXT_158); stringBuffer.append(genEnum.getQualifiedName()); stringBuffer.append(TEXT_159); stringBuffer.append(genEnum.getFormattedName()); stringBuffer.append(TEXT_160); stringBuffer.append(genEnum.getFormattedName()); stringBuffer.append(TEXT_161); stringBuffer.append(genEnum.getQualifiedName()); } else if (genClassifier instanceof GenDataType) { GenDataType genDataType = (GenDataType)genClassifier; if (genDataType.isPrimitiveType() || genDataType.isArrayType()) { stringBuffer.append(TEXT_162); stringBuffer.append(genDataType.getFormattedName()); stringBuffer.append(TEXT_163); } else { stringBuffer.append(TEXT_164); stringBuffer.append(genDataType.getRawInstanceClassName()); stringBuffer.append(TEXT_165); stringBuffer.append(genDataType.getFormattedName()); stringBuffer.append(TEXT_166); } stringBuffer.append(TEXT_167); stringBuffer.append(genDataType.getFormattedName()); stringBuffer.append(TEXT_168); if (!genDataType.isPrimitiveType() && !genDataType.isArrayType()) { stringBuffer.append(TEXT_169); stringBuffer.append(genDataType.getRawInstanceClassName()); } if (!genModel.isSuppressEMFModelTags()) {boolean first = true; for (StringTokenizer stringTokenizer = new StringTokenizer(genDataType.getModelInfo(), "\n\r"); stringTokenizer.hasMoreTokens(); ) { String modelInfo = stringTokenizer.nextToken(); if (first) { first = false; stringBuffer.append(TEXT_170); stringBuffer.append(modelInfo); } else { stringBuffer.append(TEXT_171); stringBuffer.append(modelInfo); }} if (first) { stringBuffer.append(TEXT_172); }} } stringBuffer.append(TEXT_173); } else { stringBuffer.append(TEXT_174); } if (isImplementation) { stringBuffer.append(TEXT_175); stringBuffer.append(genClassifier.getImportedMetaType()); stringBuffer.append(TEXT_176); stringBuffer.append(genClassifier.getClassifierAccessorName()); stringBuffer.append(TEXT_177); if (genPackage.isLoadedInitialization()) { stringBuffer.append(TEXT_178); stringBuffer.append(genClassifier.getClassifierInstanceName()); stringBuffer.append(TEXT_179); stringBuffer.append(genClassifier.getClassifierInstanceName()); stringBuffer.append(TEXT_180); stringBuffer.append(genClassifier.getImportedMetaType()); stringBuffer.append(TEXT_181); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EPackage")); stringBuffer.append(TEXT_182); stringBuffer.append(genPackage.getImportedPackageInterfaceName()); stringBuffer.append(TEXT_183); stringBuffer.append(genPackage.getLocalClassifierIndex(genClassifier)); stringBuffer.append(TEXT_184); } stringBuffer.append(TEXT_185); stringBuffer.append(genClassifier.getClassifierInstanceName()); stringBuffer.append(TEXT_186); } else { stringBuffer.append(TEXT_187); stringBuffer.append(genClassifier.getImportedMetaType()); stringBuffer.append(TEXT_188); stringBuffer.append(genClassifier.getClassifierAccessorName()); stringBuffer.append(TEXT_189); } if (genClassifier instanceof GenClass) { GenClass genClass = (GenClass)genClassifier; for (GenFeature genFeature : genClass.getGenFeatures()) { if (isInterface) { stringBuffer.append(TEXT_190); stringBuffer.append(genFeature.getFeatureKind()); stringBuffer.append(TEXT_191); stringBuffer.append(genClass.getQualifiedInterfaceName()); if (!genClass.isMapEntry() && !genFeature.isSuppressedGetVisibility()) { stringBuffer.append(TEXT_192); stringBuffer.append(genFeature.getGetAccessor()); } stringBuffer.append(TEXT_193); stringBuffer.append(genFeature.getFormattedName()); stringBuffer.append(TEXT_194); stringBuffer.append(genFeature.getFeatureKind()); stringBuffer.append(TEXT_195); stringBuffer.append(genFeature.getFormattedName()); stringBuffer.append(TEXT_196); stringBuffer.append(genClass.getQualifiedInterfaceName()); if (!genClass.isMapEntry() && !genFeature.isSuppressedGetVisibility()) { stringBuffer.append(TEXT_197); stringBuffer.append(genFeature.getGetAccessor()); stringBuffer.append(TEXT_198); } stringBuffer.append(TEXT_199); stringBuffer.append(genClass.getClassifierAccessorName()); stringBuffer.append(TEXT_200); } else { stringBuffer.append(TEXT_201); } if (isImplementation) { stringBuffer.append(TEXT_202); stringBuffer.append(genFeature.getImportedMetaType()); stringBuffer.append(TEXT_203); stringBuffer.append(genFeature.getFeatureAccessorName()); stringBuffer.append(TEXT_204); if (!genPackage.isLoadedInitialization()) { stringBuffer.append(TEXT_205); stringBuffer.append(genFeature.getImportedMetaType()); stringBuffer.append(TEXT_206); stringBuffer.append(genClass.getClassifierInstanceName()); stringBuffer.append(TEXT_207); stringBuffer.append(genClass.getLocalFeatureIndex(genFeature)); stringBuffer.append(TEXT_208); } else { stringBuffer.append(TEXT_209); stringBuffer.append(genFeature.getImportedMetaType()); stringBuffer.append(TEXT_210); stringBuffer.append(genClassifier.getClassifierAccessorName()); stringBuffer.append(TEXT_211); stringBuffer.append(genClass.getLocalFeatureIndex(genFeature)); stringBuffer.append(TEXT_212); } stringBuffer.append(TEXT_213); } else { stringBuffer.append(TEXT_214); stringBuffer.append(genFeature.getImportedMetaType()); stringBuffer.append(TEXT_215); stringBuffer.append(genFeature.getFeatureAccessorName()); stringBuffer.append(TEXT_216); } stringBuffer.append(TEXT_217); } } } if (isInterface) { stringBuffer.append(TEXT_218); } else { stringBuffer.append(TEXT_219); } if (isImplementation) { stringBuffer.append(TEXT_220); stringBuffer.append(genPackage.getImportedFactoryInterfaceName()); stringBuffer.append(TEXT_221); stringBuffer.append(genPackage.getFactoryInterfaceName()); stringBuffer.append(TEXT_222); stringBuffer.append(genPackage.getImportedFactoryInterfaceName()); stringBuffer.append(TEXT_223); } else { stringBuffer.append(TEXT_224); stringBuffer.append(genPackage.getFactoryInterfaceName()); stringBuffer.append(TEXT_225); stringBuffer.append(genPackage.getFactoryInterfaceName()); stringBuffer.append(TEXT_226); } stringBuffer.append(TEXT_227); if (isImplementation) { if (!genPackage.isLoadedInitialization()) { stringBuffer.append(TEXT_228); if (!genPackage.getGenClasses().isEmpty()) { stringBuffer.append(TEXT_229); for (Iterator<GenClass> c=genPackage.getGenClasses().iterator(); c.hasNext();) { GenClass genClass = c.next(); stringBuffer.append(TEXT_230); stringBuffer.append(genClass.getClassifierInstanceName()); stringBuffer.append(TEXT_231); stringBuffer.append(genClass.getMetaType()); stringBuffer.append(TEXT_232); stringBuffer.append(genClass.getClassifierID()); stringBuffer.append(TEXT_233); for (GenFeature genFeature : genClass.getGenFeatures()) { stringBuffer.append(TEXT_234); stringBuffer.append(genFeature.getMetaType()); stringBuffer.append(TEXT_235); stringBuffer.append(genClass.getClassifierInstanceName()); stringBuffer.append(TEXT_236); stringBuffer.append(genClass.getFeatureID(genFeature)); stringBuffer.append(TEXT_237); } if (c.hasNext()) { stringBuffer.append(TEXT_238); } } } if (!genPackage.getGenEnums().isEmpty()) { stringBuffer.append(TEXT_239); for (GenEnum genEnum : genPackage.getGenEnums()) { stringBuffer.append(TEXT_240); stringBuffer.append(genEnum.getClassifierInstanceName()); stringBuffer.append(TEXT_241); stringBuffer.append(genEnum.getClassifierID()); stringBuffer.append(TEXT_242); } } if (!genPackage.getGenDataTypes().isEmpty()) { stringBuffer.append(TEXT_243); for (GenDataType genDataType : genPackage.getGenDataTypes()) { stringBuffer.append(TEXT_244); stringBuffer.append(genDataType.getClassifierInstanceName()); stringBuffer.append(TEXT_245); stringBuffer.append(genDataType.getClassifierID()); stringBuffer.append(TEXT_246); } } stringBuffer.append(TEXT_247); /////////////////////// class Information { @SuppressWarnings("unused") EGenericType eGenericType; int depth; String type; String accessor; } class InformationIterator { Iterator<?> iterator; InformationIterator(EGenericType eGenericType) { iterator = EcoreUtil.getAllContents(Collections.singleton(eGenericType)); } boolean hasNext() { return iterator.hasNext(); } Information next() { Information information = new Information(); EGenericType eGenericType = information.eGenericType = (EGenericType)iterator.next(); for (EObject container = eGenericType.eContainer(); container instanceof EGenericType; container = container.eContainer()) { ++information.depth; } if (eGenericType.getEClassifier() != null ) { GenClassifier genClassifier = genModel.findGenClassifier(eGenericType.getEClassifier()); information.type = genPackage.getPackageInstanceVariable(genClassifier.getGenPackage()) + ".get" + genClassifier.getClassifierAccessorName() + "()"; } else if (eGenericType.getETypeParameter() != null) { ETypeParameter eTypeParameter = eGenericType.getETypeParameter(); if (eTypeParameter.eContainer() instanceof EClass) { information.type = genModel.findGenClassifier((EClass)eTypeParameter.eContainer()).getClassifierInstanceName() + "_" + eGenericType.getETypeParameter().getName(); } else { information.type = "t" + (((EOperation)eTypeParameter.eContainer()).getETypeParameters().indexOf(eTypeParameter) + 1); } } else { information.type =""; } if (information.depth > 0) { if (eGenericType.eContainmentFeature().isMany()) { information.accessor = "getE" + eGenericType.eContainmentFeature().getName().substring(1) + "().add"; } else { information.accessor = "setE" + eGenericType.eContainmentFeature().getName().substring(1); } } return information; } } /////////////////////// int maxGenericTypeAssignment = 0; stringBuffer.append(TEXT_248); if (!genPackage.getPackageInitializationDependencies().isEmpty()) { stringBuffer.append(TEXT_249); for (GenPackage dep : genPackage.getPackageInitializationDependencies()) { stringBuffer.append(TEXT_250); stringBuffer.append(dep.getImportedPackageInterfaceName()); stringBuffer.append(TEXT_251); stringBuffer.append(genPackage.getPackageInstanceVariable(dep)); stringBuffer.append(TEXT_252); stringBuffer.append(dep.getImportedPackageInterfaceName()); stringBuffer.append(TEXT_253); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EPackage")); stringBuffer.append(TEXT_254); stringBuffer.append(dep.getImportedPackageInterfaceName()); stringBuffer.append(TEXT_255); } } if (!genPackage.getSubGenPackages().isEmpty()) { stringBuffer.append(TEXT_256); for (GenPackage sub : genPackage.getSubGenPackages()) { stringBuffer.append(TEXT_257); stringBuffer.append(genPackage.getPackageInstanceVariable(sub)); stringBuffer.append(TEXT_258); } } if (!genPackage.getGenClasses().isEmpty()) { boolean firstOperationAssignment = true; int maxTypeParameterAssignment = 0; if (genModel.useGenerics()) { stringBuffer.append(TEXT_259); for (GenClassifier genClassifier : genPackage.getGenClassifiers()) { for (GenTypeParameter genTypeParameter : genClassifier.getGenTypeParameters()) { if (!genTypeParameter.getEcoreTypeParameter().getEBounds().isEmpty() || genTypeParameter.isUsed()) { stringBuffer.append(TEXT_260); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.ETypeParameter")); stringBuffer.append(TEXT_261); stringBuffer.append(genClassifier.getClassifierInstanceName()); stringBuffer.append(TEXT_262); stringBuffer.append(genTypeParameter.getName()); stringBuffer.append(TEXT_263); stringBuffer.append(genClassifier.getClassifierInstanceName()); stringBuffer.append(TEXT_264); stringBuffer.append(genTypeParameter.getName()); stringBuffer.append(TEXT_265); stringBuffer.append(genModel.getNonNLS()); } else { stringBuffer.append(TEXT_266); stringBuffer.append(genClassifier.getClassifierInstanceName()); stringBuffer.append(TEXT_267); stringBuffer.append(genTypeParameter.getName()); stringBuffer.append(TEXT_268); stringBuffer.append(genModel.getNonNLS()); } } } } if (genModel.useGenerics()) { stringBuffer.append(TEXT_269); for (GenClassifier genClassifier : genPackage.getGenClassifiers()) { for (GenTypeParameter genTypeParameter : genClassifier.getGenTypeParameters()) { for (EGenericType bound : genTypeParameter.getEcoreTypeParameter().getEBounds()) { for (InformationIterator i=new InformationIterator(bound); i.hasNext(); ) { Information info = i.next(); String prefix = ""; if (maxGenericTypeAssignment <= info.depth) { ++maxGenericTypeAssignment; prefix = genModel.getImportedName("org.eclipse.emf.ecore.EGenericType") + " "; } stringBuffer.append(TEXT_270); stringBuffer.append(prefix); stringBuffer.append(TEXT_271); stringBuffer.append(info.depth + 1); stringBuffer.append(TEXT_272); stringBuffer.append(info.type); stringBuffer.append(TEXT_273); if (info.depth > 0) { stringBuffer.append(TEXT_274); stringBuffer.append(info.depth); stringBuffer.append(TEXT_275); stringBuffer.append(info.accessor); stringBuffer.append(TEXT_276); stringBuffer.append(info.depth + 1); stringBuffer.append(TEXT_277); } } stringBuffer.append(TEXT_278); stringBuffer.append(genClassifier.getClassifierInstanceName()); stringBuffer.append(TEXT_279); stringBuffer.append(genTypeParameter.getName()); stringBuffer.append(TEXT_280); } } } } stringBuffer.append(TEXT_281); for (GenClass genClass : genPackage.getGenClasses()) { if (!genClass.hasGenericSuperTypes()) { for (GenClass baseGenClass : genClass.getBaseGenClasses()) { stringBuffer.append(TEXT_282); stringBuffer.append(genClass.getClassifierInstanceName()); stringBuffer.append(TEXT_283); stringBuffer.append(genPackage.getPackageInstanceVariable(baseGenClass.getGenPackage())); stringBuffer.append(TEXT_284); stringBuffer.append(baseGenClass.getClassifierAccessorName()); stringBuffer.append(TEXT_285); } } else { for (EGenericType superType : genClass.getEcoreClass().getEGenericSuperTypes()) { for (InformationIterator i=new InformationIterator(superType); i.hasNext(); ) { Information info = i.next(); String prefix = ""; if (maxGenericTypeAssignment <= info.depth) { ++maxGenericTypeAssignment; prefix = genModel.getImportedName("org.eclipse.emf.ecore.EGenericType") + " "; } stringBuffer.append(TEXT_286); stringBuffer.append(prefix); stringBuffer.append(TEXT_287); stringBuffer.append(info.depth + 1); stringBuffer.append(TEXT_288); stringBuffer.append(info.type); stringBuffer.append(TEXT_289); if (info.depth > 0) { stringBuffer.append(TEXT_290); stringBuffer.append(info.depth); stringBuffer.append(TEXT_291); stringBuffer.append(info.accessor); stringBuffer.append(TEXT_292); stringBuffer.append(info.depth + 1); stringBuffer.append(TEXT_293); } } stringBuffer.append(TEXT_294); stringBuffer.append(genClass.getClassifierInstanceName()); stringBuffer.append(TEXT_295); } } } stringBuffer.append(TEXT_296); for (Iterator<GenClass> c=genPackage.getGenClasses().iterator(); c.hasNext();) { GenClass genClass = c.next(); boolean hasInstanceTypeName = genModel.useGenerics() && genClass.getEcoreClass().getInstanceTypeName() != null && genClass.getEcoreClass().getInstanceTypeName().contains("<"); stringBuffer.append(TEXT_297); stringBuffer.append(genClass.getClassifierInstanceName()); stringBuffer.append(TEXT_298); if (genClass.isDynamic()) { stringBuffer.append(TEXT_299); } else { stringBuffer.append(genClass.getRawImportedInterfaceName()); stringBuffer.append(TEXT_300); } stringBuffer.append(TEXT_301); stringBuffer.append(genClass.getName()); stringBuffer.append(TEXT_302); stringBuffer.append(genClass.getAbstractFlag()); stringBuffer.append(TEXT_303); stringBuffer.append(genClass.getInterfaceFlag()); stringBuffer.append(TEXT_304); stringBuffer.append(genClass.getGeneratedInstanceClassFlag()); if (hasInstanceTypeName) { stringBuffer.append(TEXT_305); stringBuffer.append(genClass.getEcoreClass().getInstanceTypeName()); stringBuffer.append(TEXT_306); } stringBuffer.append(TEXT_307); stringBuffer.append(genModel.getNonNLS()); if (hasInstanceTypeName) { stringBuffer.append(genModel.getNonNLS(2)); } for (GenFeature genFeature : genClass.getGenFeatures()) { if (genFeature.hasGenericType()) { for (InformationIterator i=new InformationIterator(genFeature.getEcoreFeature().getEGenericType()); i.hasNext(); ) { Information info = i.next(); String prefix = ""; if (maxGenericTypeAssignment <= info.depth) { ++maxGenericTypeAssignment; prefix = genModel.getImportedName("org.eclipse.emf.ecore.EGenericType") + " "; } stringBuffer.append(TEXT_308); stringBuffer.append(prefix); stringBuffer.append(TEXT_309); stringBuffer.append(info.depth + 1); stringBuffer.append(TEXT_310); stringBuffer.append(info.type); stringBuffer.append(TEXT_311); if (info.depth > 0) { stringBuffer.append(TEXT_312); stringBuffer.append(info.depth); stringBuffer.append(TEXT_313); stringBuffer.append(info.accessor); stringBuffer.append(TEXT_314); stringBuffer.append(info.depth + 1); stringBuffer.append(TEXT_315); } } } if (genFeature.isReferenceType()) { GenFeature reverseGenFeature = genFeature.getReverse(); String reverse = reverseGenFeature == null ? "null" : genPackage.getPackageInstanceVariable(reverseGenFeature.getGenPackage()) + ".get" + reverseGenFeature.getFeatureAccessorName() + "()"; stringBuffer.append(TEXT_316); stringBuffer.append(genFeature.getFeatureAccessorName()); stringBuffer.append(TEXT_317); if (genFeature.hasGenericType()) { stringBuffer.append(TEXT_318); } else { stringBuffer.append(genPackage.getPackageInstanceVariable(genFeature.getTypeGenPackage())); stringBuffer.append(TEXT_319); stringBuffer.append(genFeature.getTypeClassifierAccessorName()); stringBuffer.append(TEXT_320); } stringBuffer.append(TEXT_321); stringBuffer.append(reverse); stringBuffer.append(TEXT_322); stringBuffer.append(genFeature.getName()); stringBuffer.append(TEXT_323); stringBuffer.append(genFeature.getDefaultValue()); stringBuffer.append(TEXT_324); stringBuffer.append(genFeature.getLowerBound()); stringBuffer.append(TEXT_325); stringBuffer.append(genFeature.getUpperBound()); stringBuffer.append(TEXT_326); stringBuffer.append(genFeature.getContainerClass()); stringBuffer.append(TEXT_327); stringBuffer.append(genFeature.getTransientFlag()); stringBuffer.append(TEXT_328); stringBuffer.append(genFeature.getVolatileFlag()); stringBuffer.append(TEXT_329); stringBuffer.append(genFeature.getChangeableFlag()); stringBuffer.append(TEXT_330); stringBuffer.append(genFeature.getContainmentFlag()); stringBuffer.append(TEXT_331); stringBuffer.append(genFeature.getResolveProxiesFlag()); stringBuffer.append(TEXT_332); stringBuffer.append(genFeature.getUnsettableFlag()); stringBuffer.append(TEXT_333); stringBuffer.append(genFeature.getUniqueFlag()); stringBuffer.append(TEXT_334); stringBuffer.append(genFeature.getDerivedFlag()); stringBuffer.append(TEXT_335); stringBuffer.append(genFeature.getOrderedFlag()); stringBuffer.append(TEXT_336); stringBuffer.append(genModel.getNonNLS()); stringBuffer.append(genModel.getNonNLS(genFeature.getDefaultValue(), 2)); for (GenFeature keyFeature : genFeature.getKeys()) { stringBuffer.append(TEXT_337); stringBuffer.append(genFeature.getFeatureAccessorName()); stringBuffer.append(TEXT_338); stringBuffer.append(genPackage.getPackageInstanceVariable(keyFeature.getGenPackage())); stringBuffer.append(TEXT_339); stringBuffer.append(keyFeature.getFeatureAccessorName()); stringBuffer.append(TEXT_340); } } else { stringBuffer.append(TEXT_341); stringBuffer.append(genFeature.getFeatureAccessorName()); stringBuffer.append(TEXT_342); if (genFeature.hasGenericType()) { stringBuffer.append(TEXT_343); } else { stringBuffer.append(genPackage.getPackageInstanceVariable(genFeature.getTypeGenPackage())); stringBuffer.append(TEXT_344); stringBuffer.append(genFeature.getTypeClassifierAccessorName()); stringBuffer.append(TEXT_345); } stringBuffer.append(TEXT_346); stringBuffer.append(genFeature.getName()); stringBuffer.append(TEXT_347); stringBuffer.append(genFeature.getDefaultValue()); stringBuffer.append(TEXT_348); stringBuffer.append(genFeature.getLowerBound()); stringBuffer.append(TEXT_349); stringBuffer.append(genFeature.getUpperBound()); stringBuffer.append(TEXT_350); stringBuffer.append(genFeature.getContainerClass()); stringBuffer.append(TEXT_351); stringBuffer.append(genFeature.getTransientFlag()); stringBuffer.append(TEXT_352); stringBuffer.append(genFeature.getVolatileFlag()); stringBuffer.append(TEXT_353); stringBuffer.append(genFeature.getChangeableFlag()); stringBuffer.append(TEXT_354); stringBuffer.append(genFeature.getUnsettableFlag()); stringBuffer.append(TEXT_355); stringBuffer.append(genFeature.getIDFlag()); stringBuffer.append(TEXT_356); stringBuffer.append(genFeature.getUniqueFlag()); stringBuffer.append(TEXT_357); stringBuffer.append(genFeature.getDerivedFlag()); stringBuffer.append(TEXT_358); stringBuffer.append(genFeature.getOrderedFlag()); stringBuffer.append(TEXT_359); stringBuffer.append(genModel.getNonNLS()); stringBuffer.append(genModel.getNonNLS(genFeature.getDefaultValue(), 2)); } } for (GenOperation genOperation : genClass.getGenOperations()) {String prefix = ""; if (genOperation.hasGenericType() || !genOperation.getGenParameters().isEmpty() || !genOperation.getGenExceptions().isEmpty() || !genOperation.getGenTypeParameters().isEmpty()) { if (firstOperationAssignment) { firstOperationAssignment = false; prefix = genModel.getImportedName("org.eclipse.emf.ecore.EOperation") + " op = "; } else { prefix = "op = "; }} stringBuffer.append(TEXT_360); if (genModel.useGenerics()) { stringBuffer.append(TEXT_361); stringBuffer.append(prefix); stringBuffer.append(TEXT_362); stringBuffer.append(genClass.getClassifierInstanceName()); stringBuffer.append(TEXT_363); if (genOperation.isVoid() || genOperation.hasGenericType()) { stringBuffer.append(TEXT_364); } else { stringBuffer.append(genPackage.getPackageInstanceVariable(genOperation.getTypeGenPackage())); stringBuffer.append(TEXT_365); stringBuffer.append(genOperation.getTypeClassifierAccessorName()); stringBuffer.append(TEXT_366); } stringBuffer.append(TEXT_367); stringBuffer.append(genOperation.getName()); stringBuffer.append(TEXT_368); stringBuffer.append(genOperation.getLowerBound()); stringBuffer.append(TEXT_369); stringBuffer.append(genOperation.getUpperBound()); stringBuffer.append(TEXT_370); stringBuffer.append(genOperation.getUniqueFlag()); stringBuffer.append(TEXT_371); stringBuffer.append(genOperation.getOrderedFlag()); stringBuffer.append(TEXT_372); stringBuffer.append(genModel.getNonNLS()); } else if (!genOperation.isVoid()) { if (!genOperation.getEcoreOperation().isOrdered() || !genOperation.getEcoreOperation().isUnique()) { needsAddEOperation = true; stringBuffer.append(TEXT_373); stringBuffer.append(prefix); stringBuffer.append(TEXT_374); stringBuffer.append(genClass.getClassifierInstanceName()); stringBuffer.append(TEXT_375); stringBuffer.append(genPackage.getPackageInstanceVariable(genOperation.getTypeGenPackage())); stringBuffer.append(TEXT_376); stringBuffer.append(genOperation.getTypeClassifierAccessorName()); stringBuffer.append(TEXT_377); stringBuffer.append(genOperation.getName()); stringBuffer.append(TEXT_378); stringBuffer.append(genOperation.getLowerBound()); stringBuffer.append(TEXT_379); stringBuffer.append(genOperation.getUpperBound()); stringBuffer.append(TEXT_380); stringBuffer.append(genOperation.getUniqueFlag()); stringBuffer.append(TEXT_381); stringBuffer.append(genOperation.getOrderedFlag()); stringBuffer.append(TEXT_382); stringBuffer.append(genModel.getNonNLS()); } else { stringBuffer.append(TEXT_383); stringBuffer.append(prefix); stringBuffer.append(TEXT_384); stringBuffer.append(genClass.getClassifierInstanceName()); stringBuffer.append(TEXT_385); stringBuffer.append(genPackage.getPackageInstanceVariable(genOperation.getTypeGenPackage())); stringBuffer.append(TEXT_386); stringBuffer.append(genOperation.getTypeClassifierAccessorName()); stringBuffer.append(TEXT_387); stringBuffer.append(genOperation.getName()); stringBuffer.append(TEXT_388); stringBuffer.append(genOperation.getLowerBound()); stringBuffer.append(TEXT_389); stringBuffer.append(genOperation.getUpperBound()); stringBuffer.append(TEXT_390); stringBuffer.append(genModel.getNonNLS()); } } else { stringBuffer.append(TEXT_391); stringBuffer.append(prefix); stringBuffer.append(TEXT_392); stringBuffer.append(genClass.getClassifierInstanceName()); stringBuffer.append(TEXT_393); stringBuffer.append(genOperation.getName()); stringBuffer.append(TEXT_394); stringBuffer.append(genModel.getNonNLS()); } if (genModel.useGenerics()) { for (ListIterator<GenTypeParameter> t=genOperation.getGenTypeParameters().listIterator(); t.hasNext(); ) { GenTypeParameter genTypeParameter = t.next(); String typeParameterVariable = ""; if (!genTypeParameter.getEcoreTypeParameter().getEBounds().isEmpty() || genTypeParameter.isUsed()) { if (maxTypeParameterAssignment <= t.previousIndex()) { ++maxTypeParameterAssignment; typeParameterVariable = genModel.getImportedName("org.eclipse.emf.ecore.ETypeParameter") + " t" + t.nextIndex() + " = "; } else { typeParameterVariable = "t" + t.nextIndex() + " = "; }} stringBuffer.append(TEXT_395); stringBuffer.append(typeParameterVariable); stringBuffer.append(TEXT_396); stringBuffer.append(genTypeParameter.getName()); stringBuffer.append(TEXT_397); stringBuffer.append(genModel.getNonNLS()); for (EGenericType typeParameter : genTypeParameter.getEcoreTypeParameter().getEBounds()) { for (InformationIterator i=new InformationIterator(typeParameter); i.hasNext(); ) { Information info = i.next(); String typePrefix = ""; if (maxGenericTypeAssignment <= info.depth) { ++maxGenericTypeAssignment; typePrefix = genModel.getImportedName("org.eclipse.emf.ecore.EGenericType") + " "; } stringBuffer.append(TEXT_398); stringBuffer.append(typePrefix); stringBuffer.append(TEXT_399); stringBuffer.append(info.depth + 1); stringBuffer.append(TEXT_400); stringBuffer.append(info.type); stringBuffer.append(TEXT_401); if (info.depth > 0) { stringBuffer.append(TEXT_402); stringBuffer.append(info.depth); stringBuffer.append(TEXT_403); stringBuffer.append(info.accessor); stringBuffer.append(TEXT_404); stringBuffer.append(info.depth + 1); stringBuffer.append(TEXT_405); } } stringBuffer.append(TEXT_406); stringBuffer.append(t.nextIndex()); stringBuffer.append(TEXT_407); }
public String generate(Object argument) { final StringBuffer stringBuffer = new StringBuffer(); /** * <copyright> * * Copyright (c) 2002-2006 IBM Corporation and others. * 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 * * Contributors: * IBM - Initial API and implementation * * </copyright> */ final GenPackage genPackage = (GenPackage)((Object[])argument)[0]; final GenModel genModel=genPackage.getGenModel(); boolean isInterface = Boolean.TRUE.equals(((Object[])argument)[1]); boolean isImplementation = Boolean.TRUE.equals(((Object[])argument)[2]); String publicStaticFinalFlag = isImplementation ? "public static final " : ""; boolean needsAddEOperation = false; boolean needsAddEParameter = false; stringBuffer.append(TEXT_1); stringBuffer.append(TEXT_2); {GenBase copyrightHolder = argument instanceof GenBase ? (GenBase)argument : argument instanceof Object[] && ((Object[])argument)[0] instanceof GenBase ? (GenBase)((Object[])argument)[0] : null; if (copyrightHolder != null && copyrightHolder.hasCopyright()) { stringBuffer.append(TEXT_3); stringBuffer.append(copyrightHolder.getCopyright(copyrightHolder.getGenModel().getIndentation(stringBuffer))); } else { stringBuffer.append(TEXT_4); }} stringBuffer.append(TEXT_5); stringBuffer.append("$"); stringBuffer.append(TEXT_6); stringBuffer.append("$"); stringBuffer.append(TEXT_7); if (isImplementation && !genModel.isSuppressInterfaces()) { stringBuffer.append(TEXT_8); stringBuffer.append(genPackage.getClassPackageName()); stringBuffer.append(TEXT_9); } else { stringBuffer.append(TEXT_10); stringBuffer.append(genPackage.getReflectionPackageName()); stringBuffer.append(TEXT_11); } stringBuffer.append(TEXT_12); genModel.markImportLocation(stringBuffer, genPackage); if (isImplementation) { genModel.addPseudoImport("org.eclipse.emf.ecore.EPackage.Registry"); genModel.addPseudoImport("org.eclipse.emf.ecore.EPackage.Descriptor"); if (genPackage.isLiteralsInterface()) { genModel.addPseudoImport(genPackage.getQualifiedPackageInterfaceName() + ".Literals"); } for (GenClassifier genClassifier : genPackage.getOrderedGenClassifiers()) genModel.addPseudoImport(genPackage.getQualifiedPackageInterfaceName() + "." + genPackage.getClassifierID(genClassifier)); } if (isInterface) { stringBuffer.append(TEXT_13); if (genPackage.hasDocumentation()) { stringBuffer.append(TEXT_14); stringBuffer.append(genPackage.getDocumentation(genModel.getIndentation(stringBuffer))); stringBuffer.append(TEXT_15); } stringBuffer.append(TEXT_16); stringBuffer.append(genPackage.getQualifiedFactoryInterfaceName()); if (!genModel.isSuppressEMFModelTags()) { boolean first = true; for (StringTokenizer stringTokenizer = new StringTokenizer(genPackage.getModelInfo(), "\n\r"); stringTokenizer.hasMoreTokens(); ) { String modelInfo = stringTokenizer.nextToken(); if (first) { first = false; stringBuffer.append(TEXT_17); stringBuffer.append(modelInfo); } else { stringBuffer.append(TEXT_18); stringBuffer.append(modelInfo); }} if (first) { stringBuffer.append(TEXT_19); }} stringBuffer.append(TEXT_20); } else { stringBuffer.append(TEXT_21); } if (isImplementation) { stringBuffer.append(TEXT_22); stringBuffer.append(genPackage.getPackageClassName()); stringBuffer.append(TEXT_23); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.impl.EPackageImpl")); if (!isInterface){ stringBuffer.append(TEXT_24); stringBuffer.append(genPackage.getImportedPackageInterfaceName()); } } else { stringBuffer.append(TEXT_25); stringBuffer.append(genPackage.getPackageInterfaceName()); stringBuffer.append(TEXT_26); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EPackage")); } stringBuffer.append(TEXT_27); if (genModel.hasCopyrightField()) { stringBuffer.append(TEXT_28); stringBuffer.append(publicStaticFinalFlag); stringBuffer.append(genModel.getImportedName("java.lang.String")); stringBuffer.append(TEXT_29); stringBuffer.append(genModel.getCopyrightFieldLiteral()); stringBuffer.append(TEXT_30); stringBuffer.append(genModel.getNonNLS()); stringBuffer.append(TEXT_31); } if (isInterface) { stringBuffer.append(TEXT_32); stringBuffer.append(publicStaticFinalFlag); stringBuffer.append(genModel.getImportedName("java.lang.String")); stringBuffer.append(TEXT_33); stringBuffer.append(genPackage.getPackageName()); stringBuffer.append(TEXT_34); stringBuffer.append(genModel.getNonNLS()); stringBuffer.append(TEXT_35); stringBuffer.append(publicStaticFinalFlag); stringBuffer.append(genModel.getImportedName("java.lang.String")); stringBuffer.append(TEXT_36); stringBuffer.append(genPackage.getNSURI()); stringBuffer.append(TEXT_37); stringBuffer.append(genModel.getNonNLS()); stringBuffer.append(TEXT_38); stringBuffer.append(publicStaticFinalFlag); stringBuffer.append(genModel.getImportedName("java.lang.String")); stringBuffer.append(TEXT_39); stringBuffer.append(genPackage.getNSName()); stringBuffer.append(TEXT_40); stringBuffer.append(genModel.getNonNLS()); if (genPackage.isContentType()) { stringBuffer.append(TEXT_41); stringBuffer.append(publicStaticFinalFlag); stringBuffer.append(genModel.getImportedName("java.lang.String")); stringBuffer.append(TEXT_42); stringBuffer.append(genPackage.getContentTypeIdentifier()); stringBuffer.append(TEXT_43); stringBuffer.append(genModel.getNonNLS()); } stringBuffer.append(TEXT_44); stringBuffer.append(publicStaticFinalFlag); stringBuffer.append(genPackage.getPackageInterfaceName()); stringBuffer.append(TEXT_45); stringBuffer.append(genPackage.getQualifiedPackageClassName()); stringBuffer.append(TEXT_46); for (GenClassifier genClassifier : genPackage.getOrderedGenClassifiers()) { stringBuffer.append(TEXT_47); if (genClassifier instanceof GenClass) { GenClass genClass = (GenClass)genClassifier; if (!genClass.isInterface()) { stringBuffer.append(TEXT_48); stringBuffer.append(genClass.getQualifiedClassName()); stringBuffer.append(TEXT_49); stringBuffer.append(genClass.getFormattedName()); stringBuffer.append(TEXT_50); stringBuffer.append(genClass.getQualifiedClassName()); } else { stringBuffer.append(TEXT_51); stringBuffer.append(genClass.getQualifiedInterfaceName()); stringBuffer.append(TEXT_52); stringBuffer.append(genClass.getFormattedName()); stringBuffer.append(TEXT_53); stringBuffer.append(genClass.getQualifiedInterfaceName()); } } else if (genClassifier instanceof GenEnum) { GenEnum genEnum = (GenEnum)genClassifier; stringBuffer.append(TEXT_54); stringBuffer.append(genEnum.getQualifiedName()); stringBuffer.append(TEXT_55); stringBuffer.append(genEnum.getFormattedName()); stringBuffer.append(TEXT_56); stringBuffer.append(genEnum.getQualifiedName()); } else if (genClassifier instanceof GenDataType) { GenDataType genDataType = (GenDataType)genClassifier; stringBuffer.append(TEXT_57); stringBuffer.append(genDataType.getFormattedName()); stringBuffer.append(TEXT_58); if (!genDataType.isPrimitiveType() && !genDataType.isArrayType()) { stringBuffer.append(TEXT_59); stringBuffer.append(genDataType.getRawInstanceClassName()); } } stringBuffer.append(TEXT_60); stringBuffer.append(genPackage.getQualifiedPackageClassName()); stringBuffer.append(TEXT_61); stringBuffer.append(genClassifier.getClassifierAccessorName()); stringBuffer.append(TEXT_62); stringBuffer.append(publicStaticFinalFlag); stringBuffer.append(TEXT_63); stringBuffer.append(genPackage.getClassifierID(genClassifier)); stringBuffer.append(TEXT_64); stringBuffer.append(genPackage.getClassifierValue(genClassifier)); stringBuffer.append(TEXT_65); if (genClassifier instanceof GenClass) { GenClass genClass = (GenClass)genClassifier; for (GenFeature genFeature : genClass.getAllGenFeatures()) { stringBuffer.append(TEXT_66); stringBuffer.append(genFeature.getFormattedName()); stringBuffer.append(TEXT_67); stringBuffer.append(genFeature.getFeatureKind()); stringBuffer.append(TEXT_68); stringBuffer.append(publicStaticFinalFlag); stringBuffer.append(TEXT_69); stringBuffer.append(genClass.getFeatureID(genFeature)); stringBuffer.append(TEXT_70); stringBuffer.append(genClass.getFeatureValue(genFeature)); stringBuffer.append(TEXT_71); } stringBuffer.append(TEXT_72); stringBuffer.append(genClass.getFormattedName()); stringBuffer.append(TEXT_73); stringBuffer.append(publicStaticFinalFlag); stringBuffer.append(TEXT_74); stringBuffer.append(genClass.getFeatureCountID()); stringBuffer.append(TEXT_75); stringBuffer.append(genClass.getFeatureCountValue()); stringBuffer.append(TEXT_76); } } } if (isImplementation) { if (genPackage.isLoadingInitialization()) { stringBuffer.append(TEXT_77); stringBuffer.append(genPackage.getSerializedPackageFilename()); stringBuffer.append(TEXT_78); stringBuffer.append(genModel.getNonNLS()); stringBuffer.append(TEXT_79); } for (GenClassifier genClassifier : genPackage.getGenClassifiers()) { stringBuffer.append(TEXT_80); stringBuffer.append(genClassifier.getImportedMetaType()); stringBuffer.append(TEXT_81); stringBuffer.append(genClassifier.getClassifierInstanceName()); stringBuffer.append(TEXT_82); } stringBuffer.append(TEXT_83); stringBuffer.append(genPackage.getQualifiedPackageInterfaceName()); stringBuffer.append(TEXT_84); stringBuffer.append(genPackage.getPackageClassName()); stringBuffer.append(TEXT_85); stringBuffer.append(genPackage.getQualifiedEFactoryInstanceAccessor()); stringBuffer.append(TEXT_86); if (!genPackage.isLoadedInitialization()) { stringBuffer.append(TEXT_87); } stringBuffer.append(TEXT_88); stringBuffer.append(genPackage.getImportedPackageInterfaceName()); stringBuffer.append(TEXT_89); stringBuffer.append(genPackage.getImportedPackageInterfaceName()); stringBuffer.append(TEXT_90); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EPackage")); stringBuffer.append(TEXT_91); stringBuffer.append(genPackage.getImportedPackageInterfaceName()); stringBuffer.append(TEXT_92); stringBuffer.append(genPackage.getPackageClassName()); stringBuffer.append(TEXT_93); stringBuffer.append(genPackage.getBasicPackageName()); stringBuffer.append(TEXT_94); stringBuffer.append(genPackage.getPackageClassName()); stringBuffer.append(TEXT_95); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EPackage")); stringBuffer.append(TEXT_96); stringBuffer.append(genPackage.getPackageClassName()); stringBuffer.append(TEXT_97); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EPackage")); stringBuffer.append(TEXT_98); stringBuffer.append(genPackage.getPackageClassName()); stringBuffer.append(TEXT_99); if (!genPackage.getPackageSimpleDependencies().isEmpty()) { stringBuffer.append(TEXT_100); for (GenPackage dep : genPackage.getPackageSimpleDependencies()) { stringBuffer.append(TEXT_101); stringBuffer.append(dep.getImportedPackageInterfaceName()); stringBuffer.append(TEXT_102); } stringBuffer.append(TEXT_103); } if (!genPackage.getPackageInterDependencies().isEmpty()) { stringBuffer.append(TEXT_104); for (GenPackage interdep : genPackage.getPackageInterDependencies()) { stringBuffer.append(TEXT_105); stringBuffer.append(interdep.getImportedPackageClassName()); stringBuffer.append(TEXT_106); stringBuffer.append(genPackage.getPackageInstanceVariable(interdep)); stringBuffer.append(TEXT_107); stringBuffer.append(interdep.getImportedPackageClassName()); stringBuffer.append(TEXT_108); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EPackage")); stringBuffer.append(TEXT_109); stringBuffer.append(interdep.getImportedPackageInterfaceName()); stringBuffer.append(TEXT_110); stringBuffer.append(interdep.getImportedPackageClassName()); stringBuffer.append(TEXT_111); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EPackage")); stringBuffer.append(TEXT_112); stringBuffer.append(interdep.getImportedPackageInterfaceName()); stringBuffer.append(TEXT_113); stringBuffer.append(interdep.getImportedPackageInterfaceName()); stringBuffer.append(TEXT_114); } stringBuffer.append(TEXT_115); } if (genPackage.isLoadedInitialization() || !genPackage.getPackageLoadInterDependencies().isEmpty()) { stringBuffer.append(TEXT_116); if (genPackage.isLoadingInitialization()) { stringBuffer.append(TEXT_117); stringBuffer.append(genPackage.getBasicPackageName()); stringBuffer.append(TEXT_118); } for (GenPackage interdep : genPackage.getPackageLoadInterDependencies()) { if (interdep.isLoadingInitialization()) { stringBuffer.append(TEXT_119); stringBuffer.append(genPackage.getPackageInstanceVariable(interdep)); stringBuffer.append(TEXT_120); } } stringBuffer.append(TEXT_121); } if (!genPackage.isLoadedInitialization() || !genPackage.getPackageBuildInterDependencies().isEmpty()) { stringBuffer.append(TEXT_122); if (!genPackage.isLoadedInitialization()) { stringBuffer.append(TEXT_123); stringBuffer.append(genPackage.getBasicPackageName()); stringBuffer.append(TEXT_124); } for (GenPackage interdep : genPackage.getPackageBuildInterDependencies()) { stringBuffer.append(TEXT_125); stringBuffer.append(genPackage.getPackageInstanceVariable(interdep)); stringBuffer.append(TEXT_126); } stringBuffer.append(TEXT_127); if (!genPackage.isLoadedInitialization()) { stringBuffer.append(TEXT_128); stringBuffer.append(genPackage.getBasicPackageName()); stringBuffer.append(TEXT_129); } for (GenPackage interdep : genPackage.getPackageBuildInterDependencies()) { stringBuffer.append(TEXT_130); stringBuffer.append(genPackage.getPackageInstanceVariable(interdep)); stringBuffer.append(TEXT_131); } stringBuffer.append(TEXT_132); } if (genPackage.isLoadedInitialization() || !genPackage.getPackageLoadInterDependencies().isEmpty()) { stringBuffer.append(TEXT_133); if (genPackage.isLoadedInitialization()) { stringBuffer.append(TEXT_134); stringBuffer.append(genPackage.getBasicPackageName()); stringBuffer.append(TEXT_135); } for (GenPackage interdep : genPackage.getPackageLoadInterDependencies()) { stringBuffer.append(TEXT_136); stringBuffer.append(genPackage.getPackageInstanceVariable(interdep)); stringBuffer.append(TEXT_137); } stringBuffer.append(TEXT_138); } if (genPackage.hasConstraints()) { stringBuffer.append(TEXT_139); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EValidator")); stringBuffer.append(TEXT_140); stringBuffer.append(genPackage.getBasicPackageName()); stringBuffer.append(TEXT_141); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EValidator")); stringBuffer.append(TEXT_142); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EValidator")); stringBuffer.append(TEXT_143); stringBuffer.append(genPackage.getImportedValidatorClassName()); stringBuffer.append(TEXT_144); } if (!genPackage.isEcorePackage()) { stringBuffer.append(TEXT_145); stringBuffer.append(genPackage.getBasicPackageName()); stringBuffer.append(TEXT_146); } stringBuffer.append(TEXT_147); stringBuffer.append(genPackage.getBasicPackageName()); stringBuffer.append(TEXT_148); } if (isInterface) { // TODO REMOVE THIS BOGUS EMPTY LINE stringBuffer.append(TEXT_149); } for (GenClassifier genClassifier : genPackage.getGenClassifiers()) { if (isInterface) { stringBuffer.append(TEXT_150); if (genClassifier instanceof GenClass) { GenClass genClass = (GenClass)genClassifier; stringBuffer.append(TEXT_151); stringBuffer.append(genClass.getQualifiedInterfaceName()); stringBuffer.append(TEXT_152); stringBuffer.append(genClass.getFormattedName()); stringBuffer.append(TEXT_153); stringBuffer.append(genClass.getFormattedName()); stringBuffer.append(TEXT_154); stringBuffer.append(genClass.getQualifiedInterfaceName()); if (!genModel.isSuppressEMFModelTags() && (genClass.isExternalInterface() || genClass.isDynamic())) { boolean first = true; for (StringTokenizer stringTokenizer = new StringTokenizer(genClass.getModelInfo(), "\n\r"); stringTokenizer.hasMoreTokens(); ) { String modelInfo = stringTokenizer.nextToken(); if (first) { first = false; stringBuffer.append(TEXT_155); stringBuffer.append(modelInfo); } else { stringBuffer.append(TEXT_156); stringBuffer.append(modelInfo); }} if (first) { stringBuffer.append(TEXT_157); }} } else if (genClassifier instanceof GenEnum) { GenEnum genEnum = (GenEnum)genClassifier; stringBuffer.append(TEXT_158); stringBuffer.append(genEnum.getQualifiedName()); stringBuffer.append(TEXT_159); stringBuffer.append(genEnum.getFormattedName()); stringBuffer.append(TEXT_160); stringBuffer.append(genEnum.getFormattedName()); stringBuffer.append(TEXT_161); stringBuffer.append(genEnum.getQualifiedName()); } else if (genClassifier instanceof GenDataType) { GenDataType genDataType = (GenDataType)genClassifier; if (genDataType.isPrimitiveType() || genDataType.isArrayType()) { stringBuffer.append(TEXT_162); stringBuffer.append(genDataType.getFormattedName()); stringBuffer.append(TEXT_163); } else { stringBuffer.append(TEXT_164); stringBuffer.append(genDataType.getRawInstanceClassName()); stringBuffer.append(TEXT_165); stringBuffer.append(genDataType.getFormattedName()); stringBuffer.append(TEXT_166); } stringBuffer.append(TEXT_167); stringBuffer.append(genDataType.getFormattedName()); stringBuffer.append(TEXT_168); if (!genDataType.isPrimitiveType() && !genDataType.isArrayType()) { stringBuffer.append(TEXT_169); stringBuffer.append(genDataType.getRawInstanceClassName()); } if (!genModel.isSuppressEMFModelTags()) {boolean first = true; for (StringTokenizer stringTokenizer = new StringTokenizer(genDataType.getModelInfo(), "\n\r"); stringTokenizer.hasMoreTokens(); ) { String modelInfo = stringTokenizer.nextToken(); if (first) { first = false; stringBuffer.append(TEXT_170); stringBuffer.append(modelInfo); } else { stringBuffer.append(TEXT_171); stringBuffer.append(modelInfo); }} if (first) { stringBuffer.append(TEXT_172); }} } stringBuffer.append(TEXT_173); } else { stringBuffer.append(TEXT_174); } if (isImplementation) { stringBuffer.append(TEXT_175); stringBuffer.append(genClassifier.getImportedMetaType()); stringBuffer.append(TEXT_176); stringBuffer.append(genClassifier.getClassifierAccessorName()); stringBuffer.append(TEXT_177); if (genPackage.isLoadedInitialization()) { stringBuffer.append(TEXT_178); stringBuffer.append(genClassifier.getClassifierInstanceName()); stringBuffer.append(TEXT_179); stringBuffer.append(genClassifier.getClassifierInstanceName()); stringBuffer.append(TEXT_180); stringBuffer.append(genClassifier.getImportedMetaType()); stringBuffer.append(TEXT_181); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EPackage")); stringBuffer.append(TEXT_182); stringBuffer.append(genPackage.getImportedPackageInterfaceName()); stringBuffer.append(TEXT_183); stringBuffer.append(genPackage.getLocalClassifierIndex(genClassifier)); stringBuffer.append(TEXT_184); } stringBuffer.append(TEXT_185); stringBuffer.append(genClassifier.getClassifierInstanceName()); stringBuffer.append(TEXT_186); } else { stringBuffer.append(TEXT_187); stringBuffer.append(genClassifier.getImportedMetaType()); stringBuffer.append(TEXT_188); stringBuffer.append(genClassifier.getClassifierAccessorName()); stringBuffer.append(TEXT_189); } if (genClassifier instanceof GenClass) { GenClass genClass = (GenClass)genClassifier; for (GenFeature genFeature : genClass.getGenFeatures()) { if (isInterface) { stringBuffer.append(TEXT_190); stringBuffer.append(genFeature.getFeatureKind()); stringBuffer.append(TEXT_191); stringBuffer.append(genClass.getQualifiedInterfaceName()); if (!genClass.isMapEntry() && !genFeature.isSuppressedGetVisibility()) { stringBuffer.append(TEXT_192); stringBuffer.append(genFeature.getGetAccessor()); } stringBuffer.append(TEXT_193); stringBuffer.append(genFeature.getFormattedName()); stringBuffer.append(TEXT_194); stringBuffer.append(genFeature.getFeatureKind()); stringBuffer.append(TEXT_195); stringBuffer.append(genFeature.getFormattedName()); stringBuffer.append(TEXT_196); stringBuffer.append(genClass.getQualifiedInterfaceName()); if (!genClass.isMapEntry() && !genFeature.isSuppressedGetVisibility()) { stringBuffer.append(TEXT_197); stringBuffer.append(genFeature.getGetAccessor()); stringBuffer.append(TEXT_198); } stringBuffer.append(TEXT_199); stringBuffer.append(genClass.getClassifierAccessorName()); stringBuffer.append(TEXT_200); } else { stringBuffer.append(TEXT_201); } if (isImplementation) { stringBuffer.append(TEXT_202); stringBuffer.append(genFeature.getImportedMetaType()); stringBuffer.append(TEXT_203); stringBuffer.append(genFeature.getFeatureAccessorName()); stringBuffer.append(TEXT_204); if (!genPackage.isLoadedInitialization()) { stringBuffer.append(TEXT_205); stringBuffer.append(genFeature.getImportedMetaType()); stringBuffer.append(TEXT_206); stringBuffer.append(genClass.getClassifierInstanceName()); stringBuffer.append(TEXT_207); stringBuffer.append(genClass.getLocalFeatureIndex(genFeature)); stringBuffer.append(TEXT_208); } else { stringBuffer.append(TEXT_209); stringBuffer.append(genFeature.getImportedMetaType()); stringBuffer.append(TEXT_210); stringBuffer.append(genClassifier.getClassifierAccessorName()); stringBuffer.append(TEXT_211); stringBuffer.append(genClass.getLocalFeatureIndex(genFeature)); stringBuffer.append(TEXT_212); } stringBuffer.append(TEXT_213); } else { stringBuffer.append(TEXT_214); stringBuffer.append(genFeature.getImportedMetaType()); stringBuffer.append(TEXT_215); stringBuffer.append(genFeature.getFeatureAccessorName()); stringBuffer.append(TEXT_216); } stringBuffer.append(TEXT_217); } } } if (isInterface) { stringBuffer.append(TEXT_218); } else { stringBuffer.append(TEXT_219); } if (isImplementation) { stringBuffer.append(TEXT_220); stringBuffer.append(genPackage.getImportedFactoryInterfaceName()); stringBuffer.append(TEXT_221); stringBuffer.append(genPackage.getFactoryName()); stringBuffer.append(TEXT_222); stringBuffer.append(genPackage.getImportedFactoryInterfaceName()); stringBuffer.append(TEXT_223); } else { stringBuffer.append(TEXT_224); stringBuffer.append(genPackage.getFactoryInterfaceName()); stringBuffer.append(TEXT_225); stringBuffer.append(genPackage.getFactoryName()); stringBuffer.append(TEXT_226); } stringBuffer.append(TEXT_227); if (isImplementation) { if (!genPackage.isLoadedInitialization()) { stringBuffer.append(TEXT_228); if (!genPackage.getGenClasses().isEmpty()) { stringBuffer.append(TEXT_229); for (Iterator<GenClass> c=genPackage.getGenClasses().iterator(); c.hasNext();) { GenClass genClass = c.next(); stringBuffer.append(TEXT_230); stringBuffer.append(genClass.getClassifierInstanceName()); stringBuffer.append(TEXT_231); stringBuffer.append(genClass.getMetaType()); stringBuffer.append(TEXT_232); stringBuffer.append(genClass.getClassifierID()); stringBuffer.append(TEXT_233); for (GenFeature genFeature : genClass.getGenFeatures()) { stringBuffer.append(TEXT_234); stringBuffer.append(genFeature.getMetaType()); stringBuffer.append(TEXT_235); stringBuffer.append(genClass.getClassifierInstanceName()); stringBuffer.append(TEXT_236); stringBuffer.append(genClass.getFeatureID(genFeature)); stringBuffer.append(TEXT_237); } if (c.hasNext()) { stringBuffer.append(TEXT_238); } } } if (!genPackage.getGenEnums().isEmpty()) { stringBuffer.append(TEXT_239); for (GenEnum genEnum : genPackage.getGenEnums()) { stringBuffer.append(TEXT_240); stringBuffer.append(genEnum.getClassifierInstanceName()); stringBuffer.append(TEXT_241); stringBuffer.append(genEnum.getClassifierID()); stringBuffer.append(TEXT_242); } } if (!genPackage.getGenDataTypes().isEmpty()) { stringBuffer.append(TEXT_243); for (GenDataType genDataType : genPackage.getGenDataTypes()) { stringBuffer.append(TEXT_244); stringBuffer.append(genDataType.getClassifierInstanceName()); stringBuffer.append(TEXT_245); stringBuffer.append(genDataType.getClassifierID()); stringBuffer.append(TEXT_246); } } stringBuffer.append(TEXT_247); /////////////////////// class Information { @SuppressWarnings("unused") EGenericType eGenericType; int depth; String type; String accessor; } class InformationIterator { Iterator<?> iterator; InformationIterator(EGenericType eGenericType) { iterator = EcoreUtil.getAllContents(Collections.singleton(eGenericType)); } boolean hasNext() { return iterator.hasNext(); } Information next() { Information information = new Information(); EGenericType eGenericType = information.eGenericType = (EGenericType)iterator.next(); for (EObject container = eGenericType.eContainer(); container instanceof EGenericType; container = container.eContainer()) { ++information.depth; } if (eGenericType.getEClassifier() != null ) { GenClassifier genClassifier = genModel.findGenClassifier(eGenericType.getEClassifier()); information.type = genPackage.getPackageInstanceVariable(genClassifier.getGenPackage()) + ".get" + genClassifier.getClassifierAccessorName() + "()"; } else if (eGenericType.getETypeParameter() != null) { ETypeParameter eTypeParameter = eGenericType.getETypeParameter(); if (eTypeParameter.eContainer() instanceof EClass) { information.type = genModel.findGenClassifier((EClass)eTypeParameter.eContainer()).getClassifierInstanceName() + "_" + eGenericType.getETypeParameter().getName(); } else { information.type = "t" + (((EOperation)eTypeParameter.eContainer()).getETypeParameters().indexOf(eTypeParameter) + 1); } } else { information.type =""; } if (information.depth > 0) { if (eGenericType.eContainmentFeature().isMany()) { information.accessor = "getE" + eGenericType.eContainmentFeature().getName().substring(1) + "().add"; } else { information.accessor = "setE" + eGenericType.eContainmentFeature().getName().substring(1); } } return information; } } /////////////////////// int maxGenericTypeAssignment = 0; stringBuffer.append(TEXT_248); if (!genPackage.getPackageInitializationDependencies().isEmpty()) { stringBuffer.append(TEXT_249); for (GenPackage dep : genPackage.getPackageInitializationDependencies()) { stringBuffer.append(TEXT_250); stringBuffer.append(dep.getImportedPackageInterfaceName()); stringBuffer.append(TEXT_251); stringBuffer.append(genPackage.getPackageInstanceVariable(dep)); stringBuffer.append(TEXT_252); stringBuffer.append(dep.getImportedPackageInterfaceName()); stringBuffer.append(TEXT_253); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EPackage")); stringBuffer.append(TEXT_254); stringBuffer.append(dep.getImportedPackageInterfaceName()); stringBuffer.append(TEXT_255); } } if (!genPackage.getSubGenPackages().isEmpty()) { stringBuffer.append(TEXT_256); for (GenPackage sub : genPackage.getSubGenPackages()) { stringBuffer.append(TEXT_257); stringBuffer.append(genPackage.getPackageInstanceVariable(sub)); stringBuffer.append(TEXT_258); } } if (!genPackage.getGenClasses().isEmpty()) { boolean firstOperationAssignment = true; int maxTypeParameterAssignment = 0; if (genModel.useGenerics()) { stringBuffer.append(TEXT_259); for (GenClassifier genClassifier : genPackage.getGenClassifiers()) { for (GenTypeParameter genTypeParameter : genClassifier.getGenTypeParameters()) { if (!genTypeParameter.getEcoreTypeParameter().getEBounds().isEmpty() || genTypeParameter.isUsed()) { stringBuffer.append(TEXT_260); stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.ETypeParameter")); stringBuffer.append(TEXT_261); stringBuffer.append(genClassifier.getClassifierInstanceName()); stringBuffer.append(TEXT_262); stringBuffer.append(genTypeParameter.getName()); stringBuffer.append(TEXT_263); stringBuffer.append(genClassifier.getClassifierInstanceName()); stringBuffer.append(TEXT_264); stringBuffer.append(genTypeParameter.getName()); stringBuffer.append(TEXT_265); stringBuffer.append(genModel.getNonNLS()); } else { stringBuffer.append(TEXT_266); stringBuffer.append(genClassifier.getClassifierInstanceName()); stringBuffer.append(TEXT_267); stringBuffer.append(genTypeParameter.getName()); stringBuffer.append(TEXT_268); stringBuffer.append(genModel.getNonNLS()); } } } } if (genModel.useGenerics()) { stringBuffer.append(TEXT_269); for (GenClassifier genClassifier : genPackage.getGenClassifiers()) { for (GenTypeParameter genTypeParameter : genClassifier.getGenTypeParameters()) { for (EGenericType bound : genTypeParameter.getEcoreTypeParameter().getEBounds()) { for (InformationIterator i=new InformationIterator(bound); i.hasNext(); ) { Information info = i.next(); String prefix = ""; if (maxGenericTypeAssignment <= info.depth) { ++maxGenericTypeAssignment; prefix = genModel.getImportedName("org.eclipse.emf.ecore.EGenericType") + " "; } stringBuffer.append(TEXT_270); stringBuffer.append(prefix); stringBuffer.append(TEXT_271); stringBuffer.append(info.depth + 1); stringBuffer.append(TEXT_272); stringBuffer.append(info.type); stringBuffer.append(TEXT_273); if (info.depth > 0) { stringBuffer.append(TEXT_274); stringBuffer.append(info.depth); stringBuffer.append(TEXT_275); stringBuffer.append(info.accessor); stringBuffer.append(TEXT_276); stringBuffer.append(info.depth + 1); stringBuffer.append(TEXT_277); } } stringBuffer.append(TEXT_278); stringBuffer.append(genClassifier.getClassifierInstanceName()); stringBuffer.append(TEXT_279); stringBuffer.append(genTypeParameter.getName()); stringBuffer.append(TEXT_280); } } } } stringBuffer.append(TEXT_281); for (GenClass genClass : genPackage.getGenClasses()) { if (!genClass.hasGenericSuperTypes()) { for (GenClass baseGenClass : genClass.getBaseGenClasses()) { stringBuffer.append(TEXT_282); stringBuffer.append(genClass.getClassifierInstanceName()); stringBuffer.append(TEXT_283); stringBuffer.append(genPackage.getPackageInstanceVariable(baseGenClass.getGenPackage())); stringBuffer.append(TEXT_284); stringBuffer.append(baseGenClass.getClassifierAccessorName()); stringBuffer.append(TEXT_285); } } else { for (EGenericType superType : genClass.getEcoreClass().getEGenericSuperTypes()) { for (InformationIterator i=new InformationIterator(superType); i.hasNext(); ) { Information info = i.next(); String prefix = ""; if (maxGenericTypeAssignment <= info.depth) { ++maxGenericTypeAssignment; prefix = genModel.getImportedName("org.eclipse.emf.ecore.EGenericType") + " "; } stringBuffer.append(TEXT_286); stringBuffer.append(prefix); stringBuffer.append(TEXT_287); stringBuffer.append(info.depth + 1); stringBuffer.append(TEXT_288); stringBuffer.append(info.type); stringBuffer.append(TEXT_289); if (info.depth > 0) { stringBuffer.append(TEXT_290); stringBuffer.append(info.depth); stringBuffer.append(TEXT_291); stringBuffer.append(info.accessor); stringBuffer.append(TEXT_292); stringBuffer.append(info.depth + 1); stringBuffer.append(TEXT_293); } } stringBuffer.append(TEXT_294); stringBuffer.append(genClass.getClassifierInstanceName()); stringBuffer.append(TEXT_295); } } } stringBuffer.append(TEXT_296); for (Iterator<GenClass> c=genPackage.getGenClasses().iterator(); c.hasNext();) { GenClass genClass = c.next(); boolean hasInstanceTypeName = genModel.useGenerics() && genClass.getEcoreClass().getInstanceTypeName() != null && genClass.getEcoreClass().getInstanceTypeName().contains("<"); stringBuffer.append(TEXT_297); stringBuffer.append(genClass.getClassifierInstanceName()); stringBuffer.append(TEXT_298); if (genClass.isDynamic()) { stringBuffer.append(TEXT_299); } else { stringBuffer.append(genClass.getRawImportedInterfaceName()); stringBuffer.append(TEXT_300); } stringBuffer.append(TEXT_301); stringBuffer.append(genClass.getName()); stringBuffer.append(TEXT_302); stringBuffer.append(genClass.getAbstractFlag()); stringBuffer.append(TEXT_303); stringBuffer.append(genClass.getInterfaceFlag()); stringBuffer.append(TEXT_304); stringBuffer.append(genClass.getGeneratedInstanceClassFlag()); if (hasInstanceTypeName) { stringBuffer.append(TEXT_305); stringBuffer.append(genClass.getEcoreClass().getInstanceTypeName()); stringBuffer.append(TEXT_306); } stringBuffer.append(TEXT_307); stringBuffer.append(genModel.getNonNLS()); if (hasInstanceTypeName) { stringBuffer.append(genModel.getNonNLS(2)); } for (GenFeature genFeature : genClass.getGenFeatures()) { if (genFeature.hasGenericType()) { for (InformationIterator i=new InformationIterator(genFeature.getEcoreFeature().getEGenericType()); i.hasNext(); ) { Information info = i.next(); String prefix = ""; if (maxGenericTypeAssignment <= info.depth) { ++maxGenericTypeAssignment; prefix = genModel.getImportedName("org.eclipse.emf.ecore.EGenericType") + " "; } stringBuffer.append(TEXT_308); stringBuffer.append(prefix); stringBuffer.append(TEXT_309); stringBuffer.append(info.depth + 1); stringBuffer.append(TEXT_310); stringBuffer.append(info.type); stringBuffer.append(TEXT_311); if (info.depth > 0) { stringBuffer.append(TEXT_312); stringBuffer.append(info.depth); stringBuffer.append(TEXT_313); stringBuffer.append(info.accessor); stringBuffer.append(TEXT_314); stringBuffer.append(info.depth + 1); stringBuffer.append(TEXT_315); } } } if (genFeature.isReferenceType()) { GenFeature reverseGenFeature = genFeature.getReverse(); String reverse = reverseGenFeature == null ? "null" : genPackage.getPackageInstanceVariable(reverseGenFeature.getGenPackage()) + ".get" + reverseGenFeature.getFeatureAccessorName() + "()"; stringBuffer.append(TEXT_316); stringBuffer.append(genFeature.getFeatureAccessorName()); stringBuffer.append(TEXT_317); if (genFeature.hasGenericType()) { stringBuffer.append(TEXT_318); } else { stringBuffer.append(genPackage.getPackageInstanceVariable(genFeature.getTypeGenPackage())); stringBuffer.append(TEXT_319); stringBuffer.append(genFeature.getTypeClassifierAccessorName()); stringBuffer.append(TEXT_320); } stringBuffer.append(TEXT_321); stringBuffer.append(reverse); stringBuffer.append(TEXT_322); stringBuffer.append(genFeature.getName()); stringBuffer.append(TEXT_323); stringBuffer.append(genFeature.getDefaultValue()); stringBuffer.append(TEXT_324); stringBuffer.append(genFeature.getLowerBound()); stringBuffer.append(TEXT_325); stringBuffer.append(genFeature.getUpperBound()); stringBuffer.append(TEXT_326); stringBuffer.append(genFeature.getContainerClass()); stringBuffer.append(TEXT_327); stringBuffer.append(genFeature.getTransientFlag()); stringBuffer.append(TEXT_328); stringBuffer.append(genFeature.getVolatileFlag()); stringBuffer.append(TEXT_329); stringBuffer.append(genFeature.getChangeableFlag()); stringBuffer.append(TEXT_330); stringBuffer.append(genFeature.getContainmentFlag()); stringBuffer.append(TEXT_331); stringBuffer.append(genFeature.getResolveProxiesFlag()); stringBuffer.append(TEXT_332); stringBuffer.append(genFeature.getUnsettableFlag()); stringBuffer.append(TEXT_333); stringBuffer.append(genFeature.getUniqueFlag()); stringBuffer.append(TEXT_334); stringBuffer.append(genFeature.getDerivedFlag()); stringBuffer.append(TEXT_335); stringBuffer.append(genFeature.getOrderedFlag()); stringBuffer.append(TEXT_336); stringBuffer.append(genModel.getNonNLS()); stringBuffer.append(genModel.getNonNLS(genFeature.getDefaultValue(), 2)); for (GenFeature keyFeature : genFeature.getKeys()) { stringBuffer.append(TEXT_337); stringBuffer.append(genFeature.getFeatureAccessorName()); stringBuffer.append(TEXT_338); stringBuffer.append(genPackage.getPackageInstanceVariable(keyFeature.getGenPackage())); stringBuffer.append(TEXT_339); stringBuffer.append(keyFeature.getFeatureAccessorName()); stringBuffer.append(TEXT_340); } } else { stringBuffer.append(TEXT_341); stringBuffer.append(genFeature.getFeatureAccessorName()); stringBuffer.append(TEXT_342); if (genFeature.hasGenericType()) { stringBuffer.append(TEXT_343); } else { stringBuffer.append(genPackage.getPackageInstanceVariable(genFeature.getTypeGenPackage())); stringBuffer.append(TEXT_344); stringBuffer.append(genFeature.getTypeClassifierAccessorName()); stringBuffer.append(TEXT_345); } stringBuffer.append(TEXT_346); stringBuffer.append(genFeature.getName()); stringBuffer.append(TEXT_347); stringBuffer.append(genFeature.getDefaultValue()); stringBuffer.append(TEXT_348); stringBuffer.append(genFeature.getLowerBound()); stringBuffer.append(TEXT_349); stringBuffer.append(genFeature.getUpperBound()); stringBuffer.append(TEXT_350); stringBuffer.append(genFeature.getContainerClass()); stringBuffer.append(TEXT_351); stringBuffer.append(genFeature.getTransientFlag()); stringBuffer.append(TEXT_352); stringBuffer.append(genFeature.getVolatileFlag()); stringBuffer.append(TEXT_353); stringBuffer.append(genFeature.getChangeableFlag()); stringBuffer.append(TEXT_354); stringBuffer.append(genFeature.getUnsettableFlag()); stringBuffer.append(TEXT_355); stringBuffer.append(genFeature.getIDFlag()); stringBuffer.append(TEXT_356); stringBuffer.append(genFeature.getUniqueFlag()); stringBuffer.append(TEXT_357); stringBuffer.append(genFeature.getDerivedFlag()); stringBuffer.append(TEXT_358); stringBuffer.append(genFeature.getOrderedFlag()); stringBuffer.append(TEXT_359); stringBuffer.append(genModel.getNonNLS()); stringBuffer.append(genModel.getNonNLS(genFeature.getDefaultValue(), 2)); } } for (GenOperation genOperation : genClass.getGenOperations()) {String prefix = ""; if (genOperation.hasGenericType() || !genOperation.getGenParameters().isEmpty() || !genOperation.getGenExceptions().isEmpty() || !genOperation.getGenTypeParameters().isEmpty()) { if (firstOperationAssignment) { firstOperationAssignment = false; prefix = genModel.getImportedName("org.eclipse.emf.ecore.EOperation") + " op = "; } else { prefix = "op = "; }} stringBuffer.append(TEXT_360); if (genModel.useGenerics()) { stringBuffer.append(TEXT_361); stringBuffer.append(prefix); stringBuffer.append(TEXT_362); stringBuffer.append(genClass.getClassifierInstanceName()); stringBuffer.append(TEXT_363); if (genOperation.isVoid() || genOperation.hasGenericType()) { stringBuffer.append(TEXT_364); } else { stringBuffer.append(genPackage.getPackageInstanceVariable(genOperation.getTypeGenPackage())); stringBuffer.append(TEXT_365); stringBuffer.append(genOperation.getTypeClassifierAccessorName()); stringBuffer.append(TEXT_366); } stringBuffer.append(TEXT_367); stringBuffer.append(genOperation.getName()); stringBuffer.append(TEXT_368); stringBuffer.append(genOperation.getLowerBound()); stringBuffer.append(TEXT_369); stringBuffer.append(genOperation.getUpperBound()); stringBuffer.append(TEXT_370); stringBuffer.append(genOperation.getUniqueFlag()); stringBuffer.append(TEXT_371); stringBuffer.append(genOperation.getOrderedFlag()); stringBuffer.append(TEXT_372); stringBuffer.append(genModel.getNonNLS()); } else if (!genOperation.isVoid()) { if (!genOperation.getEcoreOperation().isOrdered() || !genOperation.getEcoreOperation().isUnique()) { needsAddEOperation = true; stringBuffer.append(TEXT_373); stringBuffer.append(prefix); stringBuffer.append(TEXT_374); stringBuffer.append(genClass.getClassifierInstanceName()); stringBuffer.append(TEXT_375); stringBuffer.append(genPackage.getPackageInstanceVariable(genOperation.getTypeGenPackage())); stringBuffer.append(TEXT_376); stringBuffer.append(genOperation.getTypeClassifierAccessorName()); stringBuffer.append(TEXT_377); stringBuffer.append(genOperation.getName()); stringBuffer.append(TEXT_378); stringBuffer.append(genOperation.getLowerBound()); stringBuffer.append(TEXT_379); stringBuffer.append(genOperation.getUpperBound()); stringBuffer.append(TEXT_380); stringBuffer.append(genOperation.getUniqueFlag()); stringBuffer.append(TEXT_381); stringBuffer.append(genOperation.getOrderedFlag()); stringBuffer.append(TEXT_382); stringBuffer.append(genModel.getNonNLS()); } else { stringBuffer.append(TEXT_383); stringBuffer.append(prefix); stringBuffer.append(TEXT_384); stringBuffer.append(genClass.getClassifierInstanceName()); stringBuffer.append(TEXT_385); stringBuffer.append(genPackage.getPackageInstanceVariable(genOperation.getTypeGenPackage())); stringBuffer.append(TEXT_386); stringBuffer.append(genOperation.getTypeClassifierAccessorName()); stringBuffer.append(TEXT_387); stringBuffer.append(genOperation.getName()); stringBuffer.append(TEXT_388); stringBuffer.append(genOperation.getLowerBound()); stringBuffer.append(TEXT_389); stringBuffer.append(genOperation.getUpperBound()); stringBuffer.append(TEXT_390); stringBuffer.append(genModel.getNonNLS()); } } else { stringBuffer.append(TEXT_391); stringBuffer.append(prefix); stringBuffer.append(TEXT_392); stringBuffer.append(genClass.getClassifierInstanceName()); stringBuffer.append(TEXT_393); stringBuffer.append(genOperation.getName()); stringBuffer.append(TEXT_394); stringBuffer.append(genModel.getNonNLS()); } if (genModel.useGenerics()) { for (ListIterator<GenTypeParameter> t=genOperation.getGenTypeParameters().listIterator(); t.hasNext(); ) { GenTypeParameter genTypeParameter = t.next(); String typeParameterVariable = ""; if (!genTypeParameter.getEcoreTypeParameter().getEBounds().isEmpty() || genTypeParameter.isUsed()) { if (maxTypeParameterAssignment <= t.previousIndex()) { ++maxTypeParameterAssignment; typeParameterVariable = genModel.getImportedName("org.eclipse.emf.ecore.ETypeParameter") + " t" + t.nextIndex() + " = "; } else { typeParameterVariable = "t" + t.nextIndex() + " = "; }} stringBuffer.append(TEXT_395); stringBuffer.append(typeParameterVariable); stringBuffer.append(TEXT_396); stringBuffer.append(genTypeParameter.getName()); stringBuffer.append(TEXT_397); stringBuffer.append(genModel.getNonNLS()); for (EGenericType typeParameter : genTypeParameter.getEcoreTypeParameter().getEBounds()) { for (InformationIterator i=new InformationIterator(typeParameter); i.hasNext(); ) { Information info = i.next(); String typePrefix = ""; if (maxGenericTypeAssignment <= info.depth) { ++maxGenericTypeAssignment; typePrefix = genModel.getImportedName("org.eclipse.emf.ecore.EGenericType") + " "; } stringBuffer.append(TEXT_398); stringBuffer.append(typePrefix); stringBuffer.append(TEXT_399); stringBuffer.append(info.depth + 1); stringBuffer.append(TEXT_400); stringBuffer.append(info.type); stringBuffer.append(TEXT_401); if (info.depth > 0) { stringBuffer.append(TEXT_402); stringBuffer.append(info.depth); stringBuffer.append(TEXT_403); stringBuffer.append(info.accessor); stringBuffer.append(TEXT_404); stringBuffer.append(info.depth + 1); stringBuffer.append(TEXT_405); } } stringBuffer.append(TEXT_406); stringBuffer.append(t.nextIndex()); stringBuffer.append(TEXT_407); }
diff --git a/src/java/fedora/server/security/ResourceAttributeFinderModule.java b/src/java/fedora/server/security/ResourceAttributeFinderModule.java index 9c9f23771..fc960f68e 100755 --- a/src/java/fedora/server/security/ResourceAttributeFinderModule.java +++ b/src/java/fedora/server/security/ResourceAttributeFinderModule.java @@ -1,349 +1,349 @@ package fedora.server.security; import java.net.URI; import java.net.URISyntaxException; import java.util.Date; import com.sun.xacml.EvaluationCtx; import com.sun.xacml.attr.AttributeDesignator; import com.sun.xacml.attr.StringAttribute; import com.sun.xacml.cond.EvaluationResult; import org.apache.log4j.Logger; import fedora.common.Constants; import fedora.server.ReadOnlyContext; import fedora.server.Server; import fedora.server.errors.ServerException; import fedora.server.storage.DOManager; import fedora.server.storage.DOReader; import fedora.server.storage.types.Datastream; import fedora.server.utilities.DateUtility; /** * @author [email protected] */ class ResourceAttributeFinderModule extends AttributeFinderModule { /** Logger for this class. */ private static final Logger LOG = Logger.getLogger( ResourceAttributeFinderModule.class.getName()); protected boolean canHandleAdhoc() { return false; } static private final ResourceAttributeFinderModule singleton = new ResourceAttributeFinderModule(); private ResourceAttributeFinderModule() { super(); try { registerAttribute(Constants.OBJECT.STATE.uri, Constants.OBJECT.STATE.datatype); registerAttribute(Constants.OBJECT.OBJECT_TYPE.uri, Constants.OBJECT.OBJECT_TYPE.datatype); registerAttribute(Constants.OBJECT.OWNER.uri, Constants.OBJECT.OWNER.datatype); registerAttribute(Constants.OBJECT.CONTENT_MODEL.uri, Constants.OBJECT.CONTENT_MODEL.datatype); registerAttribute(Constants.OBJECT.CREATED_DATETIME.uri, Constants.OBJECT.CREATED_DATETIME.datatype); registerAttribute(Constants.OBJECT.LAST_MODIFIED_DATETIME.uri, Constants.OBJECT.LAST_MODIFIED_DATETIME.datatype); registerAttribute(Constants.DATASTREAM.STATE.uri, Constants.DATASTREAM.STATE.datatype); registerAttribute(Constants.DATASTREAM.CONTROL_GROUP.uri, Constants.DATASTREAM.CONTROL_GROUP.datatype); registerAttribute(Constants.DATASTREAM.CREATED_DATETIME.uri, Constants.DATASTREAM.CREATED_DATETIME.datatype); registerAttribute(Constants.DATASTREAM.INFO_TYPE.uri, Constants.DATASTREAM.INFO_TYPE.datatype); registerAttribute(Constants.DATASTREAM.LOCATION_TYPE.uri, Constants.DATASTREAM.LOCATION_TYPE.datatype); registerAttribute(Constants.DATASTREAM.MIME_TYPE.uri, Constants.DATASTREAM.MIME_TYPE.datatype); registerAttribute(Constants.DATASTREAM.CONTENT_LENGTH.uri, Constants.DATASTREAM.CONTENT_LENGTH.datatype); registerAttribute(Constants.DATASTREAM.FORMAT_URI.uri, Constants.DATASTREAM.FORMAT_URI.datatype); registerAttribute(Constants.DATASTREAM.LOCATION.uri, Constants.DATASTREAM.LOCATION.datatype); registerSupportedDesignatorType(AttributeDesignator.RESOURCE_TARGET); setInstantiatedOk(true); } catch (URISyntaxException e1) { setInstantiatedOk(false); } } static public final ResourceAttributeFinderModule getInstance() { return singleton; } private DOManager doManager = null; protected void setDOManager(DOManager doManager) { if (this.doManager == null) { this.doManager = doManager; } } private final String getResourceId(EvaluationCtx context) { URI resourceIdType = null; URI resourceIdId = null; try { resourceIdType = new URI(StringAttribute.identifier); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { resourceIdId = new URI(EvaluationCtx.RESOURCE_ID); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } EvaluationResult attribute = context.getResourceAttribute(resourceIdType, resourceIdId, null); Object element = getAttributeFromEvaluationResult(attribute); if (element == null) { LOG.debug("ResourceAttributeFinder:findAttribute" + " exit on " + "can't get resource-id on request callback"); return null; } if (! (element instanceof StringAttribute)) { LOG.debug("ResourceAttributeFinder:findAttribute" + " exit on " + "couldn't get resource-id from xacml request " + "non-string returned"); return null; } String resourceId = ((StringAttribute) element).getValue(); if (resourceId == null) { LOG.debug("ResourceAttributeFinder:findAttribute" + " exit on " + "null resource-id"); return null; } if (! validResourceId(resourceId)) { LOG.debug("ResourceAttributeFinder:findAttribute" + " exit on " + "invalid resource-id"); return null; } return resourceId; } private final boolean validResourceId(String resourceId) { if (resourceId == null) return false; // "" is a valid resource id, for it represents a don't-care condition if (" ".equals(resourceId)) return false; return true; } private final String getDatastreamId(EvaluationCtx context) { URI datastreamIdUri = null; try { datastreamIdUri = new URI(Constants.DATASTREAM.ID.uri); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } EvaluationResult attribute = context.getResourceAttribute(STRING_ATTRIBUTE_URI, datastreamIdUri, null); Object element = getAttributeFromEvaluationResult(attribute); if (element == null) { LOG.debug("getDatastreamId: " + " exit on " + "can't get resource-id on request callback"); return null; } if (! (element instanceof StringAttribute)) { LOG.debug("getDatastreamId: " + " exit on " + "couldn't get resource-id from xacml request " + "non-string returned"); return null; } String datastreamId = ((StringAttribute) element).getValue(); if (datastreamId == null) { LOG.debug("getDatastreamId: " + " exit on " + "null resource-id"); return null; } if (! validDatastreamId(datastreamId)) { LOG.debug("getDatastreamId: " + " exit on " + "invalid resource-id"); return null; } return datastreamId; } private final boolean validDatastreamId(String datastreamId) { if (datastreamId == null) return false; // "" is a valid resource id, for it represents a don't-care condition if (" ".equals(datastreamId)) return false; return true; } protected final Object getAttributeLocally(int designatorType, String attributeId, URI resourceCategory, EvaluationCtx context) { long getAttributeStartTime = System.currentTimeMillis(); try { String pid = getPid(context); if ("".equals(pid)) { LOG.debug("no pid"); return null; } LOG.debug("getResourceAttribute, pid=" + pid); DOReader reader = null; try { LOG.debug("pid="+pid); reader = doManager.getReader(Server.USE_CACHE, ReadOnlyContext.EMPTY, pid); } catch (ServerException e) { LOG.debug("couldn't get object reader"); return null; } String[] values = null; if (Constants.OBJECT.STATE.uri.equals(attributeId)) { try { values = new String[1]; values[0] = reader.GetObjectState(); LOG.debug("got " + Constants.OBJECT.STATE.uri + "=" + values[0]); } catch (ServerException e) { LOG.debug("failed getting " + Constants.OBJECT.STATE.uri); return null; } } else if (Constants.OBJECT.OBJECT_TYPE.uri.equals(attributeId)) { try { values = new String[1]; - values[0] = reader.getOwnerId(); + values[0] = reader.getFedoraObjectType(); LOG.debug("got " + Constants.OBJECT.OBJECT_TYPE.uri + "=" + values[0]); } catch (ServerException e) { LOG.debug("failed getting " + Constants.OBJECT.OBJECT_TYPE.uri); return null; } } else if (Constants.OBJECT.OWNER.uri.equals(attributeId)) { try { values = new String[1]; values[0] = reader.getOwnerId(); LOG.debug("got " + Constants.OBJECT.OWNER.uri + "=" + values[0]); } catch (ServerException e) { LOG.debug("failed getting " + Constants.OBJECT.OWNER.uri); return null; } } else if (Constants.OBJECT.CONTENT_MODEL.uri.equals(attributeId)) { try { values = new String[1]; values[0] = reader.getContentModelId(); LOG.debug("got " + Constants.OBJECT.CONTENT_MODEL.uri + "=" + values[0]); } catch (ServerException e) { LOG.debug("failed getting " + Constants.OBJECT.CONTENT_MODEL.uri); return null; } } else if (Constants.OBJECT.CREATED_DATETIME.uri.equals(attributeId)) { try { values = new String[1]; values[0] = DateUtility.convertDateToString(reader.getCreateDate()); LOG.debug("got " + Constants.OBJECT.CREATED_DATETIME.uri + "=" + values[0]); } catch (ServerException e) { LOG.debug("failed getting " + Constants.OBJECT.CREATED_DATETIME.uri); return null; } } else if (Constants.OBJECT.LAST_MODIFIED_DATETIME.uri.equals(attributeId)) { try { values = new String[1]; values[0] = DateUtility.convertDateToString(reader.getLastModDate()); LOG.debug("got " + Constants.OBJECT.LAST_MODIFIED_DATETIME.uri + "=" + values[0]); } catch (ServerException e) { LOG.debug("failed getting " + Constants.OBJECT.LAST_MODIFIED_DATETIME.uri); return null; } } else if ((Constants.DATASTREAM.STATE.uri.equals(attributeId)) || (Constants.DATASTREAM.CONTROL_GROUP.uri.equals(attributeId)) || (Constants.DATASTREAM.FORMAT_URI.uri.equals(attributeId)) || (Constants.DATASTREAM.CREATED_DATETIME.uri.equals(attributeId)) || (Constants.DATASTREAM.INFO_TYPE.uri.equals(attributeId)) || (Constants.DATASTREAM.LOCATION.uri.equals(attributeId)) || (Constants.DATASTREAM.LOCATION_TYPE.uri.equals(attributeId)) || (Constants.DATASTREAM.MIME_TYPE.uri.equals(attributeId)) || (Constants.DATASTREAM.CONTENT_LENGTH.uri.equals(attributeId)) ) { String datastreamId = getDatastreamId(context); if ("".equals(datastreamId)) { LOG.debug("no datastreamId"); return null; } LOG.debug("datastreamId=" + datastreamId); Datastream datastream; try { datastream = reader.GetDatastream(datastreamId, new Date()); //right import (above)? } catch (ServerException e) { LOG.debug("couldn't get datastream"); return null; } if (datastream == null) { LOG.debug("got null datastream"); return null; } if (Constants.DATASTREAM.STATE.uri.equals(attributeId)) { values = new String[1]; values[0] = datastream.DSState; } else if (Constants.DATASTREAM.CONTROL_GROUP.uri.equals(attributeId)) { values = new String[1]; values[0] = datastream.DSControlGrp; } else if (Constants.DATASTREAM.FORMAT_URI.uri.equals(attributeId)) { values = new String[1]; values[0] = datastream.DSFormatURI; } else if (Constants.DATASTREAM.CREATED_DATETIME.uri.equals(attributeId)) { values = new String[1]; values[0] = DateUtility.convertDateToString(datastream.DSCreateDT); } else if (Constants.DATASTREAM.INFO_TYPE.uri.equals(attributeId)) { values = new String[1]; values[0] = datastream.DSInfoType; } else if (Constants.DATASTREAM.LOCATION.uri.equals(attributeId)) { values = new String[1]; values[0] = datastream.DSLocation; } else if (Constants.DATASTREAM.LOCATION_TYPE.uri.equals(attributeId)) { values = new String[1]; values[0] = datastream.DSLocationType; } else if (Constants.DATASTREAM.MIME_TYPE.uri.equals(attributeId)) { values = new String[1]; values[0] = datastream.DSMIME; } else if (Constants.DATASTREAM.CONTENT_LENGTH.uri.equals(attributeId)) { values = new String[1]; values[0] = Long.toString(datastream.DSSize); } else { LOG.debug("looking for unknown resource attribute=" + attributeId); } } else { LOG.debug("looking for unknown resource attribute=" + attributeId); } return values; } finally { long dur = System.currentTimeMillis() - getAttributeStartTime; LOG.debug("Locally getting the '" + attributeId + "' attribute for this resource took " + dur + "ms."); } } private final String getPid(EvaluationCtx context) { URI resourceIdType = null; URI resourceIdId = null; try { resourceIdType = new URI(StringAttribute.identifier); resourceIdId = new URI(Constants.OBJECT.PID.uri); } catch (URISyntaxException e) { LOG.error("Bad URI syntax", e); } EvaluationResult attribute = context.getResourceAttribute(resourceIdType, resourceIdId, null); Object element = getAttributeFromEvaluationResult(attribute); if (element == null) { LOG.debug("PolicyFinderModule:getPid" + " exit on " + "can't get contextId on request callback"); return null; } if (! (element instanceof StringAttribute)) { LOG.debug("PolicyFinderModule:getPid" + " exit on " + "couldn't get contextId from xacml request " + "non-string returned"); return null; } String pid = ((StringAttribute) element).getValue(); if (pid == null) { LOG.debug("PolicyFinderModule:getPid" + " exit on " + "null contextId"); return null; } return pid; } }
true
true
protected final Object getAttributeLocally(int designatorType, String attributeId, URI resourceCategory, EvaluationCtx context) { long getAttributeStartTime = System.currentTimeMillis(); try { String pid = getPid(context); if ("".equals(pid)) { LOG.debug("no pid"); return null; } LOG.debug("getResourceAttribute, pid=" + pid); DOReader reader = null; try { LOG.debug("pid="+pid); reader = doManager.getReader(Server.USE_CACHE, ReadOnlyContext.EMPTY, pid); } catch (ServerException e) { LOG.debug("couldn't get object reader"); return null; } String[] values = null; if (Constants.OBJECT.STATE.uri.equals(attributeId)) { try { values = new String[1]; values[0] = reader.GetObjectState(); LOG.debug("got " + Constants.OBJECT.STATE.uri + "=" + values[0]); } catch (ServerException e) { LOG.debug("failed getting " + Constants.OBJECT.STATE.uri); return null; } } else if (Constants.OBJECT.OBJECT_TYPE.uri.equals(attributeId)) { try { values = new String[1]; values[0] = reader.getOwnerId(); LOG.debug("got " + Constants.OBJECT.OBJECT_TYPE.uri + "=" + values[0]); } catch (ServerException e) { LOG.debug("failed getting " + Constants.OBJECT.OBJECT_TYPE.uri); return null; } } else if (Constants.OBJECT.OWNER.uri.equals(attributeId)) { try { values = new String[1]; values[0] = reader.getOwnerId(); LOG.debug("got " + Constants.OBJECT.OWNER.uri + "=" + values[0]); } catch (ServerException e) { LOG.debug("failed getting " + Constants.OBJECT.OWNER.uri); return null; } } else if (Constants.OBJECT.CONTENT_MODEL.uri.equals(attributeId)) { try { values = new String[1]; values[0] = reader.getContentModelId(); LOG.debug("got " + Constants.OBJECT.CONTENT_MODEL.uri + "=" + values[0]); } catch (ServerException e) { LOG.debug("failed getting " + Constants.OBJECT.CONTENT_MODEL.uri); return null; } } else if (Constants.OBJECT.CREATED_DATETIME.uri.equals(attributeId)) { try { values = new String[1]; values[0] = DateUtility.convertDateToString(reader.getCreateDate()); LOG.debug("got " + Constants.OBJECT.CREATED_DATETIME.uri + "=" + values[0]); } catch (ServerException e) { LOG.debug("failed getting " + Constants.OBJECT.CREATED_DATETIME.uri); return null; } } else if (Constants.OBJECT.LAST_MODIFIED_DATETIME.uri.equals(attributeId)) { try { values = new String[1]; values[0] = DateUtility.convertDateToString(reader.getLastModDate()); LOG.debug("got " + Constants.OBJECT.LAST_MODIFIED_DATETIME.uri + "=" + values[0]); } catch (ServerException e) { LOG.debug("failed getting " + Constants.OBJECT.LAST_MODIFIED_DATETIME.uri); return null; } } else if ((Constants.DATASTREAM.STATE.uri.equals(attributeId)) || (Constants.DATASTREAM.CONTROL_GROUP.uri.equals(attributeId)) || (Constants.DATASTREAM.FORMAT_URI.uri.equals(attributeId)) || (Constants.DATASTREAM.CREATED_DATETIME.uri.equals(attributeId)) || (Constants.DATASTREAM.INFO_TYPE.uri.equals(attributeId)) || (Constants.DATASTREAM.LOCATION.uri.equals(attributeId)) || (Constants.DATASTREAM.LOCATION_TYPE.uri.equals(attributeId)) || (Constants.DATASTREAM.MIME_TYPE.uri.equals(attributeId)) || (Constants.DATASTREAM.CONTENT_LENGTH.uri.equals(attributeId)) ) { String datastreamId = getDatastreamId(context); if ("".equals(datastreamId)) { LOG.debug("no datastreamId"); return null; } LOG.debug("datastreamId=" + datastreamId); Datastream datastream; try { datastream = reader.GetDatastream(datastreamId, new Date()); //right import (above)? } catch (ServerException e) { LOG.debug("couldn't get datastream"); return null; } if (datastream == null) { LOG.debug("got null datastream"); return null; } if (Constants.DATASTREAM.STATE.uri.equals(attributeId)) { values = new String[1]; values[0] = datastream.DSState; } else if (Constants.DATASTREAM.CONTROL_GROUP.uri.equals(attributeId)) { values = new String[1]; values[0] = datastream.DSControlGrp; } else if (Constants.DATASTREAM.FORMAT_URI.uri.equals(attributeId)) { values = new String[1]; values[0] = datastream.DSFormatURI; } else if (Constants.DATASTREAM.CREATED_DATETIME.uri.equals(attributeId)) { values = new String[1]; values[0] = DateUtility.convertDateToString(datastream.DSCreateDT); } else if (Constants.DATASTREAM.INFO_TYPE.uri.equals(attributeId)) { values = new String[1]; values[0] = datastream.DSInfoType; } else if (Constants.DATASTREAM.LOCATION.uri.equals(attributeId)) { values = new String[1]; values[0] = datastream.DSLocation; } else if (Constants.DATASTREAM.LOCATION_TYPE.uri.equals(attributeId)) { values = new String[1]; values[0] = datastream.DSLocationType; } else if (Constants.DATASTREAM.MIME_TYPE.uri.equals(attributeId)) { values = new String[1]; values[0] = datastream.DSMIME; } else if (Constants.DATASTREAM.CONTENT_LENGTH.uri.equals(attributeId)) { values = new String[1]; values[0] = Long.toString(datastream.DSSize); } else { LOG.debug("looking for unknown resource attribute=" + attributeId); } } else { LOG.debug("looking for unknown resource attribute=" + attributeId); } return values; } finally { long dur = System.currentTimeMillis() - getAttributeStartTime; LOG.debug("Locally getting the '" + attributeId + "' attribute for this resource took " + dur + "ms."); } }
protected final Object getAttributeLocally(int designatorType, String attributeId, URI resourceCategory, EvaluationCtx context) { long getAttributeStartTime = System.currentTimeMillis(); try { String pid = getPid(context); if ("".equals(pid)) { LOG.debug("no pid"); return null; } LOG.debug("getResourceAttribute, pid=" + pid); DOReader reader = null; try { LOG.debug("pid="+pid); reader = doManager.getReader(Server.USE_CACHE, ReadOnlyContext.EMPTY, pid); } catch (ServerException e) { LOG.debug("couldn't get object reader"); return null; } String[] values = null; if (Constants.OBJECT.STATE.uri.equals(attributeId)) { try { values = new String[1]; values[0] = reader.GetObjectState(); LOG.debug("got " + Constants.OBJECT.STATE.uri + "=" + values[0]); } catch (ServerException e) { LOG.debug("failed getting " + Constants.OBJECT.STATE.uri); return null; } } else if (Constants.OBJECT.OBJECT_TYPE.uri.equals(attributeId)) { try { values = new String[1]; values[0] = reader.getFedoraObjectType(); LOG.debug("got " + Constants.OBJECT.OBJECT_TYPE.uri + "=" + values[0]); } catch (ServerException e) { LOG.debug("failed getting " + Constants.OBJECT.OBJECT_TYPE.uri); return null; } } else if (Constants.OBJECT.OWNER.uri.equals(attributeId)) { try { values = new String[1]; values[0] = reader.getOwnerId(); LOG.debug("got " + Constants.OBJECT.OWNER.uri + "=" + values[0]); } catch (ServerException e) { LOG.debug("failed getting " + Constants.OBJECT.OWNER.uri); return null; } } else if (Constants.OBJECT.CONTENT_MODEL.uri.equals(attributeId)) { try { values = new String[1]; values[0] = reader.getContentModelId(); LOG.debug("got " + Constants.OBJECT.CONTENT_MODEL.uri + "=" + values[0]); } catch (ServerException e) { LOG.debug("failed getting " + Constants.OBJECT.CONTENT_MODEL.uri); return null; } } else if (Constants.OBJECT.CREATED_DATETIME.uri.equals(attributeId)) { try { values = new String[1]; values[0] = DateUtility.convertDateToString(reader.getCreateDate()); LOG.debug("got " + Constants.OBJECT.CREATED_DATETIME.uri + "=" + values[0]); } catch (ServerException e) { LOG.debug("failed getting " + Constants.OBJECT.CREATED_DATETIME.uri); return null; } } else if (Constants.OBJECT.LAST_MODIFIED_DATETIME.uri.equals(attributeId)) { try { values = new String[1]; values[0] = DateUtility.convertDateToString(reader.getLastModDate()); LOG.debug("got " + Constants.OBJECT.LAST_MODIFIED_DATETIME.uri + "=" + values[0]); } catch (ServerException e) { LOG.debug("failed getting " + Constants.OBJECT.LAST_MODIFIED_DATETIME.uri); return null; } } else if ((Constants.DATASTREAM.STATE.uri.equals(attributeId)) || (Constants.DATASTREAM.CONTROL_GROUP.uri.equals(attributeId)) || (Constants.DATASTREAM.FORMAT_URI.uri.equals(attributeId)) || (Constants.DATASTREAM.CREATED_DATETIME.uri.equals(attributeId)) || (Constants.DATASTREAM.INFO_TYPE.uri.equals(attributeId)) || (Constants.DATASTREAM.LOCATION.uri.equals(attributeId)) || (Constants.DATASTREAM.LOCATION_TYPE.uri.equals(attributeId)) || (Constants.DATASTREAM.MIME_TYPE.uri.equals(attributeId)) || (Constants.DATASTREAM.CONTENT_LENGTH.uri.equals(attributeId)) ) { String datastreamId = getDatastreamId(context); if ("".equals(datastreamId)) { LOG.debug("no datastreamId"); return null; } LOG.debug("datastreamId=" + datastreamId); Datastream datastream; try { datastream = reader.GetDatastream(datastreamId, new Date()); //right import (above)? } catch (ServerException e) { LOG.debug("couldn't get datastream"); return null; } if (datastream == null) { LOG.debug("got null datastream"); return null; } if (Constants.DATASTREAM.STATE.uri.equals(attributeId)) { values = new String[1]; values[0] = datastream.DSState; } else if (Constants.DATASTREAM.CONTROL_GROUP.uri.equals(attributeId)) { values = new String[1]; values[0] = datastream.DSControlGrp; } else if (Constants.DATASTREAM.FORMAT_URI.uri.equals(attributeId)) { values = new String[1]; values[0] = datastream.DSFormatURI; } else if (Constants.DATASTREAM.CREATED_DATETIME.uri.equals(attributeId)) { values = new String[1]; values[0] = DateUtility.convertDateToString(datastream.DSCreateDT); } else if (Constants.DATASTREAM.INFO_TYPE.uri.equals(attributeId)) { values = new String[1]; values[0] = datastream.DSInfoType; } else if (Constants.DATASTREAM.LOCATION.uri.equals(attributeId)) { values = new String[1]; values[0] = datastream.DSLocation; } else if (Constants.DATASTREAM.LOCATION_TYPE.uri.equals(attributeId)) { values = new String[1]; values[0] = datastream.DSLocationType; } else if (Constants.DATASTREAM.MIME_TYPE.uri.equals(attributeId)) { values = new String[1]; values[0] = datastream.DSMIME; } else if (Constants.DATASTREAM.CONTENT_LENGTH.uri.equals(attributeId)) { values = new String[1]; values[0] = Long.toString(datastream.DSSize); } else { LOG.debug("looking for unknown resource attribute=" + attributeId); } } else { LOG.debug("looking for unknown resource attribute=" + attributeId); } return values; } finally { long dur = System.currentTimeMillis() - getAttributeStartTime; LOG.debug("Locally getting the '" + attributeId + "' attribute for this resource took " + dur + "ms."); } }
diff --git a/ldbc_socialnet_dbgen/src/main/java/ldbc/socialnet/dbgen/serializer/CSV.java b/ldbc_socialnet_dbgen/src/main/java/ldbc/socialnet/dbgen/serializer/CSV.java index 4c4e4a9..09f870f 100644 --- a/ldbc_socialnet_dbgen/src/main/java/ldbc/socialnet/dbgen/serializer/CSV.java +++ b/ldbc_socialnet_dbgen/src/main/java/ldbc/socialnet/dbgen/serializer/CSV.java @@ -1,790 +1,790 @@ /* * Copyright (c) 2013 LDBC * Linked Data Benchmark Council (http://ldbc.eu) * * This file is part of ldbc_socialnet_dbgen. * * ldbc_socialnet_dbgen 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. * * ldbc_socialnet_dbgen 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 ldbc_socialnet_dbgen. If not, see <http://www.gnu.org/licenses/>. * * Copyright (C) 2011 OpenLink Software <[email protected]> * All Rights Reserved. * * 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; only Version 2 of the License dated * June 1991. * * 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package ldbc.socialnet.dbgen.serializer; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Iterator; import java.util.Vector; import ldbc.socialnet.dbgen.dictionary.IPAddressDictionary; import ldbc.socialnet.dbgen.dictionary.LanguageDictionary; import ldbc.socialnet.dbgen.dictionary.LocationDictionary; import ldbc.socialnet.dbgen.dictionary.TagDictionary; import ldbc.socialnet.dbgen.generator.DateGenerator; import ldbc.socialnet.dbgen.generator.ScalableGenerator; import ldbc.socialnet.dbgen.objects.Comment; import ldbc.socialnet.dbgen.objects.Friend; import ldbc.socialnet.dbgen.objects.Group; import ldbc.socialnet.dbgen.objects.GroupMemberShip; import ldbc.socialnet.dbgen.objects.Location; import ldbc.socialnet.dbgen.objects.Photo; import ldbc.socialnet.dbgen.objects.Post; import ldbc.socialnet.dbgen.objects.ReducedUserProfile; import ldbc.socialnet.dbgen.objects.UserExtraInfo; import ldbc.socialnet.dbgen.vocabulary.DBP; import ldbc.socialnet.dbgen.vocabulary.DBPOWL; import ldbc.socialnet.dbgen.vocabulary.SN; public class CSV implements Serializer { final String NEWLINE = "\n"; final String SEPARATOR = "|"; final String[] fileNames = { "tag", "post", "forum", "person", "comment", "place", "tagclass", "organisation", "person_likes_post", "person_hasInterest_tag", "person_knows_person", "person_speaks_language", "person_workAt_organisation", "person_studyAt_organisation", "person_isLocatedIn_place", "person_email_emailaddress", "post_isLocatedIn_place", "post_hasTag_tag", "post_hasCreator_person", "comment_isLocatedIn_place", "comment_replyOf_post", "comment_replyOf_comment", "comment_hasCreator_person", "tag_hasType_tagclass", "tagclass_isSubclassOf_tagclass", "place_isPartOf_place", "organisation_isLocatedIn_place", "forum_hasModerator_person", "forum_containerOf_post", "forum_hasTag_tag", "forum_hasMember_person" }; enum Files { TAG, POST, FORUM, PERSON, COMMENT, PLACE, TAGCLASS, ORGANISATION, PERSON_LIKE_POST, PERSON_INTEREST_TAG, PERSON_KNOWS_PERSON, PERSON_SPEAKS_LANGUAGE, PERSON_WORK_AT_ORGANISATION, PERSON_STUDY_AT_ORGANISATION, PERSON_LOCATED_IN_PLACE, PERSON_HAS_EMAIL_EMAIL, POST_LOCATED_PLACE, POST_HAS_TAG_TAG, POST_HAS_CREATOR_PERSON, COMMENT_LOCATED_PLACE, COMMENT_REPLY_OF_POST, COMMENT_REPLY_OF_COMMENT, COMMENT_HAS_CREATOR_PERSON, TAG_HAS_TYPE_TAGCLASS, TAGCLASS_IS_SUBCLASS_OF_TAGCLASS, PLACE_PART_OF_PLACE, ORGANISATION_BASED_NEAR_PLACE, FORUM_HAS_MODERATOR_PERSON, FORUM_CONTAINER_OF_POST, FORUM_HASTAG_TAG, FORUM_HASMEMBER_PERSON, NUM_FILES } final String[][] fieldNames = { {"id", "name", "url"}, {"id", "imageFile", "creationDate", "locationIP", "browserUsed", "language", "content"}, {"id", "title", "creationDate"}, {"id", "firstName", "lastName", "gender", "birthday", "creationDate", "locationIP", "browserUsed"}, {"id", "creationDate", "locationIP", "browserUsed", "content"}, {"id", "name", "url", "type"}, {"id", "name", "url"}, {"id", "type", "name", "url"}, {"Person.id", "Post.id", "creationDate"}, {"Person.id", "Tag.id"}, {"Person.id", "Person.id"}, {"Person.id", "language"}, {"Person.id", "Organisation.id", "workFrom"}, {"Person.id", "Organisation.id", "classYear"}, {"Person.id", "Place.id"}, {"Person.id", "email"}, {"Post.id", "Place.id"}, {"Post.id", "Tag.id"}, {"Post.id", "Person.id"}, {"Comment.id", "Place.id"}, {"Comment.id", "Post.id"}, {"Comment.id", "Comment.id"}, {"Comment.id", "Person.id"}, {"Tag.id", "TagClass.id"}, {"TagClass.id", "TagClass.id"}, {"Place.id", "Place.id"}, {"Organisation.id", "Place.id"}, {"Forum.id", "Person.id"}, {"Forum.id", "Post.id"}, {"Forum.id", "Tag.id"}, {"Forum.id", "Person.id", "joinDate"} }; private long nrTriples; private FileWriter[][] dataFileWriter; int[] currentWriter; long[] idList; static long membershipId = 0; static long friendshipId = 0; static long gpsId = 0; static long emailId = 0; static long ipId = 0; HashMap<Integer, Integer> printedTagClasses; HashMap<String, Integer> companyToCountry; HashMap<String, Integer> universityToCountry; Vector<String> vBrowserNames; Vector<Integer> locations; Vector<Integer> serializedLanguages; Vector<String> organisations; Vector<String> interests; Vector<String> tagList; Vector<String> ipList; GregorianCalendar date; LocationDictionary locationDic; LanguageDictionary languageDic; TagDictionary tagDic; IPAddressDictionary ipDic; public CSV(String file, boolean forwardChaining) { this(file, forwardChaining, 1); } public CSV(String file, boolean forwardChaining, int nrOfOutputFiles) { vBrowserNames = new Vector<String>(); locations = new Vector<Integer>(); organisations = new Vector<String>(); interests = new Vector<String>(); tagList = new Vector<String>(); ipList = new Vector<String>(); serializedLanguages = new Vector<Integer>(); printedTagClasses = new HashMap<Integer, Integer>(); idList = new long[Files.NUM_FILES.ordinal()]; currentWriter = new int[Files.NUM_FILES.ordinal()]; for (int i = 0; i < Files.NUM_FILES.ordinal(); i++) { idList[i] = 0; currentWriter[i] = 0; } date = new GregorianCalendar(); int nrOfDigits = ((int)Math.log10(nrOfOutputFiles)) + 1; String formatString = "%0" + nrOfDigits + "d"; try{ dataFileWriter = new FileWriter[nrOfOutputFiles][Files.NUM_FILES.ordinal()]; if(nrOfOutputFiles==1) { for (int i = 0; i < Files.NUM_FILES.ordinal(); i++) { this.dataFileWriter[0][i] = new FileWriter(file + fileNames[i] + ".csv"); } } else { for(int i=0;i<nrOfOutputFiles;i++) { for (int j = 0; j < Files.NUM_FILES.ordinal(); j++) { dataFileWriter[i][j] = new FileWriter(file + fileNames[j] + String.format(formatString, i+1) + ".csv"); } } } for(int i=0;i<nrOfOutputFiles;i++) { for (int j = 0; j < Files.NUM_FILES.ordinal(); j++) { Vector<String> arguments = new Vector<String>(); for (int k = 0; k < fieldNames[j].length; k++) { arguments.add(fieldNames[j][k]); } ToCSV(arguments, j); } } } catch(IOException e){ System.err.println("Could not open File for writing."); System.err.println(e.getMessage()); System.exit(-1); } nrTriples = 0l; } public CSV(String file, boolean forwardChaining, int nrOfOutputFiles, TagDictionary tagDic, Vector<String> _vBrowsers, HashMap<String, Integer> companyToCountry, HashMap<String, Integer> univesityToCountry, IPAddressDictionary ipDic, LocationDictionary locationDic, LanguageDictionary languageDic) { this(file, forwardChaining, nrOfOutputFiles); this.tagDic = tagDic; this.vBrowserNames = _vBrowsers; this.locationDic = locationDic; this.languageDic = languageDic; this.companyToCountry = companyToCountry; this.universityToCountry = univesityToCountry; this.ipDic = ipDic; } public Long triplesGenerated() { return nrTriples; } public void printTagHierarchy(Integer tagId) { Vector<String> arguments = new Vector<String>(); Integer tagClass = tagDic.getTagClass(tagId); arguments.add(tagId.toString()); arguments.add(tagClass.toString()); ToCSV(arguments, Files.TAG_HAS_TYPE_TAGCLASS.ordinal()); while (tagClass != -1 && !printedTagClasses.containsKey(tagClass)) { printedTagClasses.put(tagClass, tagClass); arguments.add(tagClass.toString()); arguments.add(tagDic.getClassName(tagClass)); if (tagDic.getClassName(tagClass).equals("Thing")) { arguments.add("http://www.w3.org/2002/07/owl#Thing"); } else { arguments.add(DBPOWL.getUrl(tagDic.getClassName(tagClass))); } ToCSV(arguments, Files.TAGCLASS.ordinal()); Integer parent = tagDic.getClassParent(tagClass); if (parent != -1) { arguments.add(tagClass.toString()); arguments.add(parent.toString()); ToCSV(arguments, Files.TAGCLASS_IS_SUBCLASS_OF_TAGCLASS.ordinal()); } tagClass = parent; } } public void ToCSV(Vector<String> arguments, int index) { StringBuffer result = new StringBuffer(); result.append(arguments.get(0)); for (int i = 1; i < arguments.size(); i++) { result.append(SEPARATOR); result.append(arguments.get(i)); } result.append(NEWLINE); WriteTo(result.toString(), index); arguments.clear(); idList[index]++; } public void WriteTo(String data, int index) { try { dataFileWriter[currentWriter[index]][index].append(data); currentWriter[index] = (currentWriter[index] + 1) % dataFileWriter.length; } catch (IOException e) { System.out.println("Cannot write to output file "); e.printStackTrace(); } } public void printLocationHierarchy(int baseId) { Vector<String> arguments = new Vector<String>(); ArrayList<Integer> areas = new ArrayList<Integer>(); do { areas.add(baseId); baseId = locationDic.belongsTo(baseId); } while (baseId != -1); for (int i = areas.size() - 1; i >= 0; i--) { if (locations.indexOf(areas.get(i)) == -1) { locations.add(areas.get(i)); //print location arguments.add(Integer.toString(areas.get(i))); arguments.add(locationDic.getLocationName(areas.get(i))); arguments.add(DBP.getUrl(locationDic.getLocationName(areas.get(i)))); arguments.add(locationDic.getType(areas.get(i))); ToCSV(arguments, Files.PLACE.ordinal()); if (locationDic.getType(areas.get(i)) == Location.CITY || locationDic.getType(areas.get(i)) == Location.COUNTRY) { arguments.add(Integer.toString(areas.get(i))); arguments.add(Integer.toString(areas.get(i+1))); ToCSV(arguments, Files.PLACE_PART_OF_PLACE.ordinal()); } } } } public void gatherData(ReducedUserProfile profile, UserExtraInfo extraInfo){ Vector<String> arguments = new Vector<String>(); if (extraInfo == null) { System.err.println("LDBC socialnet must serialize the extraInfo"); System.exit(-1); } printLocationHierarchy(extraInfo.getLocationId()); Iterator<String> itString = extraInfo.getCompanies().iterator(); while (itString.hasNext()) { String company = itString.next(); int parentId = companyToCountry.get(company); printLocationHierarchy(parentId); } printLocationHierarchy(universityToCountry.get(extraInfo.getOrganization())); printLocationHierarchy(ipDic.getLocation(profile.getIpAddress())); arguments.add(Integer.toString(profile.getAccountId())); arguments.add(extraInfo.getFirstName()); arguments.add(extraInfo.getLastName()); arguments.add(extraInfo.getGender()); if (profile.getBirthDay() != -1 ) { date.setTimeInMillis(profile.getBirthDay()); String dateString = DateGenerator.formatDate(date); arguments.add(dateString); } else { String empty = ""; arguments.add(empty); } date.setTimeInMillis(profile.getCreatedDate()); String dateString = DateGenerator.formatDateDetail(date); arguments.add(dateString); if (profile.getIpAddress() != null) { arguments.add(profile.getIpAddress().toString()); } else { String empty = ""; arguments.add(empty); } if (profile.getBrowserIdx() >= 0) { arguments.add(vBrowserNames.get(profile.getBrowserIdx())); } else { String empty = ""; arguments.add(empty); } ToCSV(arguments, Files.PERSON.ordinal()); Vector<Integer> languages = extraInfo.getLanguages(); for (int i = 0; i < languages.size(); i++) { arguments.add(Integer.toString(profile.getAccountId())); arguments.add(languageDic.getLanguagesName(languages.get(i))); ToCSV(arguments, Files.PERSON_SPEAKS_LANGUAGE.ordinal()); } itString = extraInfo.getEmail().iterator(); while (itString.hasNext()){ String email = itString.next(); arguments.add(Integer.toString(profile.getAccountId())); arguments.add(email); ToCSV(arguments, Files.PERSON_HAS_EMAIL_EMAIL.ordinal()); } arguments.add(Integer.toString(profile.getAccountId())); arguments.add(Integer.toString(extraInfo.getLocationId())); ToCSV(arguments, Files.PERSON_LOCATED_IN_PLACE.ordinal()); int organisationId = -1; if (!extraInfo.getOrganization().equals("")){ organisationId = organisations.indexOf(extraInfo.getOrganization()); if(organisationId == -1) { organisationId = organisations.size(); organisations.add(extraInfo.getOrganization()); arguments.add(SN.formId(organisationId)); arguments.add(ScalableGenerator.OrganisationType.university.toString()); arguments.add(extraInfo.getOrganization()); arguments.add(DBP.getUrl(extraInfo.getOrganization())); ToCSV(arguments, Files.ORGANISATION.ordinal()); arguments.add(SN.formId(organisationId)); arguments.add(Integer.toString(universityToCountry.get(extraInfo.getOrganization()))); ToCSV(arguments, Files.ORGANISATION_BASED_NEAR_PLACE.ordinal()); } } if (extraInfo.getClassYear() != -1 ) { date.setTimeInMillis(extraInfo.getClassYear()); dateString = DateGenerator.formatYear(date); arguments.add(Integer.toString(profile.getAccountId())); arguments.add(SN.formId(organisationId)); arguments.add(dateString); ToCSV(arguments, Files.PERSON_STUDY_AT_ORGANISATION.ordinal()); } itString = extraInfo.getCompanies().iterator(); while (itString.hasNext()) { String company = itString.next(); organisationId = organisations.indexOf(company); if(organisationId == -1) { organisationId = organisations.size(); organisations.add(company); arguments.add(SN.formId(organisationId)); arguments.add(ScalableGenerator.OrganisationType.company.toString()); arguments.add(company); arguments.add(DBP.getUrl(company)); ToCSV(arguments, Files.ORGANISATION.ordinal()); arguments.add(SN.formId(organisationId)); arguments.add(Integer.toString(companyToCountry.get(company))); ToCSV(arguments, Files.ORGANISATION_BASED_NEAR_PLACE.ordinal()); } date.setTimeInMillis(extraInfo.getWorkFrom(company)); dateString = DateGenerator.formatYear(date); arguments.add(Integer.toString(profile.getAccountId())); arguments.add(SN.formId(organisationId)); arguments.add(dateString); ToCSV(arguments, Files.PERSON_WORK_AT_ORGANISATION.ordinal()); } Iterator<Integer> itInteger = profile.getSetOfTags().iterator(); while (itInteger.hasNext()){ Integer interestIdx = itInteger.next(); String interest = tagDic.getName(interestIdx); if (interests.indexOf(interest) == -1) { interests.add(interest); arguments.add(Integer.toString(interestIdx)); arguments.add(interest.replace("\"", "\\\"")); arguments.add(DBP.getUrl(interest)); ToCSV(arguments, Files.TAG.ordinal()); printTagHierarchy(interestIdx); } arguments.add(Integer.toString(profile.getAccountId())); arguments.add(Integer.toString(interestIdx)); ToCSV(arguments, Files.PERSON_INTEREST_TAG.ordinal()); } Friend friends[] = profile.getFriendList(); for (int i = 0; i < friends.length; i ++) { if (friends[i] != null && friends[i].getCreatedTime() != -1){ arguments.add(Integer.toString(profile.getAccountId())); arguments.add(Integer.toString(friends[i].getFriendAcc())); ToCSV(arguments,Files.PERSON_KNOWS_PERSON.ordinal()); } } //The forums of the user date.setTimeInMillis(profile.getCreatedDate()); dateString = DateGenerator.formatDateDetail(date); String title = "Wall of " + extraInfo.getFirstName() + " " + extraInfo.getLastName(); arguments.add(SN.formId(profile.getForumWallId())); arguments.add(title); arguments.add(dateString); ToCSV(arguments,Files.FORUM.ordinal()); arguments.add(SN.formId(profile.getForumWallId())); arguments.add(Integer.toString(profile.getAccountId())); ToCSV(arguments,Files.FORUM_HAS_MODERATOR_PERSON.ordinal()); itInteger = profile.getSetOfTags().iterator(); while (itInteger.hasNext()){ Integer interestIdx = itInteger.next(); - arguments.add(Integer.toString(profile.getAccountId())); + arguments.add(SN.formId(profile.getForumWallId())); arguments.add(Integer.toString(interestIdx)); ToCSV(arguments, Files.FORUM_HASTAG_TAG.ordinal()); } for (int i = 0; i < friends.length; i ++){ if (friends[i] != null && friends[i].getCreatedTime() != -1){ date.setTimeInMillis(friends[i].getCreatedTime()); dateString = DateGenerator.formatDateDetail(date); arguments.add(SN.formId(profile.getForumWallId())); arguments.add(Integer.toString(friends[i].getFriendAcc())); arguments.add(dateString); ToCSV(arguments,Files.FORUM_HASMEMBER_PERSON.ordinal()); } } } public void gatherData(Post post){ Vector<String> arguments = new Vector<String>(); String empty = ""; arguments.add(SN.formId(post.getPostId())); arguments.add(empty); date.setTimeInMillis(post.getCreatedDate()); String dateString = DateGenerator.formatDateDetail(date); arguments.add(dateString); if (post.getIpAddress() != null) { arguments.add(post.getIpAddress().toString()); } else { arguments.add(empty); } if (post.getBrowserIdx() != -1){ arguments.add(vBrowserNames.get(post.getBrowserIdx())); } else { arguments.add(empty); } if (post.getLanguage() != -1) { arguments.add(languageDic.getLanguagesName(post.getLanguage())); } else { arguments.add(empty); } arguments.add(post.getContent()); ToCSV(arguments, Files.POST.ordinal()); if (post.getIpAddress() != null) { arguments.add(SN.formId(post.getPostId())); arguments.add(Integer.toString(ipDic.getLocation(post.getIpAddress()))); ToCSV(arguments, Files.POST_LOCATED_PLACE.ordinal()); } arguments.add(SN.formId(post.getForumId())); arguments.add(SN.formId(post.getPostId())); ToCSV(arguments, Files.FORUM_CONTAINER_OF_POST.ordinal()); arguments.add(SN.formId(post.getPostId())); arguments.add(Integer.toString(post.getAuthorId())); ToCSV(arguments, Files.POST_HAS_CREATOR_PERSON.ordinal()); Iterator<Integer> it = post.getTags().iterator(); while (it.hasNext()) { Integer tagId = it.next(); String tag = tagDic.getName(tagId); if (interests.indexOf(tag) == -1) { interests.add(tag); arguments.add(Integer.toString(tagId)); arguments.add(tag.replace("\"", "\\\"")); arguments.add(DBP.getUrl(tag)); ToCSV(arguments, Files.TAG.ordinal()); printTagHierarchy(tagId); } arguments.add(SN.formId(post.getPostId())); arguments.add(Integer.toString(tagId)); ToCSV(arguments, Files.POST_HAS_TAG_TAG.ordinal()); } int userLikes[] = post.getInterestedUserAccs(); long likeTimestamps[] = post.getInterestedUserAccsTimestamp(); for (int i = 0; i < userLikes.length; i ++) { date.setTimeInMillis(likeTimestamps[i]); dateString = DateGenerator.formatDateDetail(date); arguments.add(Integer.toString(userLikes[i])); arguments.add(SN.formId(post.getPostId())); arguments.add(dateString); ToCSV(arguments, Files.PERSON_LIKE_POST.ordinal()); } } public void gatherData(Comment comment){ Vector<String> arguments = new Vector<String>(); date.setTimeInMillis(comment.getCreateDate()); String dateString = DateGenerator.formatDateDetail(date); arguments.add(SN.formId(comment.getCommentId())); arguments.add(dateString); if (comment.getIpAddress() != null) { arguments.add(comment.getIpAddress().toString()); } else { String empty = ""; arguments.add(empty); } if (comment.getBrowserIdx() != -1){ arguments.add(vBrowserNames.get(comment.getBrowserIdx())); } else { String empty = ""; arguments.add(empty); } arguments.add(comment.getContent()); ToCSV(arguments, Files.COMMENT.ordinal()); if (comment.getReply_of() == -1) { arguments.add(SN.formId(comment.getCommentId())); arguments.add(SN.formId(comment.getPostId())); ToCSV(arguments, Files.COMMENT_REPLY_OF_POST.ordinal()); } else { arguments.add(SN.formId(comment.getCommentId())); arguments.add(SN.formId(comment.getReply_of())); ToCSV(arguments, Files.COMMENT_REPLY_OF_COMMENT.ordinal()); } if (comment.getIpAddress() != null) { arguments.add(SN.formId(comment.getPostId())); arguments.add(Integer.toString(ipDic.getLocation(comment.getIpAddress()))); ToCSV(arguments, Files.COMMENT_LOCATED_PLACE.ordinal()); } arguments.add(SN.formId(comment.getCommentId())); arguments.add(Integer.toString(comment.getAuthorId())); ToCSV(arguments, Files.COMMENT_HAS_CREATOR_PERSON.ordinal()); } public void gatherData(Photo photo){ Vector<String> arguments = new Vector<String>(); String empty = ""; arguments.add(SN.formId(photo.getPhotoId())); arguments.add(photo.getImage()); date.setTimeInMillis(photo.getTakenTime()); String dateString = DateGenerator.formatDateDetail(date); arguments.add(dateString); if (photo.getIpAddress() != null) { arguments.add(photo.getIpAddress().toString()); } else { arguments.add(empty); } if (photo.getBrowserIdx() != -1){ arguments.add(vBrowserNames.get(photo.getBrowserIdx())); } else { arguments.add(empty); } arguments.add(empty); arguments.add(empty); ToCSV(arguments, Files.POST.ordinal()); if (photo.getIpAddress() != null) { arguments.add(SN.formId(photo.getPhotoId())); arguments.add(Integer.toString(ipDic.getLocation(photo.getIpAddress()))); ToCSV(arguments, Files.POST_LOCATED_PLACE.ordinal()); } arguments.add(SN.formId(photo.getPhotoId())); arguments.add(Integer.toString(photo.getCreatorId())); ToCSV(arguments, Files.POST_HAS_CREATOR_PERSON.ordinal()); arguments.add(SN.formId(photo.getAlbumId())); arguments.add(SN.formId(photo.getPhotoId())); ToCSV(arguments, Files.FORUM_CONTAINER_OF_POST.ordinal()); Iterator<Integer> it = photo.getTags().iterator(); while (it.hasNext()) { Integer tagId = it.next(); String tag = tagDic.getName(tagId); if (interests.indexOf(tag) == -1) { interests.add(tag); arguments.add(Integer.toString(tagId)); arguments.add(tag.replace("\"", "\\\"")); arguments.add(DBP.getUrl(tag)); ToCSV(arguments, Files.TAG.ordinal()); printTagHierarchy(tagId); } arguments.add(SN.formId(photo.getPhotoId())); arguments.add(Integer.toString(tagId)); ToCSV(arguments, Files.POST_HAS_TAG_TAG.ordinal()); } int userLikes[] = photo.getInterestedUserAccs(); long likeTimestamps[] = photo.getInterestedUserAccsTimestamp(); for (int i = 0; i < userLikes.length; i ++) { date.setTimeInMillis(likeTimestamps[i]); dateString = DateGenerator.formatDateDetail(date); arguments.add(Integer.toString(userLikes[i])); arguments.add(SN.formId(photo.getPhotoId())); arguments.add(dateString); ToCSV(arguments, Files.PERSON_LIKE_POST.ordinal()); } } public void gatherData(Group group) { Vector<String> arguments = new Vector<String>(); date.setTimeInMillis(group.getCreatedDate()); String dateString = DateGenerator.formatDateDetail(date); arguments.add(SN.formId(group.getForumWallId())); arguments.add(group.getGroupName()); arguments.add(dateString); ToCSV(arguments,Files.FORUM.ordinal()); arguments.add(SN.formId(group.getForumWallId())); arguments.add(Integer.toString(group.getModeratorId())); ToCSV(arguments,Files.FORUM_HAS_MODERATOR_PERSON.ordinal()); Integer groupTags[] = group.getTags(); for (int i = 0; i < groupTags.length; i ++) { String interest = tagDic.getName(groupTags[i]); if (interests.indexOf(interest) == -1) { interests.add(interest); arguments.add(Integer.toString(groupTags[i])); arguments.add(interest.replace("\"", "\\\"")); arguments.add(DBP.getUrl(interest)); ToCSV(arguments, Files.TAG.ordinal()); printTagHierarchy(groupTags[i]); } arguments.add(SN.formId(group.getForumWallId())); arguments.add(Integer.toString(groupTags[i])); ToCSV(arguments,Files.FORUM_HASTAG_TAG.ordinal()); } GroupMemberShip memberShips[] = group.getMemberShips(); int numMemberAdded = group.getNumMemberAdded(); for (int i = 0; i < numMemberAdded; i ++) { date.setTimeInMillis(memberShips[i].getJoinDate()); dateString = DateGenerator.formatDateDetail(date); arguments.add(SN.formId(group.getForumWallId())); arguments.add(Integer.toString(memberShips[i].getUserId())); arguments.add(dateString); ToCSV(arguments,Files.FORUM_HASMEMBER_PERSON.ordinal()); } } public void serialize() { try { for (int i = 0; i < dataFileWriter.length; i++) { for (int j = 0; j < Files.NUM_FILES.ordinal(); j++) { dataFileWriter[i][j].flush(); dataFileWriter[i][j].close(); } } } catch(IOException e) { System.err.println(e.getMessage()); System.exit(-1); } } }
true
true
public void gatherData(ReducedUserProfile profile, UserExtraInfo extraInfo){ Vector<String> arguments = new Vector<String>(); if (extraInfo == null) { System.err.println("LDBC socialnet must serialize the extraInfo"); System.exit(-1); } printLocationHierarchy(extraInfo.getLocationId()); Iterator<String> itString = extraInfo.getCompanies().iterator(); while (itString.hasNext()) { String company = itString.next(); int parentId = companyToCountry.get(company); printLocationHierarchy(parentId); } printLocationHierarchy(universityToCountry.get(extraInfo.getOrganization())); printLocationHierarchy(ipDic.getLocation(profile.getIpAddress())); arguments.add(Integer.toString(profile.getAccountId())); arguments.add(extraInfo.getFirstName()); arguments.add(extraInfo.getLastName()); arguments.add(extraInfo.getGender()); if (profile.getBirthDay() != -1 ) { date.setTimeInMillis(profile.getBirthDay()); String dateString = DateGenerator.formatDate(date); arguments.add(dateString); } else { String empty = ""; arguments.add(empty); } date.setTimeInMillis(profile.getCreatedDate()); String dateString = DateGenerator.formatDateDetail(date); arguments.add(dateString); if (profile.getIpAddress() != null) { arguments.add(profile.getIpAddress().toString()); } else { String empty = ""; arguments.add(empty); } if (profile.getBrowserIdx() >= 0) { arguments.add(vBrowserNames.get(profile.getBrowserIdx())); } else { String empty = ""; arguments.add(empty); } ToCSV(arguments, Files.PERSON.ordinal()); Vector<Integer> languages = extraInfo.getLanguages(); for (int i = 0; i < languages.size(); i++) { arguments.add(Integer.toString(profile.getAccountId())); arguments.add(languageDic.getLanguagesName(languages.get(i))); ToCSV(arguments, Files.PERSON_SPEAKS_LANGUAGE.ordinal()); } itString = extraInfo.getEmail().iterator(); while (itString.hasNext()){ String email = itString.next(); arguments.add(Integer.toString(profile.getAccountId())); arguments.add(email); ToCSV(arguments, Files.PERSON_HAS_EMAIL_EMAIL.ordinal()); } arguments.add(Integer.toString(profile.getAccountId())); arguments.add(Integer.toString(extraInfo.getLocationId())); ToCSV(arguments, Files.PERSON_LOCATED_IN_PLACE.ordinal()); int organisationId = -1; if (!extraInfo.getOrganization().equals("")){ organisationId = organisations.indexOf(extraInfo.getOrganization()); if(organisationId == -1) { organisationId = organisations.size(); organisations.add(extraInfo.getOrganization()); arguments.add(SN.formId(organisationId)); arguments.add(ScalableGenerator.OrganisationType.university.toString()); arguments.add(extraInfo.getOrganization()); arguments.add(DBP.getUrl(extraInfo.getOrganization())); ToCSV(arguments, Files.ORGANISATION.ordinal()); arguments.add(SN.formId(organisationId)); arguments.add(Integer.toString(universityToCountry.get(extraInfo.getOrganization()))); ToCSV(arguments, Files.ORGANISATION_BASED_NEAR_PLACE.ordinal()); } } if (extraInfo.getClassYear() != -1 ) { date.setTimeInMillis(extraInfo.getClassYear()); dateString = DateGenerator.formatYear(date); arguments.add(Integer.toString(profile.getAccountId())); arguments.add(SN.formId(organisationId)); arguments.add(dateString); ToCSV(arguments, Files.PERSON_STUDY_AT_ORGANISATION.ordinal()); } itString = extraInfo.getCompanies().iterator(); while (itString.hasNext()) { String company = itString.next(); organisationId = organisations.indexOf(company); if(organisationId == -1) { organisationId = organisations.size(); organisations.add(company); arguments.add(SN.formId(organisationId)); arguments.add(ScalableGenerator.OrganisationType.company.toString()); arguments.add(company); arguments.add(DBP.getUrl(company)); ToCSV(arguments, Files.ORGANISATION.ordinal()); arguments.add(SN.formId(organisationId)); arguments.add(Integer.toString(companyToCountry.get(company))); ToCSV(arguments, Files.ORGANISATION_BASED_NEAR_PLACE.ordinal()); } date.setTimeInMillis(extraInfo.getWorkFrom(company)); dateString = DateGenerator.formatYear(date); arguments.add(Integer.toString(profile.getAccountId())); arguments.add(SN.formId(organisationId)); arguments.add(dateString); ToCSV(arguments, Files.PERSON_WORK_AT_ORGANISATION.ordinal()); } Iterator<Integer> itInteger = profile.getSetOfTags().iterator(); while (itInteger.hasNext()){ Integer interestIdx = itInteger.next(); String interest = tagDic.getName(interestIdx); if (interests.indexOf(interest) == -1) { interests.add(interest); arguments.add(Integer.toString(interestIdx)); arguments.add(interest.replace("\"", "\\\"")); arguments.add(DBP.getUrl(interest)); ToCSV(arguments, Files.TAG.ordinal()); printTagHierarchy(interestIdx); } arguments.add(Integer.toString(profile.getAccountId())); arguments.add(Integer.toString(interestIdx)); ToCSV(arguments, Files.PERSON_INTEREST_TAG.ordinal()); } Friend friends[] = profile.getFriendList(); for (int i = 0; i < friends.length; i ++) { if (friends[i] != null && friends[i].getCreatedTime() != -1){ arguments.add(Integer.toString(profile.getAccountId())); arguments.add(Integer.toString(friends[i].getFriendAcc())); ToCSV(arguments,Files.PERSON_KNOWS_PERSON.ordinal()); } } //The forums of the user date.setTimeInMillis(profile.getCreatedDate()); dateString = DateGenerator.formatDateDetail(date); String title = "Wall of " + extraInfo.getFirstName() + " " + extraInfo.getLastName(); arguments.add(SN.formId(profile.getForumWallId())); arguments.add(title); arguments.add(dateString); ToCSV(arguments,Files.FORUM.ordinal()); arguments.add(SN.formId(profile.getForumWallId())); arguments.add(Integer.toString(profile.getAccountId())); ToCSV(arguments,Files.FORUM_HAS_MODERATOR_PERSON.ordinal()); itInteger = profile.getSetOfTags().iterator(); while (itInteger.hasNext()){ Integer interestIdx = itInteger.next(); arguments.add(Integer.toString(profile.getAccountId())); arguments.add(Integer.toString(interestIdx)); ToCSV(arguments, Files.FORUM_HASTAG_TAG.ordinal()); } for (int i = 0; i < friends.length; i ++){ if (friends[i] != null && friends[i].getCreatedTime() != -1){ date.setTimeInMillis(friends[i].getCreatedTime()); dateString = DateGenerator.formatDateDetail(date); arguments.add(SN.formId(profile.getForumWallId())); arguments.add(Integer.toString(friends[i].getFriendAcc())); arguments.add(dateString); ToCSV(arguments,Files.FORUM_HASMEMBER_PERSON.ordinal()); } } }
public void gatherData(ReducedUserProfile profile, UserExtraInfo extraInfo){ Vector<String> arguments = new Vector<String>(); if (extraInfo == null) { System.err.println("LDBC socialnet must serialize the extraInfo"); System.exit(-1); } printLocationHierarchy(extraInfo.getLocationId()); Iterator<String> itString = extraInfo.getCompanies().iterator(); while (itString.hasNext()) { String company = itString.next(); int parentId = companyToCountry.get(company); printLocationHierarchy(parentId); } printLocationHierarchy(universityToCountry.get(extraInfo.getOrganization())); printLocationHierarchy(ipDic.getLocation(profile.getIpAddress())); arguments.add(Integer.toString(profile.getAccountId())); arguments.add(extraInfo.getFirstName()); arguments.add(extraInfo.getLastName()); arguments.add(extraInfo.getGender()); if (profile.getBirthDay() != -1 ) { date.setTimeInMillis(profile.getBirthDay()); String dateString = DateGenerator.formatDate(date); arguments.add(dateString); } else { String empty = ""; arguments.add(empty); } date.setTimeInMillis(profile.getCreatedDate()); String dateString = DateGenerator.formatDateDetail(date); arguments.add(dateString); if (profile.getIpAddress() != null) { arguments.add(profile.getIpAddress().toString()); } else { String empty = ""; arguments.add(empty); } if (profile.getBrowserIdx() >= 0) { arguments.add(vBrowserNames.get(profile.getBrowserIdx())); } else { String empty = ""; arguments.add(empty); } ToCSV(arguments, Files.PERSON.ordinal()); Vector<Integer> languages = extraInfo.getLanguages(); for (int i = 0; i < languages.size(); i++) { arguments.add(Integer.toString(profile.getAccountId())); arguments.add(languageDic.getLanguagesName(languages.get(i))); ToCSV(arguments, Files.PERSON_SPEAKS_LANGUAGE.ordinal()); } itString = extraInfo.getEmail().iterator(); while (itString.hasNext()){ String email = itString.next(); arguments.add(Integer.toString(profile.getAccountId())); arguments.add(email); ToCSV(arguments, Files.PERSON_HAS_EMAIL_EMAIL.ordinal()); } arguments.add(Integer.toString(profile.getAccountId())); arguments.add(Integer.toString(extraInfo.getLocationId())); ToCSV(arguments, Files.PERSON_LOCATED_IN_PLACE.ordinal()); int organisationId = -1; if (!extraInfo.getOrganization().equals("")){ organisationId = organisations.indexOf(extraInfo.getOrganization()); if(organisationId == -1) { organisationId = organisations.size(); organisations.add(extraInfo.getOrganization()); arguments.add(SN.formId(organisationId)); arguments.add(ScalableGenerator.OrganisationType.university.toString()); arguments.add(extraInfo.getOrganization()); arguments.add(DBP.getUrl(extraInfo.getOrganization())); ToCSV(arguments, Files.ORGANISATION.ordinal()); arguments.add(SN.formId(organisationId)); arguments.add(Integer.toString(universityToCountry.get(extraInfo.getOrganization()))); ToCSV(arguments, Files.ORGANISATION_BASED_NEAR_PLACE.ordinal()); } } if (extraInfo.getClassYear() != -1 ) { date.setTimeInMillis(extraInfo.getClassYear()); dateString = DateGenerator.formatYear(date); arguments.add(Integer.toString(profile.getAccountId())); arguments.add(SN.formId(organisationId)); arguments.add(dateString); ToCSV(arguments, Files.PERSON_STUDY_AT_ORGANISATION.ordinal()); } itString = extraInfo.getCompanies().iterator(); while (itString.hasNext()) { String company = itString.next(); organisationId = organisations.indexOf(company); if(organisationId == -1) { organisationId = organisations.size(); organisations.add(company); arguments.add(SN.formId(organisationId)); arguments.add(ScalableGenerator.OrganisationType.company.toString()); arguments.add(company); arguments.add(DBP.getUrl(company)); ToCSV(arguments, Files.ORGANISATION.ordinal()); arguments.add(SN.formId(organisationId)); arguments.add(Integer.toString(companyToCountry.get(company))); ToCSV(arguments, Files.ORGANISATION_BASED_NEAR_PLACE.ordinal()); } date.setTimeInMillis(extraInfo.getWorkFrom(company)); dateString = DateGenerator.formatYear(date); arguments.add(Integer.toString(profile.getAccountId())); arguments.add(SN.formId(organisationId)); arguments.add(dateString); ToCSV(arguments, Files.PERSON_WORK_AT_ORGANISATION.ordinal()); } Iterator<Integer> itInteger = profile.getSetOfTags().iterator(); while (itInteger.hasNext()){ Integer interestIdx = itInteger.next(); String interest = tagDic.getName(interestIdx); if (interests.indexOf(interest) == -1) { interests.add(interest); arguments.add(Integer.toString(interestIdx)); arguments.add(interest.replace("\"", "\\\"")); arguments.add(DBP.getUrl(interest)); ToCSV(arguments, Files.TAG.ordinal()); printTagHierarchy(interestIdx); } arguments.add(Integer.toString(profile.getAccountId())); arguments.add(Integer.toString(interestIdx)); ToCSV(arguments, Files.PERSON_INTEREST_TAG.ordinal()); } Friend friends[] = profile.getFriendList(); for (int i = 0; i < friends.length; i ++) { if (friends[i] != null && friends[i].getCreatedTime() != -1){ arguments.add(Integer.toString(profile.getAccountId())); arguments.add(Integer.toString(friends[i].getFriendAcc())); ToCSV(arguments,Files.PERSON_KNOWS_PERSON.ordinal()); } } //The forums of the user date.setTimeInMillis(profile.getCreatedDate()); dateString = DateGenerator.formatDateDetail(date); String title = "Wall of " + extraInfo.getFirstName() + " " + extraInfo.getLastName(); arguments.add(SN.formId(profile.getForumWallId())); arguments.add(title); arguments.add(dateString); ToCSV(arguments,Files.FORUM.ordinal()); arguments.add(SN.formId(profile.getForumWallId())); arguments.add(Integer.toString(profile.getAccountId())); ToCSV(arguments,Files.FORUM_HAS_MODERATOR_PERSON.ordinal()); itInteger = profile.getSetOfTags().iterator(); while (itInteger.hasNext()){ Integer interestIdx = itInteger.next(); arguments.add(SN.formId(profile.getForumWallId())); arguments.add(Integer.toString(interestIdx)); ToCSV(arguments, Files.FORUM_HASTAG_TAG.ordinal()); } for (int i = 0; i < friends.length; i ++){ if (friends[i] != null && friends[i].getCreatedTime() != -1){ date.setTimeInMillis(friends[i].getCreatedTime()); dateString = DateGenerator.formatDateDetail(date); arguments.add(SN.formId(profile.getForumWallId())); arguments.add(Integer.toString(friends[i].getFriendAcc())); arguments.add(dateString); ToCSV(arguments,Files.FORUM_HASMEMBER_PERSON.ordinal()); } } }
diff --git a/web/src/main/java/org/fao/geonet/kernel/mef/Importer.java b/web/src/main/java/org/fao/geonet/kernel/mef/Importer.java index c23a6aa126..ca94cddf59 100644 --- a/web/src/main/java/org/fao/geonet/kernel/mef/Importer.java +++ b/web/src/main/java/org/fao/geonet/kernel/mef/Importer.java @@ -1,632 +1,639 @@ //============================================================================= //=== Copyright (C) 2001-2007 Food and Agriculture Organization of the //=== United Nations (FAO-UN), United Nations World Food Programme (WFP) //=== and United Nations Environment Programme (UNEP) //=== //=== 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, write to the Free Software //=== Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA //=== //=== Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, //=== Rome - Italy. email: [email protected] //============================================================================== package org.fao.geonet.kernel.mef; import jeeves.exceptions.BadFormatEx; import jeeves.resources.dbms.Dbms; import jeeves.server.context.ServiceContext; import jeeves.utils.BinaryFile; import jeeves.utils.Log; import jeeves.utils.Util; import jeeves.utils.Xml; import org.fao.geonet.GeonetContext; import org.fao.geonet.constants.Geonet; import org.fao.geonet.constants.Params; import org.fao.geonet.exceptions.NoSchemaMatchesException; import org.fao.geonet.exceptions.UnAuthorizedException; import org.fao.geonet.kernel.DataManager; import org.fao.geonet.lib.Lib; import org.fao.geonet.util.ISODate; import org.fao.oaipmh.exceptions.BadArgumentException; import org.jdom.Element; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.UUID; public class Importer { public static List<String> doImport(final Element params, final ServiceContext context, File mefFile, final String stylePath) throws Exception { return doImport(params, context, mefFile, stylePath, false); } public static List<String> doImport(final Element params, final ServiceContext context, File mefFile, final String stylePath, final boolean indexGroup) throws Exception { final GeonetContext gc = (GeonetContext) context .getHandlerContext(Geonet.CONTEXT_NAME); final DataManager dm = gc.getDataManager(); // Load preferred schema and set to iso19139 by default final String preferredSchema = (gc.getHandlerConfig() .getMandatoryValue("preferredSchema") != null ? gc .getHandlerConfig().getMandatoryValue("preferredSchema") : "iso19139"); final Dbms dbms = (Dbms) context.getResourceManager().open( Geonet.Res.MAIN_DB); final List<String> id = new ArrayList<String>(); final List<Element> md = new ArrayList<Element>(); final List<Element> fc = new ArrayList<Element>(); // Try to define MEF version from mef file not from parameter String fileType = Util.getParam(params, "file_type", "mef"); if (fileType.equals("mef")) { MEFLib.Version version = MEFLib.getMEFVersion(mefFile); if (version.equals(MEFLib.Version.V2)) fileType = "mef2"; } IVisitor visitor; if (fileType.equals("single")) visitor = new XmlVisitor(); else if (fileType.equals("mef")) visitor = new MEFVisitor(); else if (fileType.equals("mef2")) visitor = new MEF2Visitor(); else throw new BadArgumentException("Bad file type parameter."); // --- import metadata from MEF, Xml, ZIP files MEFLib.visit(mefFile, visitor, new IMEFVisitor() { public void handleMetadata(Element metadata, int index) throws Exception { if(Log.isDebugEnabled(Geonet.MEF)) Log.debug(Geonet.MEF, "Collecting metadata:\n" + Xml.getString(metadata)); md.add(index, metadata); } public void handleMetadataFiles(File[] Files, int index) throws Exception { + String lastUnknownMetadataFolderName=null; if(Log.isDebugEnabled(Geonet.MEF)) Log.debug(Geonet.MEF, "Multiple metadata files"); Element metadataValidForImport = null; for (File file : Files) { if (file != null && !file.isDirectory()) { Element metadata = Xml.loadFile(file); try { String metadataSchema = dm.autodetectSchema(metadata, null); // If local node doesn't know metadata // schema try to load next xml file. if (metadataSchema == null) { continue; } // If schema is preferred local node schema // load that file. if (metadataSchema.equals(preferredSchema)) { if(Log.isDebugEnabled(Geonet.MEF)) { Log.debug(Geonet.MEF, "Found metadata file " - + file.getName() + + file.getParentFile().getParentFile().getName() + File.separator + file.getParentFile().getName() + File.separator + file.getName() + " with preferred schema (" + preferredSchema + ")."); } handleMetadata(metadata, index); return; } else { if(Log.isDebugEnabled(Geonet.MEF)) { Log.debug(Geonet.MEF, "Found metadata file " - + file.getName() + " with known schema (" + + file.getParentFile().getParentFile().getName() + File.separator + file.getParentFile().getName() + File.separator + file.getName() + + " with known schema (" + metadataSchema + ")."); } metadataValidForImport = metadata; } } catch (NoSchemaMatchesException e) { + // Important folder name to identify metadata should be ../../ + lastUnknownMetadataFolderName=file.getParentFile().getParentFile().getName() + File.separator + file.getParentFile().getName() + File.separator; + Log.debug(Geonet.MEF, "No schema match for " + + lastUnknownMetadataFolderName + file.getName() + + "."); continue; } } } // Import a valid metadata if not one found // with preferred schema. if (metadataValidForImport != null) { Log .debug(Geonet.MEF, "Importing metadata with valide schema but not preferred one."); handleMetadata(metadataValidForImport, index); - } else - throw new BadFormatEx("No valid metadata file found."); + } else + throw new BadFormatEx("No valid metadata file found" + ((lastUnknownMetadataFolderName==null)?"":(" in " + lastUnknownMetadataFolderName)) + "."); } // -------------------------------------------------------------------- public void handleFeatureCat(Element featureCat, int index) throws Exception { if (featureCat != null) { if(Log.isDebugEnabled(Geonet.MEF)) Log.debug(Geonet.MEF, "Collecting feature catalog:\n" + Xml.getString(featureCat)); } fc.add(index, featureCat); } // -------------------------------------------------------------------- /** * Record is not a template by default. No category attached to * record by default. No stylesheet used by default. If no site * identifier provided, use current node id by default. No * validation by default. * * If record is a template and not a MEF file always generate a new * UUID. */ public void handleInfo(Element info, int index) throws Exception { String FS = File.separator; String uuid = null; String createDate = null; String changeDate = null; String source; String sourceName = null; // Schema in info.xml is not used anymore. // as we use autodetect schema to define // metadata schema. // String schema = null; String isTemplate; String localId = null; String rating = null; String popularity = null; String groupId = null; Element categs = null; Element privileges; boolean validate = false; // Apply a stylesheet transformation if requested String style = Util.getParam(params, Params.STYLESHEET, "_none_"); if (!style.equals("_none_")) md.add(index, Xml.transform(md.get(index), stylePath + FS + style)); Element metadata = md.get(index); String schema = dm.autodetectSchema(metadata); if (schema == null) throw new Exception("Unknown schema format : " + schema); // Handle non MEF files insertion if (info.getChildren().size() == 0) { source = Util.getParam(params, Params.SITE_ID, gc .getSiteId()); isTemplate = Util.getParam(params, Params.TEMPLATE, "n"); String category = Util .getParam(params, Params.CATEGORY, ""); if (!category.equals("")) { categs = new Element("categories"); categs.addContent((new Element("category")) .setAttribute("name", category)); } groupId = Util.getParam(params, Params.GROUP); privileges = new Element("group"); privileges.addContent(new Element("operation") .setAttribute("name", "view")); privileges.addContent(new Element("operation") .setAttribute("name", "editing")); privileges.addContent(new Element("operation") .setAttribute("name", "download")); privileges.addContent(new Element("operation") .setAttribute("name", "notify")); privileges.addContent(new Element("operation") .setAttribute("name", "dynamic")); privileges.addContent(new Element("operation") .setAttribute("name", "featured")); // Get the Metadata uuid if it's not a template. if (isTemplate.equals("n")) uuid = dm.extractUUID(schema, md.get(index)); validate = Util.getParam(params, Params.VALIDATE, "off") .equals("on"); } else { if(Log.isDebugEnabled(Geonet.MEF)) Log.debug(Geonet.MEF, "Collecting info file:\n" + Xml.getString(info)); categs = info.getChild("categories"); privileges = info.getChild("privileges"); Element general = info.getChild("general"); uuid = general.getChildText("uuid"); createDate = general.getChildText("createDate"); changeDate = general.getChildText("changeDate"); // If "assign" checkbox is set to true, we assign the metadata to the current catalog siteID/siteName boolean assign = Util.getParam(params, "assign", "off") .equals("on"); if (assign) { if(Log.isDebugEnabled(Geonet.MEF)) Log.debug(Geonet.MEF, "Assign to local catalog"); source = gc.getSiteId(); } else { // --- If siteId is not set, set to current node source = Util.getParam(general, Params.SITE_ID, gc .getSiteId()); sourceName = general.getChildText("siteName"); localId = general.getChildText("localId"); if(Log.isDebugEnabled(Geonet.MEF)) Log.debug(Geonet.MEF, "Assign to catalog: " + source); } isTemplate = general.getChildText("isTemplate").equals( "true") ? "y" : "n"; rating = general.getChildText("rating"); popularity = general.getChildText("popularity"); } if (validate) { // Validate xsd and schematron dm.validateMetadata(schema, metadata, context); } String uuidAction = Util.getParam(params, Params.UUID_ACTION, Params.NOTHING); importRecord(uuid, localId, uuidAction, md, schema, index, source, sourceName, context, id, createDate, changeDate, groupId, isTemplate, dbms); if (fc.size() != 0 && fc.get(index) != null) { // UUID is set as @uuid in root element uuid = UUID.randomUUID().toString(); fc.add(index, dm.setUUID("iso19110", uuid, fc.get(index))); // // insert metadata // int userid = context.getUserSession().getUserIdAsInt(); String group = null, docType = null, title = null, category = null; boolean ufo = false, indexImmediate = false; String fcId = dm.insertMetadata(context, dbms, "iso19110", fc.get(index), context.getSerialFactory().getSerial(dbms, "Metadata"), uuid, userid, group, source, isTemplate, docType, title, category, createDate, changeDate, ufo, indexImmediate); if(Log.isDebugEnabled(Geonet.MEF)) Log.debug(Geonet.MEF, "Adding Feature catalog with uuid: " + uuid); // Create database relation between metadata and feature // catalog String mdId = id.get(index); String query = "INSERT INTO Relations (id, relatedId) VALUES (?, ?)"; dbms.execute(query, Integer.parseInt(mdId), Integer.parseInt(fcId)); id.add(fcId); // TODO : privileges not handled for feature catalog ... } int iId = Integer.parseInt(id.get(index)); if (rating != null) dbms.execute("UPDATE Metadata SET rating=? WHERE id=?", new Integer(rating), iId); if (popularity != null) dbms.execute("UPDATE Metadata SET popularity=? WHERE id=?", new Integer(popularity), iId); dm.setTemplateExt(dbms, iId, isTemplate, null); dm.setHarvestedExt(dbms, iId, null); String pubDir = Lib.resource.getDir(context, "public", id .get(index)); String priDir = Lib.resource.getDir(context, "private", id .get(index)); new File(pubDir).mkdirs(); new File(priDir).mkdirs(); if (categs != null) addCategories(context, dm, dbms, id.get(index), categs); if (groupId == null) addPrivileges(context, dm, dbms, id.get(index), privileges); else addOperations(context, dm, dbms, privileges, id.get(index), groupId); if (indexGroup) { dm.indexMetadataGroup(dbms, id.get(index)); } else { dm.indexInThreadPool(context,id.get(index),dbms); } } // -------------------------------------------------------------------- public void handlePublicFile(String file, String changeDate, InputStream is, int index) throws IOException { if(Log.isDebugEnabled(Geonet.MEF)) Log.debug(Geonet.MEF, "Adding public file with name=" + file); saveFile(context, id.get(index), "public", file, changeDate, is); } // -------------------------------------------------------------------- public void handlePrivateFile(String file, String changeDate, InputStream is, int index) throws IOException { if(Log.isDebugEnabled(Geonet.MEF)) Log.debug(Geonet.MEF, "Adding private file with name=" + file); saveFile(context, id.get(index), "private", file, changeDate, is); } }); return id; } public static void importRecord(String uuid, String localId, String uuidAction, List<Element> md, String schema, int index, String source, String sourceName, ServiceContext context, List<String> id, String createDate, String changeDate, String groupId, String isTemplate, Dbms dbms) throws Exception { GeonetContext gc = (GeonetContext) context .getHandlerContext(Geonet.CONTEXT_NAME); DataManager dm = gc.getDataManager(); if (uuid == null || uuid.equals("") || uuidAction.equals(Params.GENERATE_UUID)) { String newuuid = UUID.randomUUID().toString(); source = null; Log .debug(Geonet.MEF, "Replacing UUID " + uuid + " with " + newuuid); uuid = newuuid; // --- set uuid inside metadata md.add(index, dm.setUUID(schema, uuid, md.get(index))); } else { if (sourceName == null) sourceName = "???"; if (source == null || source.trim().length() == 0) throw new Exception( "Missing siteId parameter from info.xml file"); // --- only update sources table if source is not current site if (!source.equals(gc.getSiteId())) { Lib.sources.update(dbms, source, sourceName, true); } } try { if (dm.existsMetadataUuid(dbms, uuid) && !uuidAction.equals(Params.NOTHING)) { // user has privileges to replace the existing metadata if(dm.getAccessManager().canEdit(context, dm.getMetadataId(dbms, uuid))) { dm.deleteMetadata(context, dbms, dm.getMetadataId(dbms, uuid)); if(Log.isDebugEnabled(Geonet.MEF)) Log.debug(Geonet.MEF, "Deleting existing metadata with UUID : " + uuid); } // user does not hav privileges to replace the existing metadata else { throw new UnAuthorizedException("User has no privilege to replace existing metadata", null); } } } catch (Exception e) { throw new Exception(" Existing metadata with UUID " + uuid + " could not be deleted. Error is: " + e.getMessage()); } if(Log.isDebugEnabled(Geonet.MEF)) Log.debug(Geonet.MEF, "Adding metadata with uuid:" + uuid); // Try to insert record with localId provided, if not use a new id. boolean insertedWithLocalId = false; if (localId != null && !localId.equals("")) { try { int iLocalId = Integer.parseInt(localId); // Use the same id to insert the metadata record. // This is an optional element. If present, indicates the // id used locally by the sourceId actor to store the metadata. Its // purpose is just to allow the reuse of the same local id when // reimporting a metadata. if (!dm.existsMetadata(dbms, iLocalId)) { if(Log.isDebugEnabled(Geonet.MEF)) Log.debug(Geonet.MEF, "Using given localId: " + localId); // // insert metadata // String docType = "", title = null, category = null; boolean ufo = false, indexImmediate = false; dm.insertMetadata(context, dbms, schema, md.get(index), iLocalId, uuid, context.getUserSession().getUserIdAsInt(), groupId, source, isTemplate, docType, title, category, createDate, changeDate, ufo, indexImmediate); id.add(index, Integer.toString(iLocalId)); insertedWithLocalId = true; } } catch (NumberFormatException e) { if(Log.isDebugEnabled(Geonet.MEF)) Log.debug(Geonet.MEF, "Invalid localId provided: " + localId + ". Adding record with a new id."); } } if (!insertedWithLocalId) { // // insert metadata // int userid = context.getUserSession().getUserIdAsInt(); String docType = null, title = null, category = null; boolean ufo = false, indexImmediate = false; id.add(index, dm.insertMetadata(context, dbms, schema, md.get(index), context.getSerialFactory().getSerial(dbms, "Metadata"), uuid, userid, groupId, source, isTemplate, docType, title, category, createDate, changeDate, ufo, indexImmediate)); } } // -------------------------------------------------------------------------- private static void saveFile(ServiceContext context, String id, String access, String file, String changeDate, InputStream is) throws IOException { String dir = Lib.resource.getDir(context, access, id); File outFile = new File(dir, file); FileOutputStream os = new FileOutputStream(outFile); BinaryFile.copy(is, os, false, true); outFile.setLastModified(new ISODate(changeDate).getSeconds() * 1000); } /** * Add categories registered in information file. * * @param context * @param dm * @param dbms * @param id * @param categ * @throws Exception */ public static void addCategories(ServiceContext context, DataManager dm, Dbms dbms, String id, Element categ) throws Exception { List locCats = dbms.select("SELECT id,name FROM Categories") .getChildren(); List list = categ.getChildren("category"); for (Object aList : list) { String catName = ((Element) aList).getAttributeValue("name"); String catId = mapLocalEntity(locCats, catName); if (catId == null) { if(Log.isDebugEnabled(Geonet.MEF)) Log.debug(Geonet.MEF, " - Skipping non-existent category : " + catName); } else { // --- metadata category exists locally if(Log.isDebugEnabled(Geonet.MEF)) Log.debug(Geonet.MEF, " - Setting category : " + catName); dm.setCategory(context, dbms, id, catId); } } } /** * Add privileges according to information file. * * @param context * @param dm * @param dbms * @param id * @param privil * @throws Exception */ private static void addPrivileges(ServiceContext context, DataManager dm, Dbms dbms, String id, Element privil) throws Exception { List locGrps = dbms.select("SELECT id,name FROM Groups").getChildren(); List list = privil.getChildren("group"); for (Object g : list) { Element group = (Element) g; String grpName = group.getAttributeValue("name"); boolean groupOwner = group.getAttributeValue("groupOwner") != null; String grpId = mapLocalEntity(locGrps, grpName); if (grpId == null) { if(Log.isDebugEnabled(Geonet.MEF)) { Log.debug(Geonet.MEF, " - Skipping non-existent group : " + grpName); } } else { // --- metadata group exists locally if(Log.isDebugEnabled(Geonet.MEF)) Log.debug(Geonet.MEF, " - Setting privileges for group : " + grpName); addOperations(context, dm, dbms, group, id, grpId); if (groupOwner) { if(Log.isDebugEnabled(Geonet.MEF)) Log.debug(Geonet.MEF, grpName + " set as group Owner "); dm.setGroupOwner(dbms, id, grpId); } } } } /** * Add operations according to information file. * * @param context * @param dm * @param dbms * @param group * @param id * @param grpId * @throws Exception */ private static void addOperations(ServiceContext context, DataManager dm, Dbms dbms, Element group, String id, String grpId) throws Exception { List opers = group.getChildren("operation"); for (Object oper1 : opers) { Element oper = (Element) oper1; String opName = oper.getAttributeValue("name"); int opId = dm.getAccessManager().getPrivilegeId(opName); if (opId == -1) { if(Log.isDebugEnabled(Geonet.MEF)) Log.debug(Geonet.MEF, " Skipping --> " + opName); } else { // --- operation exists locally if(Log.isDebugEnabled(Geonet.MEF)) Log.debug(Geonet.MEF, " Adding --> " + opName); dm.setOperation(context, dbms, id, grpId, opId + ""); } } } private static String mapLocalEntity(List entities, String name) { for (Object e : entities) { Element entity = (Element) e; if (entity.getChildText("name").equals(name) || entity.getChildText("id").equals(name)) return entity.getChildText("id"); } return null; } } // =============================================================================
false
true
public static List<String> doImport(final Element params, final ServiceContext context, File mefFile, final String stylePath, final boolean indexGroup) throws Exception { final GeonetContext gc = (GeonetContext) context .getHandlerContext(Geonet.CONTEXT_NAME); final DataManager dm = gc.getDataManager(); // Load preferred schema and set to iso19139 by default final String preferredSchema = (gc.getHandlerConfig() .getMandatoryValue("preferredSchema") != null ? gc .getHandlerConfig().getMandatoryValue("preferredSchema") : "iso19139"); final Dbms dbms = (Dbms) context.getResourceManager().open( Geonet.Res.MAIN_DB); final List<String> id = new ArrayList<String>(); final List<Element> md = new ArrayList<Element>(); final List<Element> fc = new ArrayList<Element>(); // Try to define MEF version from mef file not from parameter String fileType = Util.getParam(params, "file_type", "mef"); if (fileType.equals("mef")) { MEFLib.Version version = MEFLib.getMEFVersion(mefFile); if (version.equals(MEFLib.Version.V2)) fileType = "mef2"; } IVisitor visitor; if (fileType.equals("single")) visitor = new XmlVisitor(); else if (fileType.equals("mef")) visitor = new MEFVisitor(); else if (fileType.equals("mef2")) visitor = new MEF2Visitor(); else throw new BadArgumentException("Bad file type parameter."); // --- import metadata from MEF, Xml, ZIP files MEFLib.visit(mefFile, visitor, new IMEFVisitor() { public void handleMetadata(Element metadata, int index) throws Exception { if(Log.isDebugEnabled(Geonet.MEF)) Log.debug(Geonet.MEF, "Collecting metadata:\n" + Xml.getString(metadata)); md.add(index, metadata); } public void handleMetadataFiles(File[] Files, int index) throws Exception { if(Log.isDebugEnabled(Geonet.MEF)) Log.debug(Geonet.MEF, "Multiple metadata files"); Element metadataValidForImport = null; for (File file : Files) { if (file != null && !file.isDirectory()) { Element metadata = Xml.loadFile(file); try { String metadataSchema = dm.autodetectSchema(metadata, null); // If local node doesn't know metadata // schema try to load next xml file. if (metadataSchema == null) { continue; } // If schema is preferred local node schema // load that file. if (metadataSchema.equals(preferredSchema)) { if(Log.isDebugEnabled(Geonet.MEF)) { Log.debug(Geonet.MEF, "Found metadata file " + file.getName() + " with preferred schema (" + preferredSchema + ")."); } handleMetadata(metadata, index); return; } else { if(Log.isDebugEnabled(Geonet.MEF)) { Log.debug(Geonet.MEF, "Found metadata file " + file.getName() + " with known schema (" + metadataSchema + ")."); } metadataValidForImport = metadata; } } catch (NoSchemaMatchesException e) { continue; } } } // Import a valid metadata if not one found // with preferred schema. if (metadataValidForImport != null) { Log .debug(Geonet.MEF, "Importing metadata with valide schema but not preferred one."); handleMetadata(metadataValidForImport, index); } else throw new BadFormatEx("No valid metadata file found."); } // -------------------------------------------------------------------- public void handleFeatureCat(Element featureCat, int index) throws Exception { if (featureCat != null) { if(Log.isDebugEnabled(Geonet.MEF)) Log.debug(Geonet.MEF, "Collecting feature catalog:\n" + Xml.getString(featureCat)); } fc.add(index, featureCat); } // -------------------------------------------------------------------- /** * Record is not a template by default. No category attached to * record by default. No stylesheet used by default. If no site * identifier provided, use current node id by default. No * validation by default. * * If record is a template and not a MEF file always generate a new * UUID. */ public void handleInfo(Element info, int index) throws Exception { String FS = File.separator; String uuid = null; String createDate = null; String changeDate = null; String source; String sourceName = null; // Schema in info.xml is not used anymore. // as we use autodetect schema to define // metadata schema. // String schema = null; String isTemplate; String localId = null; String rating = null; String popularity = null; String groupId = null; Element categs = null; Element privileges; boolean validate = false; // Apply a stylesheet transformation if requested String style = Util.getParam(params, Params.STYLESHEET, "_none_"); if (!style.equals("_none_")) md.add(index, Xml.transform(md.get(index), stylePath + FS + style)); Element metadata = md.get(index); String schema = dm.autodetectSchema(metadata); if (schema == null) throw new Exception("Unknown schema format : " + schema); // Handle non MEF files insertion if (info.getChildren().size() == 0) { source = Util.getParam(params, Params.SITE_ID, gc .getSiteId()); isTemplate = Util.getParam(params, Params.TEMPLATE, "n"); String category = Util .getParam(params, Params.CATEGORY, ""); if (!category.equals("")) { categs = new Element("categories"); categs.addContent((new Element("category")) .setAttribute("name", category)); } groupId = Util.getParam(params, Params.GROUP); privileges = new Element("group"); privileges.addContent(new Element("operation") .setAttribute("name", "view")); privileges.addContent(new Element("operation") .setAttribute("name", "editing")); privileges.addContent(new Element("operation") .setAttribute("name", "download")); privileges.addContent(new Element("operation") .setAttribute("name", "notify")); privileges.addContent(new Element("operation") .setAttribute("name", "dynamic")); privileges.addContent(new Element("operation") .setAttribute("name", "featured")); // Get the Metadata uuid if it's not a template. if (isTemplate.equals("n")) uuid = dm.extractUUID(schema, md.get(index)); validate = Util.getParam(params, Params.VALIDATE, "off") .equals("on"); } else { if(Log.isDebugEnabled(Geonet.MEF)) Log.debug(Geonet.MEF, "Collecting info file:\n" + Xml.getString(info)); categs = info.getChild("categories"); privileges = info.getChild("privileges"); Element general = info.getChild("general"); uuid = general.getChildText("uuid"); createDate = general.getChildText("createDate"); changeDate = general.getChildText("changeDate"); // If "assign" checkbox is set to true, we assign the metadata to the current catalog siteID/siteName boolean assign = Util.getParam(params, "assign", "off") .equals("on"); if (assign) { if(Log.isDebugEnabled(Geonet.MEF)) Log.debug(Geonet.MEF, "Assign to local catalog"); source = gc.getSiteId(); } else { // --- If siteId is not set, set to current node source = Util.getParam(general, Params.SITE_ID, gc .getSiteId()); sourceName = general.getChildText("siteName"); localId = general.getChildText("localId"); if(Log.isDebugEnabled(Geonet.MEF)) Log.debug(Geonet.MEF, "Assign to catalog: " + source); } isTemplate = general.getChildText("isTemplate").equals( "true") ? "y" : "n"; rating = general.getChildText("rating"); popularity = general.getChildText("popularity"); } if (validate) { // Validate xsd and schematron dm.validateMetadata(schema, metadata, context); } String uuidAction = Util.getParam(params, Params.UUID_ACTION, Params.NOTHING); importRecord(uuid, localId, uuidAction, md, schema, index, source, sourceName, context, id, createDate, changeDate, groupId, isTemplate, dbms); if (fc.size() != 0 && fc.get(index) != null) { // UUID is set as @uuid in root element uuid = UUID.randomUUID().toString(); fc.add(index, dm.setUUID("iso19110", uuid, fc.get(index))); // // insert metadata // int userid = context.getUserSession().getUserIdAsInt(); String group = null, docType = null, title = null, category = null; boolean ufo = false, indexImmediate = false; String fcId = dm.insertMetadata(context, dbms, "iso19110", fc.get(index), context.getSerialFactory().getSerial(dbms, "Metadata"), uuid, userid, group, source, isTemplate, docType, title, category, createDate, changeDate, ufo, indexImmediate); if(Log.isDebugEnabled(Geonet.MEF)) Log.debug(Geonet.MEF, "Adding Feature catalog with uuid: " + uuid); // Create database relation between metadata and feature // catalog String mdId = id.get(index); String query = "INSERT INTO Relations (id, relatedId) VALUES (?, ?)"; dbms.execute(query, Integer.parseInt(mdId), Integer.parseInt(fcId)); id.add(fcId); // TODO : privileges not handled for feature catalog ... } int iId = Integer.parseInt(id.get(index)); if (rating != null) dbms.execute("UPDATE Metadata SET rating=? WHERE id=?", new Integer(rating), iId); if (popularity != null) dbms.execute("UPDATE Metadata SET popularity=? WHERE id=?", new Integer(popularity), iId); dm.setTemplateExt(dbms, iId, isTemplate, null); dm.setHarvestedExt(dbms, iId, null); String pubDir = Lib.resource.getDir(context, "public", id .get(index)); String priDir = Lib.resource.getDir(context, "private", id .get(index)); new File(pubDir).mkdirs(); new File(priDir).mkdirs(); if (categs != null) addCategories(context, dm, dbms, id.get(index), categs); if (groupId == null) addPrivileges(context, dm, dbms, id.get(index), privileges); else addOperations(context, dm, dbms, privileges, id.get(index), groupId); if (indexGroup) { dm.indexMetadataGroup(dbms, id.get(index)); } else { dm.indexInThreadPool(context,id.get(index),dbms); } } // -------------------------------------------------------------------- public void handlePublicFile(String file, String changeDate, InputStream is, int index) throws IOException { if(Log.isDebugEnabled(Geonet.MEF)) Log.debug(Geonet.MEF, "Adding public file with name=" + file); saveFile(context, id.get(index), "public", file, changeDate, is); } // -------------------------------------------------------------------- public void handlePrivateFile(String file, String changeDate, InputStream is, int index) throws IOException { if(Log.isDebugEnabled(Geonet.MEF)) Log.debug(Geonet.MEF, "Adding private file with name=" + file); saveFile(context, id.get(index), "private", file, changeDate, is); } }); return id; }
public static List<String> doImport(final Element params, final ServiceContext context, File mefFile, final String stylePath, final boolean indexGroup) throws Exception { final GeonetContext gc = (GeonetContext) context .getHandlerContext(Geonet.CONTEXT_NAME); final DataManager dm = gc.getDataManager(); // Load preferred schema and set to iso19139 by default final String preferredSchema = (gc.getHandlerConfig() .getMandatoryValue("preferredSchema") != null ? gc .getHandlerConfig().getMandatoryValue("preferredSchema") : "iso19139"); final Dbms dbms = (Dbms) context.getResourceManager().open( Geonet.Res.MAIN_DB); final List<String> id = new ArrayList<String>(); final List<Element> md = new ArrayList<Element>(); final List<Element> fc = new ArrayList<Element>(); // Try to define MEF version from mef file not from parameter String fileType = Util.getParam(params, "file_type", "mef"); if (fileType.equals("mef")) { MEFLib.Version version = MEFLib.getMEFVersion(mefFile); if (version.equals(MEFLib.Version.V2)) fileType = "mef2"; } IVisitor visitor; if (fileType.equals("single")) visitor = new XmlVisitor(); else if (fileType.equals("mef")) visitor = new MEFVisitor(); else if (fileType.equals("mef2")) visitor = new MEF2Visitor(); else throw new BadArgumentException("Bad file type parameter."); // --- import metadata from MEF, Xml, ZIP files MEFLib.visit(mefFile, visitor, new IMEFVisitor() { public void handleMetadata(Element metadata, int index) throws Exception { if(Log.isDebugEnabled(Geonet.MEF)) Log.debug(Geonet.MEF, "Collecting metadata:\n" + Xml.getString(metadata)); md.add(index, metadata); } public void handleMetadataFiles(File[] Files, int index) throws Exception { String lastUnknownMetadataFolderName=null; if(Log.isDebugEnabled(Geonet.MEF)) Log.debug(Geonet.MEF, "Multiple metadata files"); Element metadataValidForImport = null; for (File file : Files) { if (file != null && !file.isDirectory()) { Element metadata = Xml.loadFile(file); try { String metadataSchema = dm.autodetectSchema(metadata, null); // If local node doesn't know metadata // schema try to load next xml file. if (metadataSchema == null) { continue; } // If schema is preferred local node schema // load that file. if (metadataSchema.equals(preferredSchema)) { if(Log.isDebugEnabled(Geonet.MEF)) { Log.debug(Geonet.MEF, "Found metadata file " + file.getParentFile().getParentFile().getName() + File.separator + file.getParentFile().getName() + File.separator + file.getName() + " with preferred schema (" + preferredSchema + ")."); } handleMetadata(metadata, index); return; } else { if(Log.isDebugEnabled(Geonet.MEF)) { Log.debug(Geonet.MEF, "Found metadata file " + file.getParentFile().getParentFile().getName() + File.separator + file.getParentFile().getName() + File.separator + file.getName() + " with known schema (" + metadataSchema + ")."); } metadataValidForImport = metadata; } } catch (NoSchemaMatchesException e) { // Important folder name to identify metadata should be ../../ lastUnknownMetadataFolderName=file.getParentFile().getParentFile().getName() + File.separator + file.getParentFile().getName() + File.separator; Log.debug(Geonet.MEF, "No schema match for " + lastUnknownMetadataFolderName + file.getName() + "."); continue; } } } // Import a valid metadata if not one found // with preferred schema. if (metadataValidForImport != null) { Log .debug(Geonet.MEF, "Importing metadata with valide schema but not preferred one."); handleMetadata(metadataValidForImport, index); } else throw new BadFormatEx("No valid metadata file found" + ((lastUnknownMetadataFolderName==null)?"":(" in " + lastUnknownMetadataFolderName)) + "."); } // -------------------------------------------------------------------- public void handleFeatureCat(Element featureCat, int index) throws Exception { if (featureCat != null) { if(Log.isDebugEnabled(Geonet.MEF)) Log.debug(Geonet.MEF, "Collecting feature catalog:\n" + Xml.getString(featureCat)); } fc.add(index, featureCat); } // -------------------------------------------------------------------- /** * Record is not a template by default. No category attached to * record by default. No stylesheet used by default. If no site * identifier provided, use current node id by default. No * validation by default. * * If record is a template and not a MEF file always generate a new * UUID. */ public void handleInfo(Element info, int index) throws Exception { String FS = File.separator; String uuid = null; String createDate = null; String changeDate = null; String source; String sourceName = null; // Schema in info.xml is not used anymore. // as we use autodetect schema to define // metadata schema. // String schema = null; String isTemplate; String localId = null; String rating = null; String popularity = null; String groupId = null; Element categs = null; Element privileges; boolean validate = false; // Apply a stylesheet transformation if requested String style = Util.getParam(params, Params.STYLESHEET, "_none_"); if (!style.equals("_none_")) md.add(index, Xml.transform(md.get(index), stylePath + FS + style)); Element metadata = md.get(index); String schema = dm.autodetectSchema(metadata); if (schema == null) throw new Exception("Unknown schema format : " + schema); // Handle non MEF files insertion if (info.getChildren().size() == 0) { source = Util.getParam(params, Params.SITE_ID, gc .getSiteId()); isTemplate = Util.getParam(params, Params.TEMPLATE, "n"); String category = Util .getParam(params, Params.CATEGORY, ""); if (!category.equals("")) { categs = new Element("categories"); categs.addContent((new Element("category")) .setAttribute("name", category)); } groupId = Util.getParam(params, Params.GROUP); privileges = new Element("group"); privileges.addContent(new Element("operation") .setAttribute("name", "view")); privileges.addContent(new Element("operation") .setAttribute("name", "editing")); privileges.addContent(new Element("operation") .setAttribute("name", "download")); privileges.addContent(new Element("operation") .setAttribute("name", "notify")); privileges.addContent(new Element("operation") .setAttribute("name", "dynamic")); privileges.addContent(new Element("operation") .setAttribute("name", "featured")); // Get the Metadata uuid if it's not a template. if (isTemplate.equals("n")) uuid = dm.extractUUID(schema, md.get(index)); validate = Util.getParam(params, Params.VALIDATE, "off") .equals("on"); } else { if(Log.isDebugEnabled(Geonet.MEF)) Log.debug(Geonet.MEF, "Collecting info file:\n" + Xml.getString(info)); categs = info.getChild("categories"); privileges = info.getChild("privileges"); Element general = info.getChild("general"); uuid = general.getChildText("uuid"); createDate = general.getChildText("createDate"); changeDate = general.getChildText("changeDate"); // If "assign" checkbox is set to true, we assign the metadata to the current catalog siteID/siteName boolean assign = Util.getParam(params, "assign", "off") .equals("on"); if (assign) { if(Log.isDebugEnabled(Geonet.MEF)) Log.debug(Geonet.MEF, "Assign to local catalog"); source = gc.getSiteId(); } else { // --- If siteId is not set, set to current node source = Util.getParam(general, Params.SITE_ID, gc .getSiteId()); sourceName = general.getChildText("siteName"); localId = general.getChildText("localId"); if(Log.isDebugEnabled(Geonet.MEF)) Log.debug(Geonet.MEF, "Assign to catalog: " + source); } isTemplate = general.getChildText("isTemplate").equals( "true") ? "y" : "n"; rating = general.getChildText("rating"); popularity = general.getChildText("popularity"); } if (validate) { // Validate xsd and schematron dm.validateMetadata(schema, metadata, context); } String uuidAction = Util.getParam(params, Params.UUID_ACTION, Params.NOTHING); importRecord(uuid, localId, uuidAction, md, schema, index, source, sourceName, context, id, createDate, changeDate, groupId, isTemplate, dbms); if (fc.size() != 0 && fc.get(index) != null) { // UUID is set as @uuid in root element uuid = UUID.randomUUID().toString(); fc.add(index, dm.setUUID("iso19110", uuid, fc.get(index))); // // insert metadata // int userid = context.getUserSession().getUserIdAsInt(); String group = null, docType = null, title = null, category = null; boolean ufo = false, indexImmediate = false; String fcId = dm.insertMetadata(context, dbms, "iso19110", fc.get(index), context.getSerialFactory().getSerial(dbms, "Metadata"), uuid, userid, group, source, isTemplate, docType, title, category, createDate, changeDate, ufo, indexImmediate); if(Log.isDebugEnabled(Geonet.MEF)) Log.debug(Geonet.MEF, "Adding Feature catalog with uuid: " + uuid); // Create database relation between metadata and feature // catalog String mdId = id.get(index); String query = "INSERT INTO Relations (id, relatedId) VALUES (?, ?)"; dbms.execute(query, Integer.parseInt(mdId), Integer.parseInt(fcId)); id.add(fcId); // TODO : privileges not handled for feature catalog ... } int iId = Integer.parseInt(id.get(index)); if (rating != null) dbms.execute("UPDATE Metadata SET rating=? WHERE id=?", new Integer(rating), iId); if (popularity != null) dbms.execute("UPDATE Metadata SET popularity=? WHERE id=?", new Integer(popularity), iId); dm.setTemplateExt(dbms, iId, isTemplate, null); dm.setHarvestedExt(dbms, iId, null); String pubDir = Lib.resource.getDir(context, "public", id .get(index)); String priDir = Lib.resource.getDir(context, "private", id .get(index)); new File(pubDir).mkdirs(); new File(priDir).mkdirs(); if (categs != null) addCategories(context, dm, dbms, id.get(index), categs); if (groupId == null) addPrivileges(context, dm, dbms, id.get(index), privileges); else addOperations(context, dm, dbms, privileges, id.get(index), groupId); if (indexGroup) { dm.indexMetadataGroup(dbms, id.get(index)); } else { dm.indexInThreadPool(context,id.get(index),dbms); } } // -------------------------------------------------------------------- public void handlePublicFile(String file, String changeDate, InputStream is, int index) throws IOException { if(Log.isDebugEnabled(Geonet.MEF)) Log.debug(Geonet.MEF, "Adding public file with name=" + file); saveFile(context, id.get(index), "public", file, changeDate, is); } // -------------------------------------------------------------------- public void handlePrivateFile(String file, String changeDate, InputStream is, int index) throws IOException { if(Log.isDebugEnabled(Geonet.MEF)) Log.debug(Geonet.MEF, "Adding private file with name=" + file); saveFile(context, id.get(index), "private", file, changeDate, is); } }); return id; }
diff --git a/tools/cytoscape-gpml/src/org/pathvisio/cytoscape/DefaultAttributeMapper.java b/tools/cytoscape-gpml/src/org/pathvisio/cytoscape/DefaultAttributeMapper.java index 602b9c92..5843b721 100644 --- a/tools/cytoscape-gpml/src/org/pathvisio/cytoscape/DefaultAttributeMapper.java +++ b/tools/cytoscape-gpml/src/org/pathvisio/cytoscape/DefaultAttributeMapper.java @@ -1,268 +1,270 @@ // PathVisio, // a tool for data visualization and analysis using Biological Pathways // Copyright 2006-2009 BiGCaT Bioinformatics // // 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.pathvisio.cytoscape; import java.awt.Color; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.pathvisio.debug.Logger; import org.pathvisio.model.DataSource; import org.pathvisio.model.PathwayElement; import org.pathvisio.model.PropertyType; import cytoscape.data.CyAttributes; public class DefaultAttributeMapper implements AttributeMapper { public static final String CY_COMMENT_SOURCE = "cytoscape-attribute: "; private Map<PropertyType, Object> defaultValues; private Map<PropertyType, String> prop2attr; private Map<String, PropertyType> attr2prop; private Set<PropertyType> protectedProps; public DefaultAttributeMapper() { prop2attr = new HashMap<PropertyType, String>(); attr2prop = new HashMap<String, PropertyType>(); defaultValues = new HashMap<PropertyType, Object>(); setInitialMappings(); } public String getMapping(PropertyType prop) { //First check if a mapping is explicitely set String name = prop2attr.get(prop); if(name == null && prop != null) { //If not, use the property tag name name = prop.tag(); } return name; } public PropertyType getMapping(String attr) { PropertyType prop = attr2prop.get(attr); if(prop == null) { //If not, find out if it's a GPML attribute prop = PropertyType.getByTag(attr); } return prop; } public void setMapping(String attr, PropertyType prop) { setAttributeToPropertyMapping(attr, prop); setPropertyToAttributeMapping(prop, attr); } public void setDefaultValue(PropertyType prop, Object value) { defaultValues.put(prop, value); } public Object getDefaultValue(PropertyType prop) { return defaultValues.get(prop); } /** * Set a mapping from attribute to property * @param attr * @param prop */ public void setAttributeToPropertyMapping(String attr, PropertyType prop) { attr2prop.put(attr, prop); } /** * Set a mapping from property to attribute * @param prop * @param attr */ public void setPropertyToAttributeMapping(PropertyType prop, String attr) { prop2attr.put(prop, attr); } protected Set<PropertyType> getProtectedProps() { if(protectedProps == null) { protectedProps = new HashSet<PropertyType>(); protectedProps.add(PropertyType.CENTERX); protectedProps.add(PropertyType.CENTERY); protectedProps.add(PropertyType.STARTX); protectedProps.add(PropertyType.STARTY); protectedProps.add(PropertyType.ENDX); protectedProps.add(PropertyType.ENDY); protectedProps.add(PropertyType.COMMENTS); protectedProps.add(PropertyType.GRAPHID); } return protectedProps; } protected void setInitialMappings() { setMapping("canonicalName", PropertyType.TEXTLABEL); setDefaultValue(PropertyType.DATASOURCE, DataSource.UNIPROT); } public boolean isProtected(PropertyType prop) { return getProtectedProps().contains(prop); } public void protect(PropertyType prop) { getProtectedProps().add(prop); } public void unprotect(PropertyType prop) { getProtectedProps().remove(prop); } public void attributesToProperties(String id, PathwayElement elm, CyAttributes attr) { //Process defaults for(PropertyType prop : defaultValues.keySet()) { - elm.setStaticProperty(prop, defaultValues.get(prop)); + if(elm.getStaticPropertyKeys().contains(prop)) { + elm.setStaticProperty(prop, defaultValues.get(prop)); + } } //Process mappings for(String aname : attr.getAttributeNames()) { PropertyType prop = getProperty(aname); //Protected property, don't set from attributes if(isProtected(prop)) { // Logger.log.trace("\tProperty is protected, skipping"); continue; } Logger.log.trace ("Property " + aname); //No mapping for this attribute, store in attributeMap if(prop == null) { //TODO needs more testing /* String value = null; switch (attr.getType(id)) { case CyAttributes.TYPE_STRING: value = attr.getStringAttribute(id, aname); break; case CyAttributes.TYPE_BOOLEAN: value = "" + attr.getBooleanAttribute(id, aname); break; case CyAttributes.TYPE_FLOATING: value = "" + attr.getDoubleAttribute(id, aname); break; case CyAttributes.TYPE_INTEGER: value = "" + attr.getIntegerAttribute(id, aname); break; case CyAttributes.TYPE_UNDEFINED: try { value = "" + attr.getAttribute(id, aname); } catch (IllegalArgumentException e) { Logger.log.error ("Illegal argument exception " + aname + " " + value); } Logger.log.trace ("Undefined " + value); break; default: //TODO: handle other types such as List } Logger.log.trace("\tNo mapping found, adding as generic attribute " + aname + " " + value); if(value != null && !(value.length() == 0)) { Logger.log.trace ("Setting value"); elm.setDynamicProperty(aname, value); } */ } else { //Found a property, try to set it try { Object value = null; switch(prop.type()) { case BOOLEAN: value = attr.getBooleanAttribute(id, aname); break; case INTEGER: value = attr.getIntegerAttribute(id, aname); break; case DOUBLE: value = attr.getDoubleAttribute(id, aname); break; case COLOR: value = Color.decode("" + attr.getIntegerAttribute(id, aname)); break; case STRING: case DB_ID: case DB_SYMBOL: case DATASOURCE: value = attr.getAttribute(id, aname); break; default: // Logger.log.trace("\tUnsupported type: attribute " + aname + " to property " + prop); //Don't transfer the attribute, if it's not a supported type } Logger.log.trace("Setting property " + prop + " to " + value); if(value != null) { elm.setStaticProperty(prop, value); } } catch(Exception e) { // Logger.log.error("Unable to parse value for " + prop, e); } } } } private PropertyType getProperty(String attributeName) { return getMapping(attributeName); } private String getAttributeName(PropertyType property) { return getMapping(property); } public void propertiesToAttributes(String id, PathwayElement elm, CyAttributes attr) { for(PropertyType prop : elm.getStaticPropertyKeys()) { Object value = elm.getStaticProperty(prop); if(value != null) { String aname = getAttributeName(prop); switch(prop.type()) { case BOOLEAN: attr.setAttribute(id, aname, (Boolean)value); break; case INTEGER: attr.setAttribute(id, aname, (Integer)value); break; case DOUBLE: attr.setAttribute(id, aname, (Double)value); break; case COLOR: attr.setAttribute(id, aname, ((Color)value).getRGB()); break; case STRING: case DB_ID: case DB_SYMBOL: default: attr.setAttribute(id, aname, value.toString()); } } } //TODO needs more testing /* // now deal with the attributes in attributeMap. for (String key : elm.getDynamicPropertyKeys()) { attr.setAttribute(id, key, elm.getDynamicProperty(key)); } */ } }
true
true
public void attributesToProperties(String id, PathwayElement elm, CyAttributes attr) { //Process defaults for(PropertyType prop : defaultValues.keySet()) { elm.setStaticProperty(prop, defaultValues.get(prop)); } //Process mappings for(String aname : attr.getAttributeNames()) { PropertyType prop = getProperty(aname); //Protected property, don't set from attributes if(isProtected(prop)) { // Logger.log.trace("\tProperty is protected, skipping"); continue; } Logger.log.trace ("Property " + aname); //No mapping for this attribute, store in attributeMap if(prop == null) { //TODO needs more testing /* String value = null; switch (attr.getType(id)) { case CyAttributes.TYPE_STRING: value = attr.getStringAttribute(id, aname); break; case CyAttributes.TYPE_BOOLEAN: value = "" + attr.getBooleanAttribute(id, aname); break; case CyAttributes.TYPE_FLOATING: value = "" + attr.getDoubleAttribute(id, aname); break; case CyAttributes.TYPE_INTEGER: value = "" + attr.getIntegerAttribute(id, aname); break; case CyAttributes.TYPE_UNDEFINED: try { value = "" + attr.getAttribute(id, aname); } catch (IllegalArgumentException e) { Logger.log.error ("Illegal argument exception " + aname + " " + value); } Logger.log.trace ("Undefined " + value); break; default: //TODO: handle other types such as List } Logger.log.trace("\tNo mapping found, adding as generic attribute " + aname + " " + value); if(value != null && !(value.length() == 0)) { Logger.log.trace ("Setting value"); elm.setDynamicProperty(aname, value); } */ } else { //Found a property, try to set it try { Object value = null; switch(prop.type()) { case BOOLEAN: value = attr.getBooleanAttribute(id, aname); break; case INTEGER: value = attr.getIntegerAttribute(id, aname); break; case DOUBLE: value = attr.getDoubleAttribute(id, aname); break; case COLOR: value = Color.decode("" + attr.getIntegerAttribute(id, aname)); break; case STRING: case DB_ID: case DB_SYMBOL: case DATASOURCE: value = attr.getAttribute(id, aname); break; default: // Logger.log.trace("\tUnsupported type: attribute " + aname + " to property " + prop); //Don't transfer the attribute, if it's not a supported type } Logger.log.trace("Setting property " + prop + " to " + value); if(value != null) { elm.setStaticProperty(prop, value); } } catch(Exception e) { // Logger.log.error("Unable to parse value for " + prop, e); } } } } private PropertyType getProperty(String attributeName) { return getMapping(attributeName); } private String getAttributeName(PropertyType property) { return getMapping(property); } public void propertiesToAttributes(String id, PathwayElement elm, CyAttributes attr) { for(PropertyType prop : elm.getStaticPropertyKeys()) { Object value = elm.getStaticProperty(prop); if(value != null) { String aname = getAttributeName(prop); switch(prop.type()) { case BOOLEAN: attr.setAttribute(id, aname, (Boolean)value); break; case INTEGER: attr.setAttribute(id, aname, (Integer)value); break; case DOUBLE: attr.setAttribute(id, aname, (Double)value); break; case COLOR: attr.setAttribute(id, aname, ((Color)value).getRGB()); break; case STRING: case DB_ID: case DB_SYMBOL: default: attr.setAttribute(id, aname, value.toString()); } } } //TODO needs more testing /* // now deal with the attributes in attributeMap. for (String key : elm.getDynamicPropertyKeys()) { attr.setAttribute(id, key, elm.getDynamicProperty(key)); } */ } }
public void attributesToProperties(String id, PathwayElement elm, CyAttributes attr) { //Process defaults for(PropertyType prop : defaultValues.keySet()) { if(elm.getStaticPropertyKeys().contains(prop)) { elm.setStaticProperty(prop, defaultValues.get(prop)); } } //Process mappings for(String aname : attr.getAttributeNames()) { PropertyType prop = getProperty(aname); //Protected property, don't set from attributes if(isProtected(prop)) { // Logger.log.trace("\tProperty is protected, skipping"); continue; } Logger.log.trace ("Property " + aname); //No mapping for this attribute, store in attributeMap if(prop == null) { //TODO needs more testing /* String value = null; switch (attr.getType(id)) { case CyAttributes.TYPE_STRING: value = attr.getStringAttribute(id, aname); break; case CyAttributes.TYPE_BOOLEAN: value = "" + attr.getBooleanAttribute(id, aname); break; case CyAttributes.TYPE_FLOATING: value = "" + attr.getDoubleAttribute(id, aname); break; case CyAttributes.TYPE_INTEGER: value = "" + attr.getIntegerAttribute(id, aname); break; case CyAttributes.TYPE_UNDEFINED: try { value = "" + attr.getAttribute(id, aname); } catch (IllegalArgumentException e) { Logger.log.error ("Illegal argument exception " + aname + " " + value); } Logger.log.trace ("Undefined " + value); break; default: //TODO: handle other types such as List } Logger.log.trace("\tNo mapping found, adding as generic attribute " + aname + " " + value); if(value != null && !(value.length() == 0)) { Logger.log.trace ("Setting value"); elm.setDynamicProperty(aname, value); } */ } else { //Found a property, try to set it try { Object value = null; switch(prop.type()) { case BOOLEAN: value = attr.getBooleanAttribute(id, aname); break; case INTEGER: value = attr.getIntegerAttribute(id, aname); break; case DOUBLE: value = attr.getDoubleAttribute(id, aname); break; case COLOR: value = Color.decode("" + attr.getIntegerAttribute(id, aname)); break; case STRING: case DB_ID: case DB_SYMBOL: case DATASOURCE: value = attr.getAttribute(id, aname); break; default: // Logger.log.trace("\tUnsupported type: attribute " + aname + " to property " + prop); //Don't transfer the attribute, if it's not a supported type } Logger.log.trace("Setting property " + prop + " to " + value); if(value != null) { elm.setStaticProperty(prop, value); } } catch(Exception e) { // Logger.log.error("Unable to parse value for " + prop, e); } } } } private PropertyType getProperty(String attributeName) { return getMapping(attributeName); } private String getAttributeName(PropertyType property) { return getMapping(property); } public void propertiesToAttributes(String id, PathwayElement elm, CyAttributes attr) { for(PropertyType prop : elm.getStaticPropertyKeys()) { Object value = elm.getStaticProperty(prop); if(value != null) { String aname = getAttributeName(prop); switch(prop.type()) { case BOOLEAN: attr.setAttribute(id, aname, (Boolean)value); break; case INTEGER: attr.setAttribute(id, aname, (Integer)value); break; case DOUBLE: attr.setAttribute(id, aname, (Double)value); break; case COLOR: attr.setAttribute(id, aname, ((Color)value).getRGB()); break; case STRING: case DB_ID: case DB_SYMBOL: default: attr.setAttribute(id, aname, value.toString()); } } } //TODO needs more testing /* // now deal with the attributes in attributeMap. for (String key : elm.getDynamicPropertyKeys()) { attr.setAttribute(id, key, elm.getDynamicProperty(key)); } */ } }
diff --git a/src/share/org/dianexus/triceps/Node.java b/src/share/org/dianexus/triceps/Node.java index 3750113..970d36e 100644 --- a/src/share/org/dianexus/triceps/Node.java +++ b/src/share/org/dianexus/triceps/Node.java @@ -1,110 +1,111 @@ import java.lang.*; import java.util.*; public class Node { private String concept = ""; private String description = ""; private int step = 0; private String stepName = ""; private String dependencies = ""; private String questionRef = ""; // name within DISC private String actionType = ""; private String action = ""; private String answerType = ""; private String answerOptions = ""; private static final String TAB = " "; private static final int ITAB = (int)TAB.charAt(0); /* N.B. need this obtuse way of checking for adjacent TABs from tokenizer - no other way seems to work */ public Node(int step, String tsv) { String token; boolean lastWasTab = true; // so that if first was tab, will recognize that a token is missing int count = 0; try { StringTokenizer st = new StringTokenizer(tsv, "\t", false); this.step = step; count = st.countTokens(); int j = 0; /* If there are no adjacent tabs in a line, then this fails to work. It is not clear why. Hack for now: no longer return tabs. Since navigation.txt no longer has adjacent tabs, this is working */ for (int i = 0; i < count; ++i) { token = st.nextToken(); // this is the only way to tell whether the token returned is a TAB - TAB.equals(token) doesn't work! if ((int)token.charAt(0) == ITAB) { if (lastWasTab || i == (count - 1)) { token = null; // ensures that adjacent tabs, or conceptless nodes get set correctly } else { lastWasTab = true; continue; } } else { lastWasTab = false; } if (token == null) token = ""; switch (++j) { case 1: concept = token; break; case 2: description = token; break; case 3: stepName = "_" + token; - break; // assumes, for now, that input is nubmer without underscore + break; // assumes, for now, that input is number without underscore case 4: dependencies = token; break; case 5: questionRef = token; break; case 6: actionType = token; break; case 7: action = token; break; case 8: { answerOptions = token; int index = answerOptions.indexOf(";"); if (index != -1) { answerType = answerOptions.substring(0, index); } - } + else answerType = answerOptions; + } } } if (j != 8) { System.out.println("Error tokenizing line " + step + " (" + j + "/8 tokens found)"); } } catch(Exception e) { System.out.println("Error tokenizing line " + step + " (" + count + "/8 tokens)" + e.getMessage()); } } public String getAction() { return action; } public String getActionType() { return actionType; } public String getAnswerOptions() { return answerOptions; } public String getAnswerType() { return answerType; } public String getConcept() { return concept; } public String getDependencies() { return dependencies; } public String getDescription() { return description; } public String getName() { return stepName; } public String getQuestionRef() { return questionRef; } public int getStep() { return step; } /** * Prints out the components of a node in the schedule. */ public String toString() { return "Node (" + step + "): <B>" + stepName + "</B><BR>\n" + "Concept: <B>" + concept + "</B><BR>\n" + "Description: <B>" + description + "</B><BR>\n" + "Dependencies: <B>" + dependencies + "</B><BR>\n" + "Question Reference: <B>" + questionRef + "</B><BR>\n" + "Action Type: <B>" + actionType + "</B><BR>\n" + "Action: <B>" + action + "</B><BR>\n" + "AnswerType: <B>" + answerType + "</B><BR>\n" + "AnswerOptions: <B>" + answerOptions + "</B><BR>\n"; } }
false
true
public Node(int step, String tsv) { String token; boolean lastWasTab = true; // so that if first was tab, will recognize that a token is missing int count = 0; try { StringTokenizer st = new StringTokenizer(tsv, "\t", false); this.step = step; count = st.countTokens(); int j = 0; /* If there are no adjacent tabs in a line, then this fails to work. It is not clear why. Hack for now: no longer return tabs. Since navigation.txt no longer has adjacent tabs, this is working */ for (int i = 0; i < count; ++i) { token = st.nextToken(); // this is the only way to tell whether the token returned is a TAB - TAB.equals(token) doesn't work! if ((int)token.charAt(0) == ITAB) { if (lastWasTab || i == (count - 1)) { token = null; // ensures that adjacent tabs, or conceptless nodes get set correctly } else { lastWasTab = true; continue; } } else { lastWasTab = false; } if (token == null) token = ""; switch (++j) { case 1: concept = token; break; case 2: description = token; break; case 3: stepName = "_" + token; break; // assumes, for now, that input is nubmer without underscore case 4: dependencies = token; break; case 5: questionRef = token; break; case 6: actionType = token; break; case 7: action = token; break; case 8: { answerOptions = token; int index = answerOptions.indexOf(";"); if (index != -1) { answerType = answerOptions.substring(0, index); } } } } if (j != 8) { System.out.println("Error tokenizing line " + step + " (" + j + "/8 tokens found)"); } } catch(Exception e) { System.out.println("Error tokenizing line " + step + " (" + count + "/8 tokens)" + e.getMessage()); } }
public Node(int step, String tsv) { String token; boolean lastWasTab = true; // so that if first was tab, will recognize that a token is missing int count = 0; try { StringTokenizer st = new StringTokenizer(tsv, "\t", false); this.step = step; count = st.countTokens(); int j = 0; /* If there are no adjacent tabs in a line, then this fails to work. It is not clear why. Hack for now: no longer return tabs. Since navigation.txt no longer has adjacent tabs, this is working */ for (int i = 0; i < count; ++i) { token = st.nextToken(); // this is the only way to tell whether the token returned is a TAB - TAB.equals(token) doesn't work! if ((int)token.charAt(0) == ITAB) { if (lastWasTab || i == (count - 1)) { token = null; // ensures that adjacent tabs, or conceptless nodes get set correctly } else { lastWasTab = true; continue; } } else { lastWasTab = false; } if (token == null) token = ""; switch (++j) { case 1: concept = token; break; case 2: description = token; break; case 3: stepName = "_" + token; break; // assumes, for now, that input is number without underscore case 4: dependencies = token; break; case 5: questionRef = token; break; case 6: actionType = token; break; case 7: action = token; break; case 8: { answerOptions = token; int index = answerOptions.indexOf(";"); if (index != -1) { answerType = answerOptions.substring(0, index); } else answerType = answerOptions; } } } if (j != 8) { System.out.println("Error tokenizing line " + step + " (" + j + "/8 tokens found)"); } } catch(Exception e) { System.out.println("Error tokenizing line " + step + " (" + count + "/8 tokens)" + e.getMessage()); } }
diff --git a/gdx/src/com/badlogic/gdx/graphics/glutils/ETC1.java b/gdx/src/com/badlogic/gdx/graphics/glutils/ETC1.java index 5db21f87e..bcf85e16d 100644 --- a/gdx/src/com/badlogic/gdx/graphics/glutils/ETC1.java +++ b/gdx/src/com/badlogic/gdx/graphics/glutils/ETC1.java @@ -1,273 +1,273 @@ /******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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.badlogic.gdx.graphics.glutils; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.nio.ByteBuffer; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.Pixmap.Format; import com.badlogic.gdx.utils.BufferUtils; import com.badlogic.gdx.utils.Disposable; import com.badlogic.gdx.utils.GdxRuntimeException; /** Class for encoding and decoding ETC1 compressed images. Also provides methods to add a PKM header. * @author mzechner */ public class ETC1 { /** The PKM header size in bytes **/ public static int PKM_HEADER_SIZE = 16; public static int ETC1_RGB8_OES = 0x00008d64; /** Class for storing ETC1 compressed image data. * @author mzechner */ public final static class ETC1Data implements Disposable { /** the width in pixels **/ public final int width; /** the height in pixels **/ public final int height; /** the optional PKM header and compressed image data **/ public final ByteBuffer compressedData; /** the offset in bytes to the actual compressed data. Might be 16 if this contains a PKM header, 0 otherwise **/ public final int dataOffset; ETC1Data (int width, int height, ByteBuffer compressedData, int dataOffset) { this.width = width; this.height = height; this.compressedData = compressedData; this.dataOffset = dataOffset; } public ETC1Data (FileHandle pkmFile) { byte[] buffer = new byte[1024 * 10]; DataInputStream in = null; try { in = new DataInputStream(new BufferedInputStream(new GZIPInputStream(pkmFile.read()))); int fileSize = in.readInt(); - compressedData = BufferUtils.newByteBuffer(fileSize); + compressedData = BufferUtils.newUnsafeByteBuffer(fileSize); int readBytes = 0; while ((readBytes = in.read(buffer)) != -1) { compressedData.put(buffer, 0, readBytes); } compressedData.position(0); compressedData.limit(compressedData.capacity()); } catch (Exception e) { throw new GdxRuntimeException("Couldn't load pkm file '" + pkmFile + "'", e); } finally { if (in != null) try { in.close(); } catch (Exception e) { } } width = getWidthPKM(compressedData, 0); height = getHeightPKM(compressedData, 0); dataOffset = PKM_HEADER_SIZE; compressedData.position(dataOffset); } /** @return whether this ETC1Data has a PKM header */ public boolean hasPKMHeader () { return dataOffset == 16; } /** Writes the ETC1Data with a PKM header to the given file. * @param file the file. */ public void write (FileHandle file) { DataOutputStream write = null; byte[] buffer = new byte[10 * 1024]; int writtenBytes = 0; compressedData.position(0); compressedData.limit(compressedData.capacity()); try { write = new DataOutputStream(new GZIPOutputStream(file.write(false))); write.writeInt(compressedData.capacity()); while (writtenBytes != compressedData.capacity()) { int bytesToWrite = Math.min(compressedData.remaining(), buffer.length); compressedData.get(buffer, 0, bytesToWrite); write.write(buffer, 0, bytesToWrite); writtenBytes += bytesToWrite; } } catch (Exception e) { throw new GdxRuntimeException("Couldn't write PKM file to '" + file + "'", e); } finally { if (write != null) try { write.close(); } catch (Exception e) { } } compressedData.position(dataOffset); compressedData.limit(compressedData.capacity()); } /** Releases the native resources of the ETC1Data instance. */ public void dispose () { BufferUtils.disposeUnsafeByteBuffer(compressedData); } public String toString () { if (hasPKMHeader()) { return (ETC1.isValidPKM(compressedData, 0) ? "valid" : "invalid") + " pkm [" + ETC1.getWidthPKM(compressedData, 0) + "x" + ETC1.getHeightPKM(compressedData, 0) + "], compressed: " + (compressedData.capacity() - ETC1.PKM_HEADER_SIZE); } else { return "raw [" + width + "x" + height + "], compressed: " + (compressedData.capacity() - ETC1.PKM_HEADER_SIZE); } } } private static int getPixelSize (Format format) { if (format == Format.RGB565) return 2; if (format == Format.RGB888) return 3; throw new GdxRuntimeException("Can only handle RGB565 or RGB888 images"); } /** Encodes the image via the ETC1 compression scheme. Only {@link Format#RGB565} and {@link Format#RGB888} are supported. * @param pixmap the {@link Pixmap} * @return the {@link ETC1Data} */ public static ETC1Data encodeImage (Pixmap pixmap) { int pixelSize = getPixelSize(pixmap.getFormat()); ByteBuffer compressedData = encodeImage(pixmap.getPixels(), 0, pixmap.getWidth(), pixmap.getHeight(), pixelSize); return new ETC1Data(pixmap.getWidth(), pixmap.getHeight(), compressedData, 0); } /** Encodes the image via the ETC1 compression scheme. Only {@link Format#RGB565} and {@link Format#RGB888} are supported. Adds * a PKM header in front of the compressed image data. * @param pixmap the {@link Pixmap} * @return the {@link ETC1Data} */ public static ETC1Data encodeImagePKM (Pixmap pixmap) { int pixelSize = getPixelSize(pixmap.getFormat()); ByteBuffer compressedData = encodeImagePKM(pixmap.getPixels(), 0, pixmap.getWidth(), pixmap.getHeight(), pixelSize); return new ETC1Data(pixmap.getWidth(), pixmap.getHeight(), compressedData, 16); } /** Takes ETC1 compressed image data and converts it to a {@link Format#RGB565} or {@link Format#RGB888} {@link Pixmap}. Does * not modify the ByteBuffer's position or limit. * @param etc1Data the {@link ETC1Data} instance * @param format either {@link Format#RGB565} or {@link Format#RGB888} * @return the Pixmap */ public static Pixmap decodeImage (ETC1Data etc1Data, Format format) { int dataOffset = 0; int width = 0; int height = 0; if (etc1Data.hasPKMHeader()) { dataOffset = 16; width = ETC1.getWidthPKM(etc1Data.compressedData, 0); height = ETC1.getHeightPKM(etc1Data.compressedData, 0); } else { dataOffset = 0; width = etc1Data.width; height = etc1Data.height; } int pixelSize = getPixelSize(format); Pixmap pixmap = new Pixmap(width, height, format); decodeImage(etc1Data.compressedData, dataOffset, pixmap.getPixels(), 0, width, height, pixelSize); return pixmap; } /*JNI #include <etc1/etc1_utils.h> #include <stdlib.h> */ /** @param width the width in pixels * @param height the height in pixels * @return the number of bytes needed to store the compressed data */ public static native int getCompressedDataSize (int width, int height); /* return etc1_get_encoded_data_size(width, height); */ /** Writes a PKM header to the {@link ByteBuffer}. Does not modify the position or limit of the ByteBuffer. * @param header the direct native order {@link ByteBuffer} * @param offset the offset to the header in bytes * @param width the width in pixels * @param height the height in pixels */ public static native void formatHeader (ByteBuffer header, int offset, int width, int height); /* etc1_pkm_format_header((etc1_byte*)header + offset, width, height); */ /** @param header direct native order {@link ByteBuffer} holding the PKM header * @param offset the offset in bytes to the PKM header from the ByteBuffer's start * @return the width stored in the PKM header */ static native int getWidthPKM (ByteBuffer header, int offset); /* return etc1_pkm_get_width((etc1_byte*)header + offset); */ /** @param header direct native order {@link ByteBuffer} holding the PKM header * @param offset the offset in bytes to the PKM header from the ByteBuffer's start * @return the height stored in the PKM header */ static native int getHeightPKM (ByteBuffer header, int offset); /* return etc1_pkm_get_height((etc1_byte*)header + offset); */ /** @param header direct native order {@link ByteBuffer} holding the PKM header * @param offset the offset in bytes to the PKM header from the ByteBuffer's start * @return the width stored in the PKM header */ static native boolean isValidPKM (ByteBuffer header, int offset); /* return etc1_pkm_is_valid((etc1_byte*)header + offset) != 0?true:false; */ /** Decodes the compressed image data to RGB565 or RGB888 pixel data. Does not modify the position or limit of the * {@link ByteBuffer} instances. * @param compressedData the compressed image data in a direct native order {@link ByteBuffer} * @param offset the offset in bytes to the image data from the start of the buffer * @param decodedData the decoded data in a direct native order ByteBuffer, must hold width * height * pixelSize bytes. * @param offsetDec the offset in bytes to the decoded image data. * @param width the width in pixels * @param height the height in pixels * @param pixelSize the pixel size, either 2 (RBG565) or 3 (RGB888) */ private static native void decodeImage (ByteBuffer compressedData, int offset, ByteBuffer decodedData, int offsetDec, int width, int height, int pixelSize); /* etc1_decode_image((etc1_byte*)compressedData + offset, (etc1_byte*)decodedData + offsetDec, width, height, pixelSize, width * pixelSize); */ /** Encodes the image data given as RGB565 or RGB888. Does not modify the position or limit of the {@link ByteBuffer}. * @param imageData the image data in a direct native order {@link ByteBuffer} * @param offset the offset in bytes to the image data from the start of the buffer * @param width the width in pixels * @param height the height in pixels * @param pixelSize the pixel size, either 2 (RGB565) or 3 (RGB888) * @return a new direct native order ByteBuffer containing the compressed image data */ private static native ByteBuffer encodeImage (ByteBuffer imageData, int offset, int width, int height, int pixelSize); /* int compressedSize = etc1_get_encoded_data_size(width, height); etc1_byte* compressedData = (etc1_byte*)malloc(compressedSize); etc1_encode_image((etc1_byte*)imageData + offset, width, height, pixelSize, width * pixelSize, compressedData); return env->NewDirectByteBuffer(compressedData, compressedSize); */ /** Encodes the image data given as RGB565 or RGB888. Does not modify the position or limit of the {@link ByteBuffer}. * @param imageData the image data in a direct native order {@link ByteBuffer} * @param offset the offset in bytes to the image data from the start of the buffer * @param width the width in pixels * @param height the height in pixels * @param pixelSize the pixel size, either 2 (RGB565) or 3 (RGB888) * @return a new direct native order ByteBuffer containing the compressed image data */ private static native ByteBuffer encodeImagePKM (ByteBuffer imageData, int offset, int width, int height, int pixelSize); /* int compressedSize = etc1_get_encoded_data_size(width, height); etc1_byte* compressed = (etc1_byte*)malloc(compressedSize + ETC_PKM_HEADER_SIZE); etc1_pkm_format_header(compressed, width, height); etc1_encode_image((etc1_byte*)imageData + offset, width, height, pixelSize, width * pixelSize, compressed + ETC_PKM_HEADER_SIZE); return env->NewDirectByteBuffer(compressed, compressedSize + ETC_PKM_HEADER_SIZE); */ }
true
true
public ETC1Data (FileHandle pkmFile) { byte[] buffer = new byte[1024 * 10]; DataInputStream in = null; try { in = new DataInputStream(new BufferedInputStream(new GZIPInputStream(pkmFile.read()))); int fileSize = in.readInt(); compressedData = BufferUtils.newByteBuffer(fileSize); int readBytes = 0; while ((readBytes = in.read(buffer)) != -1) { compressedData.put(buffer, 0, readBytes); } compressedData.position(0); compressedData.limit(compressedData.capacity()); } catch (Exception e) { throw new GdxRuntimeException("Couldn't load pkm file '" + pkmFile + "'", e); } finally { if (in != null) try { in.close(); } catch (Exception e) { } } width = getWidthPKM(compressedData, 0); height = getHeightPKM(compressedData, 0); dataOffset = PKM_HEADER_SIZE; compressedData.position(dataOffset); }
public ETC1Data (FileHandle pkmFile) { byte[] buffer = new byte[1024 * 10]; DataInputStream in = null; try { in = new DataInputStream(new BufferedInputStream(new GZIPInputStream(pkmFile.read()))); int fileSize = in.readInt(); compressedData = BufferUtils.newUnsafeByteBuffer(fileSize); int readBytes = 0; while ((readBytes = in.read(buffer)) != -1) { compressedData.put(buffer, 0, readBytes); } compressedData.position(0); compressedData.limit(compressedData.capacity()); } catch (Exception e) { throw new GdxRuntimeException("Couldn't load pkm file '" + pkmFile + "'", e); } finally { if (in != null) try { in.close(); } catch (Exception e) { } } width = getWidthPKM(compressedData, 0); height = getHeightPKM(compressedData, 0); dataOffset = PKM_HEADER_SIZE; compressedData.position(dataOffset); }
diff --git a/hk2/auto-depends/src/java/com/sun/hk2/component/LazyInhabitant.java b/hk2/auto-depends/src/java/com/sun/hk2/component/LazyInhabitant.java index a87b6c965..dfd0e2d92 100644 --- a/hk2/auto-depends/src/java/com/sun/hk2/component/LazyInhabitant.java +++ b/hk2/auto-depends/src/java/com/sun/hk2/component/LazyInhabitant.java @@ -1,114 +1,114 @@ /* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 2007-2008 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can obtain * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html * or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt. * Sun designates this particular file as subject to the "Classpath" exception * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * Header, with the fields enclosed by brackets [] replaced by your own * identifying information: "Portions Copyrighted [year] * [name of copyright owner]" * * Contributor(s): * * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. */ package com.sun.hk2.component; import org.jvnet.hk2.component.ComponentException; import org.jvnet.hk2.component.Habitat; import org.jvnet.hk2.component.Inhabitant; import org.jvnet.hk2.component.Inhabitants; import org.jvnet.hk2.component.MultiMap; import org.jvnet.hk2.component.Womb; import org.jvnet.hk2.component.Wombs; /** * @author Kohsuke Kawaguchi */ public class LazyInhabitant<T> extends AbstractInhabitantImpl<T> { private final String typeName; /** * Real {@link Inhabitant} object. Lazily created. */ private volatile Inhabitant<T> real; /** * Lazy reference to {@link ClassLoader}. */ private final Holder<ClassLoader> classLoader; protected final Habitat habitat; private final MultiMap<String,String> metadata; public LazyInhabitant(Habitat habitat, Holder<ClassLoader> cl, String typeName, MultiMap<String,String> metadata) { assert metadata!=null; this.habitat = habitat; this.classLoader = cl; this.typeName = typeName; this.metadata = metadata; } public String typeName() { return typeName; } public Class<T> type() { fetch(); return real.type(); } public MultiMap<String,String> metadata() { return metadata; } @SuppressWarnings("unchecked") - private void fetch() { + private synchronized void fetch() { if(real!=null) return; try { Class<T> c = (Class<T>) classLoader.get().loadClass(typeName); real = Inhabitants.wrapByScope(c,createWomb(c),habitat); } catch (ClassNotFoundException e) { throw new ComponentException("Failed to load "+typeName+" from "+classLoader.get(),e); } } /** * Creates {@link Womb} for instantiating objects. */ protected Womb<T> createWomb(Class<T> c) { return Wombs.create(c,habitat,metadata); } public T get(Inhabitant onBehalfOf) throws ComponentException { fetch(); return real.get(onBehalfOf); } public void release() { if(real!=null) real.release(); } }
true
true
private void fetch() { if(real!=null) return; try { Class<T> c = (Class<T>) classLoader.get().loadClass(typeName); real = Inhabitants.wrapByScope(c,createWomb(c),habitat); } catch (ClassNotFoundException e) { throw new ComponentException("Failed to load "+typeName+" from "+classLoader.get(),e); } }
private synchronized void fetch() { if(real!=null) return; try { Class<T> c = (Class<T>) classLoader.get().loadClass(typeName); real = Inhabitants.wrapByScope(c,createWomb(c),habitat); } catch (ClassNotFoundException e) { throw new ComponentException("Failed to load "+typeName+" from "+classLoader.get(),e); } }
diff --git a/src/com/intervigil/micdroid/wave/WaveWriter.java b/src/com/intervigil/micdroid/wave/WaveWriter.java index af4f356..a5ee32e 100644 --- a/src/com/intervigil/micdroid/wave/WaveWriter.java +++ b/src/com/intervigil/micdroid/wave/WaveWriter.java @@ -1,126 +1,124 @@ /* WaveWriter.java Copyright (c) 2010 Ethan Chen 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.intervigil.micdroid.wave; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.RandomAccessFile; public class WaveWriter { private static final int OUTPUT_STREAM_BUFFER = 16384; private File output; private BufferedOutputStream outputStream; private int bytesWritten; private int sampleRate; private int channels; private int sampleBits; public WaveWriter(String path, String name, int sampleRate, int channels, int sampleBits) { this.output = new File(path + File.separator + name); this.sampleRate = sampleRate; this.channels = channels; this.sampleBits = sampleBits; this.bytesWritten = 0; } public boolean createWaveFile() throws IOException { if (this.output.exists()) { this.output.delete(); } if (this.output.createNewFile()) { // create file, set up output stream FileOutputStream fileStream = new FileOutputStream(output); this.outputStream = new BufferedOutputStream(fileStream, OUTPUT_STREAM_BUFFER); // write 44 bytes of space for the header this.outputStream.write(new byte[44]); return true; } return false; } public void write(short[] buffer, int bufferSize) throws IOException { for (int i = 0; i < bufferSize; i++) { write16BitsLowHigh(this.outputStream, buffer[i]); bytesWritten += 2; } } public void closeWaveFile() throws IOException { // close output stream then rewind and write wave header this.outputStream.flush(); this.outputStream.close(); writeWaveHeader(); } private void writeWaveHeader() throws IOException { // rewind to beginning of the file RandomAccessFile file = new RandomAccessFile(this.output, "rw"); file.seek(0); int bytesPerSec = (sampleBits + 7) / 8; file.writeBytes("RIFF"); // wave label file.writeInt(Integer.reverseBytes(bytesWritten + 36)); // length in // bytes without // header file.writeBytes("WAVEfmt "); file.writeInt(Integer.reverseBytes(16)); // length of pcm format // declaration area file.writeShort(Short.reverseBytes((short) 1)); // is PCM file.writeShort(Short.reverseBytes((short) channels)); // number of // channels, this // is mono file.writeInt(Integer.reverseBytes(sampleRate)); // sample rate, this is // probably 22050 Hz - file - .writeInt(Integer.reverseBytes(sampleRate * channels - * bytesPerSec)); // bytes per second + file.writeInt(Integer.reverseBytes(sampleRate * channels * bytesPerSec)); // bytes per second file.writeShort(Short.reverseBytes((short) (channels * bytesPerSec))); // bytes // per // sample // time file.writeShort(Short.reverseBytes((short) sampleBits)); // bits per // sample, this // is 16 bit // pcm file.writeBytes("data"); // data section label file.writeInt(Integer.reverseBytes(bytesWritten)); // length of raw pcm // data in bytes file.close(); file = null; } private static void write16BitsLowHigh(OutputStream stream, short sample) throws IOException { // write already writes the lower order byte of this short stream.write(sample); stream.write((sample >> 8)); } }
true
true
private void writeWaveHeader() throws IOException { // rewind to beginning of the file RandomAccessFile file = new RandomAccessFile(this.output, "rw"); file.seek(0); int bytesPerSec = (sampleBits + 7) / 8; file.writeBytes("RIFF"); // wave label file.writeInt(Integer.reverseBytes(bytesWritten + 36)); // length in // bytes without // header file.writeBytes("WAVEfmt "); file.writeInt(Integer.reverseBytes(16)); // length of pcm format // declaration area file.writeShort(Short.reverseBytes((short) 1)); // is PCM file.writeShort(Short.reverseBytes((short) channels)); // number of // channels, this // is mono file.writeInt(Integer.reverseBytes(sampleRate)); // sample rate, this is // probably 22050 Hz file .writeInt(Integer.reverseBytes(sampleRate * channels * bytesPerSec)); // bytes per second file.writeShort(Short.reverseBytes((short) (channels * bytesPerSec))); // bytes // per // sample // time file.writeShort(Short.reverseBytes((short) sampleBits)); // bits per // sample, this // is 16 bit // pcm file.writeBytes("data"); // data section label file.writeInt(Integer.reverseBytes(bytesWritten)); // length of raw pcm // data in bytes file.close(); file = null; }
private void writeWaveHeader() throws IOException { // rewind to beginning of the file RandomAccessFile file = new RandomAccessFile(this.output, "rw"); file.seek(0); int bytesPerSec = (sampleBits + 7) / 8; file.writeBytes("RIFF"); // wave label file.writeInt(Integer.reverseBytes(bytesWritten + 36)); // length in // bytes without // header file.writeBytes("WAVEfmt "); file.writeInt(Integer.reverseBytes(16)); // length of pcm format // declaration area file.writeShort(Short.reverseBytes((short) 1)); // is PCM file.writeShort(Short.reverseBytes((short) channels)); // number of // channels, this // is mono file.writeInt(Integer.reverseBytes(sampleRate)); // sample rate, this is // probably 22050 Hz file.writeInt(Integer.reverseBytes(sampleRate * channels * bytesPerSec)); // bytes per second file.writeShort(Short.reverseBytes((short) (channels * bytesPerSec))); // bytes // per // sample // time file.writeShort(Short.reverseBytes((short) sampleBits)); // bits per // sample, this // is 16 bit // pcm file.writeBytes("data"); // data section label file.writeInt(Integer.reverseBytes(bytesWritten)); // length of raw pcm // data in bytes file.close(); file = null; }
diff --git a/src/com/ijg/darklight/core/ModuleHandler.java b/src/com/ijg/darklight/core/ModuleHandler.java index ef569f5..bffdfaa 100644 --- a/src/com/ijg/darklight/core/ModuleHandler.java +++ b/src/com/ijg/darklight/core/ModuleHandler.java @@ -1,115 +1,115 @@ package com.ijg.darklight.core; import java.util.ArrayList; import java.util.HashMap; import me.shanked.nicatronTg.darklight.view.VulnerabilityOutput; import com.ijg.darklight.core.loader.ModuleLoader; /** * Handles the scoring modules * @author Isaac Grant * @author Lucas Nicodemus * @version .1 * @see com.ijg.darklight.core.ScoreModule */ public class ModuleHandler { private Engine engine; private double total; private ArrayList<Issue> issues = new ArrayList<Issue>(); private ArrayList<ScoreModule> modules = new ArrayList<ScoreModule>(); private VulnerabilityOutput outputManager; /** * * @param engine The instance of engine to which this module handler will belong */ public ModuleHandler(Engine engine) { this.engine = engine; outputManager = new VulnerabilityOutput(this); ScoreModule[] loadedModules = ModuleLoader.loadAllModules(); for (ScoreModule loadedModule : loadedModules) { modules.add(loadedModule); } for (ScoreModule module : modules) { total += module.getIssueCount(); } } /** * Generate a hash map of fixed issues * @return A hash map of fixed issues */ public HashMap<String, String> getFixedIssues() { HashMap<String, String> issuesMap = new HashMap<String, String>(); for (Issue issue : issues) { issuesMap.put(issue.getName(), issue.getDescription()); } return issuesMap; } /** * Update the status of all issues */ public void checkAllVulnerabilities() { boolean changed = false; for (ScoreModule module : modules) { ArrayList<Issue> modifiedIssues = module.check(); for (Issue issue : modifiedIssues) { - if (issue.getFixed() && issues.contains(issue)) { + if (issue.getFixed() && !issues.contains(issue)) { issues.add(issue); changed = true; } else if (!issue.getFixed() && issues.contains(issue)) { issues.remove(issue); changed = true; } } } if (changed) { outputManager.writeNewOutput(); engine.authUser(); engine.sendUpdate(issues.size(), getFixedIssues()); } } /** * Get all fixed issues * @return All fixed issues */ public ArrayList<Issue> getIssues() { return issues; } /** * Get the total number of issues * @return The total number of issues */ public int getTotalIssueCount() { return (int) total; } /** * Get number of issues that have been fixed * @return Number of issues that have been fixed */ public int getFixedIssueCount() { return issues.size(); } /** * Get the percentage of fixed issues * @return The percentage of fixed issues */ public String getFixedIssuePercent() { return "" + ((int) (((double) issues.size()) / total) * 100) + "%"; } }
true
true
public void checkAllVulnerabilities() { boolean changed = false; for (ScoreModule module : modules) { ArrayList<Issue> modifiedIssues = module.check(); for (Issue issue : modifiedIssues) { if (issue.getFixed() && issues.contains(issue)) { issues.add(issue); changed = true; } else if (!issue.getFixed() && issues.contains(issue)) { issues.remove(issue); changed = true; } } } if (changed) { outputManager.writeNewOutput(); engine.authUser(); engine.sendUpdate(issues.size(), getFixedIssues()); } }
public void checkAllVulnerabilities() { boolean changed = false; for (ScoreModule module : modules) { ArrayList<Issue> modifiedIssues = module.check(); for (Issue issue : modifiedIssues) { if (issue.getFixed() && !issues.contains(issue)) { issues.add(issue); changed = true; } else if (!issue.getFixed() && issues.contains(issue)) { issues.remove(issue); changed = true; } } } if (changed) { outputManager.writeNewOutput(); engine.authUser(); engine.sendUpdate(issues.size(), getFixedIssues()); } }
diff --git a/src/main/java/org/multibit/viewsystem/swing/MultiBitFrame.java b/src/main/java/org/multibit/viewsystem/swing/MultiBitFrame.java index 54c01e41..4d6a1718 100644 --- a/src/main/java/org/multibit/viewsystem/swing/MultiBitFrame.java +++ b/src/main/java/org/multibit/viewsystem/swing/MultiBitFrame.java @@ -1,1765 +1,1766 @@ /** * Copyright 2012 multibit.org * * Licensed under the MIT license (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://opensource.org/licenses/mit-license.php * * 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.multibit.viewsystem.swing; import java.awt.BorderLayout; import java.awt.Component; import java.awt.ComponentOrientation; import java.awt.Container; import java.awt.Cursor; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.FontMetrics; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.SystemColor; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.math.BigInteger; import java.util.List; import java.util.Timer; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.InputMap; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JSplitPane; import javax.swing.JTextField; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.ToolTipManager; import javax.swing.UIManager; import javax.swing.plaf.basic.BasicSplitPaneDivider; import javax.swing.text.DefaultEditorKit; import org.bitcoinj.wallet.Protos.Wallet.EncryptionType; import org.joda.money.Money; import org.multibit.Localiser; import org.multibit.controller.Controller; import org.multibit.controller.bitcoin.BitcoinController; import org.multibit.controller.core.CoreController; import org.multibit.controller.exchange.ExchangeController; import org.multibit.exchange.CurrencyConverter; import org.multibit.exchange.CurrencyConverterListener; import org.multibit.exchange.ExchangeRate; import org.multibit.exchange.TickerTimerTask; import org.multibit.message.Message; import org.multibit.message.MessageManager; import org.multibit.model.bitcoin.BitcoinModel; import org.multibit.model.bitcoin.WalletBusyListener; import org.multibit.model.bitcoin.WalletData; import org.multibit.model.core.StatusEnum; import org.multibit.model.exchange.ExchangeModel; import org.multibit.network.ReplayManager; import org.multibit.platform.GenericApplication; import org.multibit.platform.listener.GenericQuitEventListener; import org.multibit.platform.listener.GenericQuitResponse; import org.multibit.store.MultiBitWalletVersion; import org.multibit.utils.ImageLoader; import org.multibit.viewsystem.DisplayHint; import org.multibit.viewsystem.View; import org.multibit.viewsystem.ViewSystem; import org.multibit.viewsystem.Viewable; import org.multibit.viewsystem.swing.action.AbstractExitAction; import org.multibit.viewsystem.swing.action.CloseWalletAction; import org.multibit.viewsystem.swing.action.CreateWalletSubmitAction; import org.multibit.viewsystem.swing.action.DeleteWalletAction; import org.multibit.viewsystem.swing.action.HelpContextAction; import org.multibit.viewsystem.swing.action.MnemonicUtil; import org.multibit.viewsystem.swing.action.MultiBitAction; import org.multibit.viewsystem.swing.action.MultiBitWalletBusyAction; import org.multibit.viewsystem.swing.action.OpenWalletAction; import org.multibit.viewsystem.swing.view.ViewFactory; import org.multibit.viewsystem.swing.view.components.BlinkLabel; import org.multibit.viewsystem.swing.view.components.FontSizer; import org.multibit.viewsystem.swing.view.components.HelpButton; import org.multibit.viewsystem.swing.view.components.MultiBitLabel; import org.multibit.viewsystem.swing.view.components.MultiBitTitledPanel; import org.multibit.viewsystem.swing.view.panels.HelpContentsPanel; import org.multibit.viewsystem.swing.view.panels.SendBitcoinConfirmPanel; import org.multibit.viewsystem.swing.view.panels.ShowTransactionsPanel; import org.multibit.viewsystem.swing.view.ticker.TickerTablePanel; import org.multibit.viewsystem.swing.view.walletlist.SingleWalletPanel; import org.multibit.viewsystem.swing.view.walletlist.WalletListPanel; import org.simplericity.macify.eawt.ApplicationEvent; import org.simplericity.macify.eawt.ApplicationListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.bitcoin.core.ECKey; import com.google.bitcoin.core.Sha256Hash; import com.google.bitcoin.core.Transaction; import com.google.bitcoin.core.Wallet; /* * JFrame displaying Swing version of MultiBit */ public class MultiBitFrame extends JFrame implements ViewSystem, ApplicationListener, WalletBusyListener, CurrencyConverterListener { private static final Logger log = LoggerFactory.getLogger(MultiBitFrame.class); private static final double PROPORTION_OF_VERTICAL_SCREEN_TO_FILL = 0.75D; private static final double PROPORTION_OF_HORIZONTAL_SCREEN_TO_FILL = 0.82D; public static final String EXAMPLE_LONG_FIELD_TEXT = "1JiM1UyTGqpLqgayxTPbWbcdVeoepmY6pK++++"; public static final String EXAMPLE_MEDIUM_FIELD_TEXT = "Typical text 00.12345678 BTC (000.01 XYZ)"; public static final int WIDTH_OF_LONG_FIELDS = 300; public static final int WIDTH_OF_AMOUNT_FIELD = 150; public static final int WALLET_WIDTH_DELTA = 25; public static final int SCROLL_BAR_DELTA = 20; public static final int HEIGHT_OF_HEADER = 70; public static final int WIDTH_OF_SPLIT_PANE_DIVIDER = 9; private StatusBar statusBar; private StatusEnum online = StatusEnum.CONNECTING; public static final String SEPARATOR = " - "; private static final long serialVersionUID = 7621813615342923041L; private final Controller controller; private final CoreController coreController; private final BitcoinController bitcoinController; private final ExchangeController exchangeController; private Localiser localiser; private String helpContext; public String getHelpContext() { return helpContext; } @Override public void setHelpContext(String helpContext) { this.helpContext = helpContext; } private MultiBitLabel estimatedBalanceLabelLabel; private BlinkLabel estimatedBalanceBTCLabel; private BlinkLabel estimatedBalanceFiatLabel; public BlinkLabel getEstimatedBalanceBTCLabel() { return estimatedBalanceBTCLabel; } public BlinkLabel getEstimatedBalanceFiatLabel() { return estimatedBalanceFiatLabel; } private HelpButton availableBalanceLabelButton; private HelpButton availableBalanceBTCButton; private HelpButton availableBalanceFiatButton; /** * list of wallets shown in left hand column */ private WalletListPanel walletsView; private JSplitPane splitPane; private static final int TOOLTIP_DISMISSAL_DELAY = 12000; // millisecs /** * Provide the Application reference during construction */ private final GenericApplication application; private final GenericQuitResponse multiBitFrameQuitResponse = new GenericQuitResponse() { @Override public void cancelQuit() { log.debug("Quit Canceled"); } @Override public void performQuit() { log.debug("Performed Quit"); } }; final private GenericQuitEventListener quitEventListener; /** * the tabbed pane containing the views * */ private MultiBitTabbedPane viewTabbedPane; public Logger logger = LoggerFactory.getLogger(MultiBitFrame.class.getName()); private ViewFactory viewFactory; private Timer fileChangeTimer; private Timer tickerTimer1; private Timer tickerTimer2; private TickerTimerTask tickerTimerTask1; private TickerTimerTask tickerTimerTask2; private JPanel headerPanel; private TickerTablePanel tickerTablePanel; private MultiBitWalletBusyAction addPasswordAction; private MultiBitWalletBusyAction changePasswordAction; private MultiBitWalletBusyAction removePasswordAction; private MultiBitWalletBusyAction signMessageAction; private MultiBitWalletBusyAction showImportPrivateKeysAction; private MultiBitWalletBusyAction showExportPrivateKeysAction; private MultiBitWalletBusyAction resetTransactionsAction; /** * For events coming from Peers condense the events into regular updates. * This is to prevent the UI thrashing with hundreds of events per second. */ public static final int FIRE_DATA_CHANGED_UPDATE_LATER_DELAY_TIME = 1000; // milliseconds /** * Timer used to condense multiple updates */ private static Timer fireDataChangedTimer; private static FireDataChangedTimerTask fireDataChangedTimerTask; @SuppressWarnings("deprecation") public MultiBitFrame(CoreController coreController, BitcoinController bitcoinController, ExchangeController exchangeController, GenericApplication application, View initialView) { this.coreController = coreController; this.bitcoinController = bitcoinController; this.exchangeController = exchangeController; this.controller = this.coreController; this.quitEventListener = this.coreController; this.localiser = controller.getLocaliser(); this.application = application; // Remap to command v and C on a Mac if (application != null && application.isMac()) { InputMap im = (InputMap) UIManager.get("TextField.focusInputMap"); im.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, KeyEvent.META_DOWN_MASK), DefaultEditorKit.copyAction); im.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, KeyEvent.META_DOWN_MASK), DefaultEditorKit.pasteAction); im.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, KeyEvent.META_DOWN_MASK), DefaultEditorKit.cutAction); } ColorAndFontConstants.init(); FontSizer.INSTANCE.initialise(controller); UIManager.put("ToolTip.font", FontSizer.INSTANCE.getAdjustedDefaultFont()); setCursor(Cursor.WAIT_CURSOR); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); String titleText = localiser.getString("multiBitFrame.title"); if (this.bitcoinController.getModel().getActiveWallet() != null) { titleText = titleText + SEPARATOR + this.bitcoinController.getModel().getActivePerWalletModelData().getWalletDescription() + SEPARATOR + this.bitcoinController.getModel().getActivePerWalletModelData().getWalletFilename(); } setTitle(titleText); ToolTipManager.sharedInstance().setDismissDelay(TOOLTIP_DISMISSAL_DELAY); // TODO Examine how this fits in with the controller onQuit() event // Cam: I've moved this to the quit event. addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent arg0) { quitEventListener.onQuitEvent(null, multiBitFrameQuitResponse); } }); applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale())); sizeAndCenter(); viewFactory = new ViewFactory(this.bitcoinController, this.exchangeController, this); initUI(initialView); this.bitcoinController.registerWalletBusyListener(this); // Initialise the file change timer. fileChangeTimer = new Timer(); fileChangeTimer.schedule(new FileChangeTimerTask(this.bitcoinController), FileChangeTimerTask.INITIAL_DELAY, FileChangeTimerTask.DEFAULT_REPEAT_RATE); // Initialise the tickers. tickerTimer1 = new Timer(); tickerTimerTask1 = new TickerTimerTask(this.exchangeController, this, true); tickerTimer1.schedule(tickerTimerTask1, TickerTimerTask.INITIAL_DELAY, TickerTimerTask.DEFAULT_REPEAT_RATE); tickerTimer2 = new Timer(); tickerTimerTask2 = new TickerTimerTask(this.exchangeController, this, false); tickerTimer2.schedule(tickerTimerTask2, TickerTimerTask.INITIAL_DELAY + TickerTimerTask.TASK_SEPARATION, TickerTimerTask.DEFAULT_REPEAT_RATE); // Initialise status bar. statusBar.initialise(); estimatedBalanceLabelLabel.setFocusable(false); estimatedBalanceBTCLabel.setFocusable(false); estimatedBalanceFiatLabel.setFocusable(false); availableBalanceLabelButton.setFocusable(false); availableBalanceBTCButton.setFocusable(false); availableBalanceFiatButton.setFocusable(false); updateHeader(); calculateDividerPosition(); MultiBitTabbedPane.setEnableUpdates(true); CurrencyConverter.INSTANCE.addCurrencyConverterListener(this); displayView(null != initialView ? initialView : View.DEFAULT_VIEW()); pack(); setVisible(true); fireDataChangedTimerTask = new FireDataChangedTimerTask(this); fireDataChangedTimer = new Timer(); fireDataChangedTimer.scheduleAtFixedRate(fireDataChangedTimerTask, FIRE_DATA_CHANGED_UPDATE_LATER_DELAY_TIME, FIRE_DATA_CHANGED_UPDATE_LATER_DELAY_TIME); } public GenericApplication getApplication() { return application; } private void sizeAndCenter() { // Get the screen size as a java dimension. Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int height = (int) (screenSize.height * PROPORTION_OF_VERTICAL_SCREEN_TO_FILL); int width = (int) (screenSize.width * PROPORTION_OF_HORIZONTAL_SCREEN_TO_FILL); // Set the jframe height and width. setPreferredSize(new Dimension(width, height)); double startVerticalPositionRatio = (1 - PROPORTION_OF_VERTICAL_SCREEN_TO_FILL) / 2; double startHorizontalPositionRatio = (1 - PROPORTION_OF_HORIZONTAL_SCREEN_TO_FILL) / 2; setLocation((int) (width * startHorizontalPositionRatio), (int) (height * startVerticalPositionRatio)); } private void initUI(View initialView) { Container contentPane = getContentPane(); contentPane.setLayout(new GridBagLayout()); contentPane.setBackground(ColorAndFontConstants.BACKGROUND_COLOR); GridBagConstraints constraints = new GridBagConstraints(); GridBagConstraints constraints2 = new GridBagConstraints(); // Set the application icon. ImageIcon imageIcon = ImageLoader.createImageIcon(ImageLoader.MULTIBIT_ICON_FILE); if (imageIcon != null) { setIconImage(imageIcon.getImage()); } headerPanel = new JPanel(); headerPanel.setOpaque(false); headerPanel.setBackground(ColorAndFontConstants.BACKGROUND_COLOR); headerPanel.setLayout(new GridBagLayout()); headerPanel.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale())); JPanel balancePanel = createBalancePanel(); constraints2.fill = GridBagConstraints.BOTH; constraints2.gridx = 0; constraints2.gridy = 0; constraints2.gridwidth = 1; constraints2.gridheight = 1; constraints2.weightx = 1.0; constraints2.weighty = 1.0; constraints2.anchor = GridBagConstraints.LINE_START; headerPanel.add(balancePanel, constraints2); addMenuBar(constraints, contentPane); constraints.fill = GridBagConstraints.BOTH; constraints.gridx = 0; constraints.gridy = 0; constraints.gridwidth = 2; constraints.weightx = 1.0; constraints.weighty = 1.0; constraints.anchor = GridBagConstraints.LINE_START; contentPane.add(headerPanel, constraints); // Create the wallet list panel. walletsView = new WalletListPanel(this.bitcoinController, this); // Create the tabbedpane that holds the views. viewTabbedPane = new MultiBitTabbedPane(controller); viewTabbedPane.setBackground(ColorAndFontConstants.BACKGROUND_COLOR); // Add the send bitcoin tab. JPanel sendBitcoinOutlinePanel = new JPanel(new BorderLayout()); Viewable sendBitcoinView = viewFactory.getView(View.SEND_BITCOIN_VIEW); sendBitcoinOutlinePanel.add((JPanel) sendBitcoinView, BorderLayout.CENTER); viewTabbedPane.addTab(sendBitcoinView.getViewTitle(), sendBitcoinView.getViewIcon(), sendBitcoinView.getViewTooltip(), sendBitcoinOutlinePanel); // Add the receive bitcoin tab. JPanel receiveBitcoinOutlinePanel = new JPanel(new BorderLayout()); Viewable receiveBitcoinView = viewFactory.getView(View.RECEIVE_BITCOIN_VIEW); receiveBitcoinOutlinePanel.add((JPanel) receiveBitcoinView, BorderLayout.CENTER); viewTabbedPane.addTab(receiveBitcoinView.getViewTitle(), receiveBitcoinView.getViewIcon(), receiveBitcoinView.getViewTooltip(), receiveBitcoinOutlinePanel); // Add the transactions tab. JPanel transactionsOutlinePanel = new JPanel(new BorderLayout()); Viewable transactionsView = viewFactory.getView(View.TRANSACTIONS_VIEW); transactionsOutlinePanel.add((JPanel) transactionsView, BorderLayout.CENTER); viewTabbedPane.addTab(transactionsView.getViewTitle(), transactionsView.getViewIcon(), transactionsView.getViewTooltip(), transactionsOutlinePanel); if (initialView == View.SEND_BITCOIN_VIEW) { viewTabbedPane.setSelectedIndex(0); } else if (initialView == View.RECEIVE_BITCOIN_VIEW) { viewTabbedPane.setSelectedIndex(1); } else if (initialView == View.TRANSACTIONS_VIEW) { viewTabbedPane.setSelectedIndex(2); } // Create a split pane with the two scroll panes in it. if (ComponentOrientation.LEFT_TO_RIGHT == ComponentOrientation.getOrientation(controller.getLocaliser().getLocale())) { splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, (JPanel) walletsView, viewTabbedPane); } else { splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, viewTabbedPane, (JPanel) walletsView); splitPane.setResizeWeight(1.0); } splitPane.setOneTouchExpandable(false); splitPane.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, SystemColor.windowBorder)); splitPane.setBackground(ColorAndFontConstants.BACKGROUND_COLOR); BasicSplitPaneDivider divider = ( ( javax.swing.plaf.basic.BasicSplitPaneUI)splitPane.getUI()).getDivider(); divider.setDividerSize(WIDTH_OF_SPLIT_PANE_DIVIDER); constraints.fill = GridBagConstraints.BOTH; constraints.gridx = 0; constraints.gridy = 1; constraints.gridwidth = 2; constraints.gridheight = 1; constraints.weightx = 1.0; constraints.weighty = 1000.0; constraints.gridwidth = 1; constraints.anchor = GridBagConstraints.LINE_START; contentPane.add(splitPane, constraints); calculateDividerPosition(); // Cannot get the RTL wallets drawing nicely so switch off adjustment. splitPane.setEnabled(ComponentOrientation.LEFT_TO_RIGHT.equals(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()))); statusBar = new StatusBar(this.bitcoinController, this); statusBar.updateOnlineStatusText(online); MessageManager.INSTANCE.addMessageListener(statusBar); constraints.fill = GridBagConstraints.BOTH; constraints.gridx = 0; constraints.gridy = 2; constraints.weightx = 1; constraints.weighty = 0.1; constraints.gridwidth = 2; contentPane.add(statusBar, constraints); } private JPanel createBalancePanel() { JPanel headerPanel = new JPanel(); headerPanel.setMinimumSize(new Dimension(700, HEIGHT_OF_HEADER)); headerPanel.setPreferredSize(new Dimension(700, HEIGHT_OF_HEADER)); headerPanel.setOpaque(false); headerPanel.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale())); headerPanel.setLayout(new GridBagLayout()); GridBagConstraints constraints = new GridBagConstraints(); constraints.gridx = 0; constraints.gridy = 0; constraints.weightx = 0.01; constraints.weighty = 0.6; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.anchor = GridBagConstraints.LINE_START; headerPanel.add(MultiBitTitledPanel.createStent(8, 8), constraints); constraints.fill = GridBagConstraints.NONE; constraints.gridx = 3; constraints.gridy = 0; constraints.weightx = 0.01; constraints.weighty = 0.6; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.anchor = GridBagConstraints.LINE_START; String[] keys = new String[] { "multiBitFrame.balanceLabel", "multiBitFrame.availableToSpend2"}; int stentWidth = MultiBitTitledPanel.calculateStentWidthForKeys(controller.getLocaliser(), keys, headerPanel); headerPanel.add(MultiBitTitledPanel.createStent(stentWidth, 1), constraints); FontMetrics fontMetrics = this.getFontMetrics(FontSizer.INSTANCE.getAdjustedDefaultFont()); int availableToSpendWidth = fontMetrics.stringWidth(controller.getLocaliser().getString("multiBitFrame.availableToSpend2")); int availableToSpendHeight = fontMetrics.getHeight(); estimatedBalanceLabelLabel = new MultiBitLabel(controller.getLocaliser().getString("multiBitFrame.balanceLabel"), JTextField.RIGHT); estimatedBalanceLabelLabel.setToolTipText(HelpContentsPanel.createTooltipText(controller.getLocaliser().getString("multiBitFrame.balanceLabel.tooltip"))); estimatedBalanceLabelLabel.setFont(FontSizer.INSTANCE.getAdjustedDefaultFontWithDelta(3 * ColorAndFontConstants.MULTIBIT_LARGE_FONT_INCREASE)); constraints.gridx = 3; constraints.gridy = 1; constraints.weightx = 0.6; constraints.weighty = 0.4; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.anchor = GridBagConstraints.LINE_END; headerPanel.add(estimatedBalanceLabelLabel, constraints); headerPanel.add(MultiBitTitledPanel.createStent(availableToSpendWidth, availableToSpendHeight), constraints); constraints.gridx = 4; constraints.gridy = 0; constraints.weightx = 0.01; constraints.weighty = 0.6; constraints.anchor = GridBagConstraints.LINE_START; headerPanel.add(MultiBitTitledPanel.createStent(12), constraints); estimatedBalanceBTCLabel = new BlinkLabel(controller, true); estimatedBalanceBTCLabel.setToolTipText(HelpContentsPanel.createTooltipText(controller.getLocaliser().getString("multiBitFrame.balanceLabel.tooltip"))); estimatedBalanceBTCLabel.setBorder(BorderFactory.createEmptyBorder()); //estimatedBalanceBTCLabel.setBorder(BorderFactory.createLineBorder(Color.RED)); constraints.gridx = 5; constraints.gridy = 1; constraints.weightx = 0.6; constraints.weighty = 0.6; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.anchor = GridBagConstraints.LINE_START; headerPanel.add(estimatedBalanceBTCLabel, constraints); estimatedBalanceFiatLabel = new BlinkLabel(controller, true); estimatedBalanceFiatLabel.setToolTipText(HelpContentsPanel.createTooltipText(controller.getLocaliser().getString("multiBitFrame.balanceLabel.tooltip"))); estimatedBalanceFiatLabel.setBorder(BorderFactory.createEmptyBorder()); //estimatedBalanceFiatLabel.setBorder(BorderFactory.createLineBorder(Color.RED)); constraints.gridx = 6; constraints.gridy = 0; constraints.weightx = 0.01; constraints.weighty = 0.6; constraints.anchor = GridBagConstraints.LINE_START; headerPanel.add(MultiBitTitledPanel.createStent(12), constraints); constraints.gridx = 7; constraints.gridy = 1; constraints.weightx = 0.6; constraints.weighty = 0.6; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.anchor = GridBagConstraints.LINE_START; headerPanel.add(estimatedBalanceFiatLabel, constraints); Action availableBalanceHelpAction = new HelpContextAction(controller, null, "multiBitFrame.availableToSpend2", "multiBitFrame.availableToSpend.tooltip", "multiBitFrame.helpMenuText", HelpContentsPanel.HELP_AVAILABLE_TO_SPEND_URL); availableBalanceLabelButton = new HelpButton(availableBalanceHelpAction, controller); availableBalanceLabelButton.setHorizontalAlignment(JLabel.RIGHT); availableBalanceLabelButton.setBorder(BorderFactory.createEmptyBorder()); String tooltipText = HelpContentsPanel.createMultilineTooltipText(new String[] { controller.getLocaliser().getString("multiBitFrame.availableToSpend.tooltip"), "\n", controller.getLocaliser().getString("multiBitFrame.helpMenuTooltip") }); availableBalanceLabelButton.setToolTipText(tooltipText); availableBalanceLabelButton.setBorder(BorderFactory.createEmptyBorder()); constraints.gridx = 3; constraints.gridy = 2; constraints.weightx = 0.6; constraints.weighty = 0.4; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.anchor = GridBagConstraints.LINE_END; headerPanel.add(availableBalanceLabelButton, constraints); headerPanel.add(MultiBitTitledPanel.createStent(availableToSpendWidth, availableToSpendHeight), constraints); constraints.gridx = 5; constraints.gridy = 2; constraints.weightx = 0.6; constraints.weighty = 0.01; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.anchor = GridBagConstraints.LINE_START; availableBalanceBTCButton = new HelpButton(availableBalanceHelpAction, controller); availableBalanceBTCButton.setBorder(BorderFactory.createEmptyBorder()); availableBalanceBTCButton.setToolTipText(tooltipText); headerPanel.add(availableBalanceBTCButton, constraints); constraints.gridx = 7; constraints.gridy = 2; constraints.weightx = 0.6; constraints.weighty = 0.01; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.anchor = GridBagConstraints.LINE_START; availableBalanceFiatButton = new HelpButton(availableBalanceHelpAction, controller); availableBalanceFiatButton.setBorder(BorderFactory.createEmptyBorder()); availableBalanceFiatButton.setToolTipText(tooltipText); //availableBalanceFiatButton.setBorder(BorderFactory.createLineBorder(Color.RED)); headerPanel.add(availableBalanceFiatButton, constraints); constraints.gridx = 0; constraints.gridy = 3; constraints.weightx = 0.01; constraints.weighty = 0.6; constraints.anchor = GridBagConstraints.LINE_START; headerPanel.add(MultiBitTitledPanel.createStent(8, 8), constraints); JPanel forcer1 = new JPanel(); forcer1.setOpaque(false); //forcer1.setBorder(BorderFactory.createLineBorder(Color.CYAN)); constraints.fill = GridBagConstraints.BOTH; constraints.gridx = 8; constraints.gridy = 2; constraints.weightx = 10000; constraints.weighty = 10000; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.anchor = GridBagConstraints.LINE_END; headerPanel.add(forcer1, constraints); JPanel forcer2 = new JPanel(); forcer2.setOpaque(false); //forcer2.setBorder(BorderFactory.createLineBorder(Color.YELLOW)); constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridx = 8; constraints.gridy = 1; constraints.weightx = 10000; constraints.weighty = 0.01; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.anchor = GridBagConstraints.LINE_END; headerPanel.add(forcer2, constraints); // Initially invisible. availableBalanceLabelButton.setVisible(false); availableBalanceLabelButton.setEnabled(false); availableBalanceBTCButton.setVisible(false); availableBalanceBTCButton.setEnabled(false); availableBalanceFiatButton.setVisible(false); availableBalanceFiatButton.setEnabled(false); JPanel filler3 = new JPanel(); filler3.setOpaque(false); constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridx = 8; constraints.gridy = 0; constraints.weightx = 1000; constraints.weighty = 1.0; constraints.gridwidth = 1; constraints.gridheight = 2; constraints.anchor = GridBagConstraints.LINE_START; headerPanel.add(filler3, constraints); // Add ticker panel. tickerTablePanel = new TickerTablePanel(this, this.exchangeController); constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridx = 9; constraints.gridy = 0; constraints.weightx = 1; constraints.weighty = 1; constraints.gridwidth = 1; constraints.gridheight = 3; constraints.anchor = GridBagConstraints.CENTER; headerPanel.add(tickerTablePanel, constraints); // Add a little stent to keep it off the right hand edge. int stent = 6; // A reasonable default. Insets tabAreaInsets = UIManager.getInsets("TabbedPane.tabAreaInsets"); if (tabAreaInsets != null) { stent = tabAreaInsets.right; } constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridx = 10; constraints.gridy = 0; constraints.weightx = 1; constraints.weighty = 1; constraints.anchor = GridBagConstraints.BASELINE_TRAILING; headerPanel.add(MultiBitTitledPanel.createStent(stent), constraints); return headerPanel; } /** * @param constraints * @param contentPane */ private void addMenuBar(GridBagConstraints constraints, Container contentPane) { ComponentOrientation componentOrientation = ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()); // Create the menu bar. JMenuBar menuBar = new JMenuBar(); menuBar.setComponentOrientation(componentOrientation); // Create the toolBar. JPanel toolBarPanel = new JPanel(); toolBarPanel.setOpaque(false); MnemonicUtil mnemonicUtil = new MnemonicUtil(controller.getLocaliser()); // Build the File menu. JMenu fileMenu = new JMenu(localiser.getString("multiBitFrame.fileMenuText")); fileMenu.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); fileMenu.setComponentOrientation(componentOrientation); fileMenu.setMnemonic(mnemonicUtil.getMnemonic("multiBitFrame.fileMenuMnemonic")); menuBar.add(fileMenu); // Build the Trade menu. JMenu tradeMenu = new JMenu(localiser.getString("multiBitFrame.tradeMenuText")); tradeMenu.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); tradeMenu.setComponentOrientation(componentOrientation); tradeMenu.setMnemonic(mnemonicUtil.getMnemonic("multiBitFrame.tradeMenuMnemonic")); menuBar.add(tradeMenu); // Build the View menu. JMenu viewMenu = new JMenu(localiser.getString("multiBitFrame.viewMenuText")); viewMenu.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); viewMenu.setComponentOrientation(componentOrientation); viewMenu.setMnemonic(mnemonicUtil.getMnemonic("multiBitFrame.viewMenuMnemonic")); menuBar.add(viewMenu); // Build the Tools menu. JMenu toolsMenu = new JMenu(localiser.getString("multiBitFrame.toolsMenuText")); toolsMenu.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); toolsMenu.setComponentOrientation(componentOrientation); toolsMenu.setMnemonic(mnemonicUtil.getMnemonic("multiBitFrame.toolsMenuMnemonic")); menuBar.add(toolsMenu); // Build the Help menu. JMenu helpMenu = new JMenu(localiser.getString("multiBitFrame.helpMenuText")); helpMenu.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); helpMenu.setComponentOrientation(componentOrientation); helpMenu.setMnemonic(mnemonicUtil.getMnemonic("multiBitFrame.helpMenuMnemonic")); menuBar.add(helpMenu); // Create new wallet action. CreateWalletSubmitAction createNewWalletAction = new CreateWalletSubmitAction(this.bitcoinController, ImageLoader.createImageIcon(ImageLoader.CREATE_NEW_ICON_FILE), this); JMenuItem menuItem = new JMenuItem(createNewWalletAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); fileMenu.add(menuItem); // Open wallet action. OpenWalletAction openWalletAction = new OpenWalletAction(this.bitcoinController, ImageLoader.createImageIcon(ImageLoader.OPEN_WALLET_ICON_FILE), this); menuItem = new JMenuItem(openWalletAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); fileMenu.add(menuItem); CloseWalletAction closeWalletAction = new CloseWalletAction(this.bitcoinController, ImageLoader.createImageIcon(ImageLoader.CLOSE_WALLET_ICON_FILE), this); menuItem = new JMenuItem(closeWalletAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); fileMenu.add(menuItem); fileMenu.addSeparator(); // See if user has enabled the delete wallet action String showDeleteWalletString = this.bitcoinController.getModel().getUserPreference(BitcoinModel.SHOW_DELETE_WALLET); if (Boolean.TRUE.toString().equalsIgnoreCase(showDeleteWalletString)) { DeleteWalletAction deleteWalletAction = new DeleteWalletAction(this.bitcoinController, ImageLoader.createImageIcon(ImageLoader.DELETE_WALLET_ICON_FILE), this); menuItem = new JMenuItem(deleteWalletAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); fileMenu.add(menuItem); fileMenu.addSeparator(); } // Add password action. addPasswordAction = new MultiBitWalletBusyAction(this.bitcoinController, ImageLoader.ADD_PASSWORD_ICON_FILE, "addPasswordAction.text", "addPasswordAction.tooltip", "addPasswordAction.mnemonic", View.ADD_PASSWORD_VIEW); menuItem = new JMenuItem(addPasswordAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); fileMenu.add(menuItem); // Change password action. changePasswordAction = new MultiBitWalletBusyAction(this.bitcoinController, ImageLoader.CHANGE_PASSWORD_ICON_FILE, "changePasswordAction.text", "changePasswordAction.tooltip", "changePasswordAction.mnemonic", View.CHANGE_PASSWORD_VIEW); menuItem = new JMenuItem(changePasswordAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); fileMenu.add(menuItem); // Remove password action. removePasswordAction = new MultiBitWalletBusyAction(this.bitcoinController, ImageLoader.REMOVE_PASSWORD_ICON_FILE, "removePasswordAction.text", "removePasswordAction.tooltip", "removePasswordAction.mnemonic", View.REMOVE_PASSWORD_VIEW); menuItem = new JMenuItem(removePasswordAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); fileMenu.add(menuItem); // Exit action. if (application != null && !application.isMac()) { // Non Macs have an Exit Menu item. fileMenu.addSeparator(); { AbstractAction exitAction = new AbstractExitAction(this.controller) { @Override public void actionPerformed(ActionEvent e) { quitEventListener.onQuitEvent(null, multiBitFrameQuitResponse); } }; menuItem = new JMenuItem(exitAction); } menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); fileMenu.add(menuItem); } // Show welcome action. MultiBitAction showWelcomeAction = new MultiBitAction(controller, ImageLoader.WELCOME_ICON_FILE, "welcomePanel.text", "welcomePanel.title", "welcomePanel.mnemonic", View.WELCOME_VIEW); menuItem = new JMenuItem(showWelcomeAction); showWelcomeAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("welcomePanel.title"))); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); helpMenu.add(menuItem); MultiBitAction showHelpContentsAction; if (ComponentOrientation.LEFT_TO_RIGHT == ComponentOrientation.getOrientation(controller.getLocaliser().getLocale())) { showHelpContentsAction = new MultiBitAction(controller, ImageLoader.HELP_CONTENTS_ICON_FILE, "showHelpContentsAction.text", "showHelpContentsAction.tooltip", "showHelpContentsAction.mnemonic", View.HELP_CONTENTS_VIEW); } else { showHelpContentsAction = new MultiBitAction(controller, ImageLoader.HELP_CONTENTS_RTL_ICON_FILE, "showHelpContentsAction.text", "showHelpContentsAction.tooltip", "showHelpContentsAction.mnemonic", View.HELP_CONTENTS_VIEW); } showHelpContentsAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("showHelpContentsAction.tooltip"))); menuItem = new JMenuItem(showHelpContentsAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); helpMenu.add(menuItem); if (application != null && !application.isMac()) { // Non Macs have a Help About menu item. MultiBitAction helpAboutAction = new MultiBitAction(controller, ImageLoader.MULTIBIT_SMALL_ICON_FILE, "helpAboutAction.text", "helpAboutAction.tooltip", "helpAboutAction.mnemonic", View.HELP_ABOUT_VIEW); helpAboutAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("helpAboutAction.tooltip"))); menuItem = new JMenuItem(helpAboutAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); helpMenu.add(menuItem); } // View Transactions action. MultiBitAction showTransactionsAction = new MultiBitAction(controller, ImageLoader.TRANSACTIONS_ICON_FILE, "showTransactionsAction.text", "showTransactionsAction.tooltip", "showTransactionsAction.mnemonic", View.TRANSACTIONS_VIEW); showTransactionsAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("showTransactionsAction.tooltip"))); menuItem = new JMenuItem(showTransactionsAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); viewMenu.add(menuItem); // View Charts action. MultiBitAction showChartsAction = new MultiBitAction(controller, ImageLoader.CHART_LINE_ICON_FILE, "chartsPanelAction.text", "chartsPanelAction.tooltip", "chartsPanelAction.mnemonic", View.CHARTS_VIEW); showChartsAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("chartsPanelAction.tooltip"))); menuItem = new JMenuItem(showChartsAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); viewMenu.add(menuItem); // Show messages action. MultiBitAction showMessagesAction = new MultiBitAction(controller, ImageLoader.MESSAGES_ICON_FILE, "messagesPanel.text", "messagesPanel.tooltip", "messagesPanel.mnemonic", View.MESSAGES_VIEW); showMessagesAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("messagesPanel.tooltip"))); menuItem = new JMenuItem(showMessagesAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); viewMenu.add(menuItem); // Send bitcoin action. MultiBitAction sendBitcoinAction = new MultiBitAction(controller, ImageLoader.SEND_BITCOIN_ICON_FILE, "sendBitcoinAction.text", "sendBitcoinAction.tooltip", "sendBitcoinAction.mnemonic", View.SEND_BITCOIN_VIEW); sendBitcoinAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("sendBitcoinAction.tooltip"))); menuItem = new JMenuItem(sendBitcoinAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); tradeMenu.add(menuItem); MultiBitAction receiveBitcoinAction = new MultiBitAction(controller, ImageLoader.RECEIVE_BITCOIN_ICON_FILE, "receiveBitcoinAction.text", "receiveBitcoinAction.tooltip", "receiveBitcoinAction.mnemonic", View.RECEIVE_BITCOIN_VIEW); receiveBitcoinAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("receiveBitcoinAction.tooltip"))); menuItem = new JMenuItem(receiveBitcoinAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); tradeMenu.add(menuItem); // Show preferences. if (application != null && !application.isMac()) { // Non Macs have a Preferences menu item. MultiBitAction showPreferencesAction = new MultiBitAction(controller, ImageLoader.PREFERENCES_ICON_FILE, "showPreferencesAction.text", "showPreferencesAction.tooltip", "showPreferencesAction.mnemonic", View.PREFERENCES_VIEW); showPreferencesAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("showPreferencesAction.tooltip"))); menuItem = new JMenuItem(showPreferencesAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); viewMenu.add(menuItem); } viewMenu.addSeparator(); // Show ticker. String viewTicker = controller.getModel().getUserPreference(ExchangeModel.TICKER_SHOW); boolean isTickerVisible = !Boolean.FALSE.toString().equals(viewTicker); String tickerKey; if (isTickerVisible) { tickerKey = "multiBitFrame.ticker.hide.text"; } else { tickerKey = "multiBitFrame.ticker.show.text"; } final JMenuItem showTicker = new JMenuItem(controller.getLocaliser().getString(tickerKey)); showTicker.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); showTicker.setComponentOrientation(componentOrientation); showTicker.setIcon(ImageLoader.createImageIcon(ImageLoader.MONEY_ICON_FILE)); if (tickerTablePanel != null) { tickerTablePanel.setVisible(isTickerVisible); } final MultiBitFrame thisFrame = this; showTicker.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { if (tickerTablePanel != null) { if (tickerTablePanel.isVisible()) { tickerTablePanel.setVisible(false); controller.getModel().setUserPreference(ExchangeModel.TICKER_SHOW, Boolean.FALSE.toString()); showTicker.setText(controller.getLocaliser().getString("multiBitFrame.ticker.show.text")); } else { tickerTablePanel.setVisible(true); controller.getModel().setUserPreference(ExchangeModel.TICKER_SHOW, Boolean.TRUE.toString()); showTicker.setText(controller.getLocaliser().getString("multiBitFrame.ticker.hide.text")); // Cancel any existing timer. if (tickerTimer1 != null) { tickerTimer1.cancel(); } if (tickerTimer2 != null) { tickerTimer2.cancel(); } // Start ticker timer. tickerTimer1 = new Timer(); tickerTimer1.schedule(new TickerTimerTask(exchangeController, thisFrame, true), 0, TickerTimerTask.DEFAULT_REPEAT_RATE); boolean showSecondRow = Boolean.TRUE.toString().equals( controller.getModel().getUserPreference(ExchangeModel.TICKER_SHOW_SECOND_ROW)); if (showSecondRow) { tickerTimer2 = new Timer(); tickerTimer2.schedule(new TickerTimerTask(exchangeController, thisFrame, false), TickerTimerTask.TASK_SEPARATION, TickerTimerTask.DEFAULT_REPEAT_RATE); } } } } }); viewMenu.add(showTicker); // Sign message. signMessageAction = new MultiBitWalletBusyAction(this.bitcoinController, ImageLoader.MESSAGE_SIGN_ICON_FILE, "signMessageAction.text", "signMessageAction.tooltip", "signMessageAction.mnemonic", View.SIGN_MESSAGE_VIEW); menuItem = new JMenuItem(signMessageAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); toolsMenu.add(menuItem); // Verify message. MultiBitAction verifyMessageAction = new MultiBitAction(this.bitcoinController, ImageLoader.MESSAGE_VERIFY_ICON_FILE, "verifyMessageAction.text", "verifyMessageAction.tooltip", "verifyMessageAction.mnemonic", View.VERIFY_MESSAGE_VIEW); + verifyMessageAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("verifyMessageAction.tooltip"))); menuItem = new JMenuItem(verifyMessageAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); toolsMenu.add(menuItem); toolsMenu.addSeparator(); // Import private keys. showImportPrivateKeysAction = new MultiBitWalletBusyAction(this.bitcoinController, ImageLoader.IMPORT_PRIVATE_KEYS_ICON_FILE, "showImportPrivateKeysAction.text", "showImportPrivateKeysAction.tooltip", "showImportPrivateKeysAction.mnemonic", View.SHOW_IMPORT_PRIVATE_KEYS_VIEW); menuItem = new JMenuItem(showImportPrivateKeysAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); toolsMenu.add(menuItem); // Export private keys. showExportPrivateKeysAction = new MultiBitWalletBusyAction(this.bitcoinController, ImageLoader.EXPORT_PRIVATE_KEYS_ICON_FILE, "showExportPrivateKeysAction.text", "showExportPrivateKeysAction.tooltip", "showExportPrivateKeysAction.mnemonic", View.SHOW_EXPORT_PRIVATE_KEYS_VIEW); menuItem = new JMenuItem(showExportPrivateKeysAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); toolsMenu.add(menuItem); toolsMenu.addSeparator(); resetTransactionsAction = new MultiBitWalletBusyAction(this.bitcoinController, ImageLoader.RESET_TRANSACTIONS_ICON_FILE, "resetTransactionsAction.text", "resetTransactionsAction.tooltip", "resetTransactionsAction.mnemonic", View.RESET_TRANSACTIONS_VIEW); resetTransactionsAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("resetTransactionsAction.tooltip"))); menuItem = new JMenuItem(resetTransactionsAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); toolsMenu.add(menuItem); setJMenuBar(menuBar); return; } /** * Recreate all views. */ @Override public void recreateAllViews(final boolean initUI, final View initialView) { // if initUI set, do an invokeLater or else it can sometimes leave the menu items in the Mac header row. if (EventQueue.isDispatchThread() && !initUI) { recreateAllViewsOnSwingThread(initUI, initialView); } else { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { recreateAllViewsOnSwingThread(initUI, initialView); } }); } } private void recreateAllViewsOnSwingThread(final boolean initUI, View initialView) { ColorAndFontConstants.init(); // Close down current view. if (controller.getCurrentView() != View.UNKNOWN_VIEW) { navigateAwayFromView(controller.getCurrentView()); } if (initUI) { // Remember and replay task and remove any listeners. List<WalletData> replayPerWalletModelDataList = null; if (ReplayManager.INSTANCE.getCurrentReplayTask() != null) { replayPerWalletModelDataList = ReplayManager.INSTANCE.getCurrentReplayTask().getPerWalletModelDataToReplay(); } ReplayManager.INSTANCE.removeDownloadListeners(replayPerWalletModelDataList); // Remove the WalletBusyListeners. this.bitcoinController.logNumberOfWalletBusyListeners(); this.bitcoinController.clearWalletBusyListeners(); this.localiser = controller.getLocaliser(); Container contentPane = getContentPane(); viewFactory.initialise(); contentPane.removeAll(); viewTabbedPane.removeAllTabs(); initUI(null); // TODO check task is still running by taskid. if (replayPerWalletModelDataList != null) { ReplayManager.INSTANCE.addDownloadListeners(replayPerWalletModelDataList); } if (initialView != null && !(initialView == View.TRANSACTIONS_VIEW) && !(initialView == View.SEND_BITCOIN_VIEW) && !(initialView == View.RECEIVE_BITCOIN_VIEW)) { JPanel currentTabPanel = new JPanel(new BorderLayout()); Viewable currentView = viewFactory.getView(initialView); currentTabPanel.add((JPanel) currentView, BorderLayout.CENTER); viewTabbedPane.addTab(currentView.getViewTitle(), currentView.getViewIcon(), currentView.getViewTooltip(), currentTabPanel, true); } try { applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale())); } catch (ClassCastException cce) { // Look and feel exception - ignore. } } statusBar.refreshOnlineStatusText(); updateHeader(); // Tell the wallets list to display. if (walletsView != null) { walletsView.displayView(DisplayHint.COMPLETE_REDRAW); } if (tickerTablePanel != null) { tickerTablePanel.update(); } // Tell all the tabs in the tabbedPane to update. if (viewTabbedPane != null) { for (int i = 0; i < viewTabbedPane.getTabCount(); i++) { JPanel tabComponent = (JPanel) viewTabbedPane.getComponentAt(i); Component[] components = tabComponent.getComponents(); if (components != null && components.length > 0 && components[0] instanceof Viewable) { Viewable loopView = ((Viewable) components[0]); loopView.displayView(DisplayHint.COMPLETE_REDRAW); if (initialView != null && loopView.getViewId().toString().equals(initialView.toString())) { viewTabbedPane.setSelectedIndex(i); } } } } this.bitcoinController.logNumberOfWalletBusyListeners(); } /** * Display next view. */ @Override public void displayView(View viewToDisplay) { log.debug("Displaying view '" + viewToDisplay + "'"); // Open wallet view obselete - show transactions if (View.OPEN_WALLET_VIEW == viewToDisplay) { viewToDisplay = View.TRANSACTIONS_VIEW; } // Create Bulk addreses obselete - show transactions if (View.CREATE_BULK_ADDRESSES_VIEW == viewToDisplay) { viewToDisplay = View.TRANSACTIONS_VIEW; } // Show wallets view always on display. if (View.YOUR_WALLETS_VIEW == viewToDisplay) { walletsView.displayView(DisplayHint.COMPLETE_REDRAW); return; } controller.setCurrentView(viewToDisplay); final Viewable nextViewFinal = viewFactory.getView(viewToDisplay); if (nextViewFinal == null) { log.debug("Cannot display view " + viewToDisplay); return; } if (EventQueue.isDispatchThread()) { displayViewOnSwingThread(nextViewFinal); } else { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { displayViewOnSwingThread(nextViewFinal); } }); } } private void displayViewOnSwingThread(final Viewable nextViewFinal) { String viewName = nextViewFinal.getViewId().toString(); boolean foundTab = false; if (viewTabbedPane.getTabCount() > 0) { //log.debug("viewTabbedPane " + System.identityHashCode(viewTabbedPane) + " initally has " + viewTabbedPane.getTabCount() + " tabs."); for (int i = 0; i < viewTabbedPane.getTabCount(); i++) { JPanel tabComponent = (JPanel) viewTabbedPane.getComponentAt(i); if (tabComponent != null) { Component[] childComponents = tabComponent.getComponents(); String tabName = null; if (childComponents != null && childComponents.length > 0 && childComponents[0] instanceof Viewable) { tabName= ((Viewable) childComponents[0]).getViewId().toString(); } if (viewName != null && viewName.equals(tabName)) { foundTab = true; ((JPanel) viewTabbedPane.getComponentAt(i)).removeAll(); ((JPanel) viewTabbedPane.getComponentAt(i)).add((JPanel) nextViewFinal); viewTabbedPane.setSelectedIndex(i); break; } } } } if (!foundTab && nextViewFinal instanceof JPanel) { JPanel tabOutlinePanel = new JPanel(new BorderLayout()); tabOutlinePanel.add((JPanel) nextViewFinal, BorderLayout.CENTER); viewTabbedPane.addTab(nextViewFinal.getViewTitle(), nextViewFinal.getViewIcon(), nextViewFinal.getViewTooltip(), tabOutlinePanel, true); viewTabbedPane.setSelectedComponent(tabOutlinePanel); } nextViewFinal.displayView(DisplayHint.COMPLETE_REDRAW); //log.debug("viewTabbedPane " + System.identityHashCode(viewTabbedPane) + " finally has " + viewTabbedPane.getTabCount() + " tabs."); this.setCursor(Cursor.getDefaultCursor()); } /** * Navigate away from view - this may be on another thread hence the * SwingUtilities.invokeLater. */ @Override public void navigateAwayFromView(View viewToNavigateAwayFrom) { if (View.YOUR_WALLETS_VIEW == viewToNavigateAwayFrom) { // Do nothing return; } final Viewable viewToNavigateAwayFromFinal = viewFactory.getView(viewToNavigateAwayFrom); if (viewToNavigateAwayFromFinal != null) { if (EventQueue.isDispatchThread()) { viewToNavigateAwayFromFinal.navigateAwayFromView(); } else { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { viewToNavigateAwayFromFinal.navigateAwayFromView(); } }); } } } @Override public void setOnlineStatus(StatusEnum statusEnum) { online = statusEnum; if (statusBar != null) { statusBar.updateOnlineStatusText(statusEnum); } } @Override public void walletBusyChange(boolean newWalletIsBusy) { if (EventQueue.isDispatchThread()) { updateMenuItemsOnWalletChange(); } else { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { updateMenuItemsOnWalletChange(); } }); } } private void updateMenuItemsOnWalletChange() { signMessageAction.setEnabled(!this.bitcoinController.getModel().getActivePerWalletModelData().isBusy()); showImportPrivateKeysAction.setEnabled(!this.bitcoinController.getModel().getActivePerWalletModelData().isBusy()); showExportPrivateKeysAction.setEnabled(!this.bitcoinController.getModel().getActivePerWalletModelData().isBusy()); resetTransactionsAction.setEnabled(!this.bitcoinController.getModel().getActivePerWalletModelData().isBusy()); if (this.bitcoinController.getModel().getActiveWallet() == null) { // Cannot do anything password related. addPasswordAction.setEnabled(false); changePasswordAction.setEnabled(false); removePasswordAction.setEnabled(false); } else { if (this.bitcoinController.getModel().getActivePerWalletModelData().isBusy()) { addPasswordAction.setEnabled(false); changePasswordAction.setEnabled(false); removePasswordAction.setEnabled(false); } else { if (this.bitcoinController.getModel().getActiveWallet().getEncryptionType() == EncryptionType.ENCRYPTED_SCRYPT_AES) { addPasswordAction.setEnabled(false); changePasswordAction.setEnabled(true); removePasswordAction.setEnabled(true); } else { if (this.bitcoinController.getModel().getActiveWalletWalletInfo() == null || this.bitcoinController.getModel().getActiveWalletWalletInfo().getWalletVersion() == MultiBitWalletVersion.SERIALIZED) { addPasswordAction.setEnabled(false); } else { addPasswordAction.setEnabled(true); } changePasswordAction.setEnabled(false); removePasswordAction.setEnabled(false); } } } if (this.bitcoinController.getModel().getActivePerWalletModelData().isBusy()) { String walletIsBusyText = HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("multiBitSubmitAction.walletIsBusy", new Object[]{controller.getLocaliser().getString(this.bitcoinController.getModel().getActivePerWalletModelData().getBusyTaskKey())})); signMessageAction.putValue(Action.SHORT_DESCRIPTION, walletIsBusyText); showImportPrivateKeysAction.putValue(Action.SHORT_DESCRIPTION, walletIsBusyText); showExportPrivateKeysAction.putValue(Action.SHORT_DESCRIPTION, walletIsBusyText); resetTransactionsAction.putValue(Action.SHORT_DESCRIPTION, walletIsBusyText); addPasswordAction.putValue(Action.SHORT_DESCRIPTION, walletIsBusyText); changePasswordAction.putValue(Action.SHORT_DESCRIPTION, walletIsBusyText); removePasswordAction.putValue(Action.SHORT_DESCRIPTION, walletIsBusyText); } else { signMessageAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("signMessageAction.tooltip"))); showImportPrivateKeysAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("showImportPrivateKeysAction.tooltip"))); showExportPrivateKeysAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("showExportPrivateKeysAction.tooltip"))); resetTransactionsAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("resetTransactionsAction.tooltip"))); addPasswordAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("addPasswordAction.tooltip"))); changePasswordAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("changePasswordAction.tooltip"))); removePasswordAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("removePasswordAction.tooltip"))); } } @Override /** * Update due to a block being downloaded. * This typically comes in from a Peer. */ public void blockDownloaded() { // Update transaction screen in case status icons have changed. if (View.TRANSACTIONS_VIEW == controller.getCurrentView()) { ShowTransactionsPanel.updateTransactions(); } } @Override public void onCoinsReceived(Wallet wallet, Transaction transaction, BigInteger prevBalance, BigInteger newBalance) { fireDataChangedUpdateLater(DisplayHint.WALLET_TRANSACTIONS_HAVE_CHANGED); } @Override public void onCoinsSent(Wallet wallet, Transaction transaction, BigInteger prevBalance, BigInteger newBalance) { fireDataChangedUpdateLater(DisplayHint.WALLET_TRANSACTIONS_HAVE_CHANGED); } /** * One of the wallets has been reorganised due to a block chain reorganise */ @Override public void onReorganize(Wallet wallet) { log.info("Wallet has been reorganised."); recreateAllViews(false, controller.getCurrentView()); } @Override public void onTransactionConfidenceChanged(Wallet wallet, Transaction transaction) { if (controller.getCurrentView() == View.TRANSACTIONS_VIEW) { ShowTransactionsPanel.updateTransactions(); } else if (controller.getCurrentView() == View.SEND_BITCOIN_VIEW) { final int numberOfPeers = (transaction == null || transaction.getConfidence() == null) ? 0 : transaction.getConfidence().getBroadcastByCount(); //log.debug("numberOfPeers = " + numberOfPeers); final Sha256Hash transactionHash = (transaction == null) ? null : transaction.getHash(); //log.debug((transaction != null && transaction.getConfidence() != null) ? transaction.getConfidence().toString() : "No transaction confidence for tx"); SendBitcoinConfirmPanel.updatePanelDueToTransactionConfidenceChange(transactionHash, numberOfPeers); } } @Override public void fireFilesHaveBeenChangedByAnotherProcess(WalletData perWalletModelData) { if (this.bitcoinController.getModel().getActiveWalletFilename() != null && this.bitcoinController.getModel().getActiveWalletFilename().equals(perWalletModelData.getWalletFilename())) { Message message = new Message(HelpContentsPanel.createTooltipText(controller.getLocaliser().getString("singleWalletPanel.dataHasChanged.tooltip.1") + " " + controller.getLocaliser().getString("singleWalletPanel.dataHasChanged.tooltip.2")), true); MessageManager.INSTANCE.addMessage(message); } fireDataChangedUpdateNow(DisplayHint.COMPLETE_REDRAW); } /** * Mark that the UI needs to be updated as soon as possible. */ @Override public void fireDataChangedUpdateNow(final DisplayHint displayHint) { if (EventQueue.isDispatchThread()) { fireDataChangedOnSwingThread(displayHint); } else { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { fireDataChangedOnSwingThread(displayHint); } }); } } /** * Mark that the UI needs updating the next time the fireDataChangedTimer fires. */ @Override public void fireDataChangedUpdateLater(DisplayHint displayHint) { if (fireDataChangedTimerTask != null) { fireDataChangedTimerTask.setFireDataChanged(true); } } /** * Actually update the UI. * (Called back from the FireDataChangedTimerTask). */ private void fireDataChangedOnSwingThread(DisplayHint displayHint) { updateHeader(); // Update the password related menu items. updateMenuItemsOnWalletChange(); // Tell the wallets list to display. if (walletsView != null) { walletsView.displayView(displayHint); } // Tell the current view to update itself. Viewable currentViewView = viewFactory.getView(controller.getCurrentView()); if (currentViewView != null) { currentViewView.displayView(displayHint); } } /** * Update the Ticker Panel after the exchange data has changed. */ public void fireExchangeDataChanged() { updateHeader(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { tickerTablePanel.update(); } }); } public void updateHeader(final String syncMessage, final double syncPercent) { final boolean filesHaveBeenChangeByAnotherProcess = this.bitcoinController.getModel().getActivePerWalletModelData() != null && this.bitcoinController.getModel().getActivePerWalletModelData().isFilesHaveBeenChangedByAnotherProcess(); final boolean isBusy = this.bitcoinController.getModel().getActivePerWalletModelData().isBusy(); if (EventQueue.isDispatchThread()) { updateHeaderOnSwingThread(filesHaveBeenChangeByAnotherProcess, null, null, isBusy, syncMessage, syncPercent); } else { SwingUtilities.invokeLater(new Runnable() { public void run() { updateHeaderOnSwingThread(filesHaveBeenChangeByAnotherProcess, null, null, isBusy, syncMessage, syncPercent); } }); } } public void updateHeader() { final BigInteger finalEstimatedBalance = this.bitcoinController.getModel().getActiveWalletEstimatedBalance(); final BigInteger finalAvailableToSpend = this.bitcoinController.getModel().getActiveWalletAvailableBalance(); final boolean filesHaveBeenChangeByAnotherProcess = this.bitcoinController.getModel().getActivePerWalletModelData() != null && this.bitcoinController.getModel().getActivePerWalletModelData().isFilesHaveBeenChangedByAnotherProcess(); final boolean isBusy = this.bitcoinController.getModel().getActivePerWalletModelData().isBusy(); if (EventQueue.isDispatchThread()) { updateHeaderOnSwingThread(filesHaveBeenChangeByAnotherProcess, finalEstimatedBalance, finalAvailableToSpend, isBusy, null, -1); } else { SwingUtilities.invokeLater(new Runnable() { public void run() { updateHeaderOnSwingThread(filesHaveBeenChangeByAnotherProcess, finalEstimatedBalance, finalAvailableToSpend, isBusy, null, -1); } }); } } private void updateHeaderOnSwingThread(final boolean filesHaveBeenChangedByAnotherProcess, final BigInteger estimatedBalance, final BigInteger availableToSpend, final boolean isBusy, final String syncMessage, final double syncPercent) { if (filesHaveBeenChangedByAnotherProcess) { // Files have been changed by another process - blank totals // and put 'Updates stopped' message. estimatedBalanceLabelLabel.setText(controller.getLocaliser().getString("singleWalletPanel.dataHasChanged.text")); estimatedBalanceBTCLabel.setText(" "); estimatedBalanceFiatLabel.setText(" "); setUpdatesStoppedTooltip(estimatedBalanceLabelLabel); availableBalanceLabelButton.setText(" "); availableBalanceBTCButton.setText(" "); availableBalanceFiatButton.setText(" "); } else { if (isBusy) { estimatedBalanceLabelLabel.setText(" "); estimatedBalanceLabelLabel.setToolTipText(null); if (syncMessage != null && !syncMessage.isEmpty()) { estimatedBalanceBTCLabel.setText(syncMessage); estimatedBalanceBTCLabel.setToolTipText(syncMessage); } if (syncPercent > -1) { estimatedBalanceFiatLabel.setText("(" + (int) syncPercent + "%)"); estimatedBalanceFiatLabel.setToolTipText(syncMessage); } else if (syncPercent == 0 || (syncMessage != null && !syncMessage.isEmpty())) { estimatedBalanceFiatLabel.setText(" "); estimatedBalanceFiatLabel.setToolTipText(null); } else { estimatedBalanceFiatLabel.setToolTipText(null); } availableBalanceBTCButton.setText(" "); availableBalanceFiatButton.setText(" "); availableBalanceLabelButton.setEnabled(false); availableBalanceBTCButton.setEnabled(false); availableBalanceFiatButton.setEnabled(false); availableBalanceLabelButton.setVisible(false); availableBalanceBTCButton.setVisible(false); availableBalanceFiatButton.setVisible(false); } else { estimatedBalanceLabelLabel.setText(controller.getLocaliser().getString("multiBitFrame.balanceLabel")); estimatedBalanceLabelLabel.setToolTipText(controller.getLocaliser().getString("multiBitFrame.balanceLabel.tooltip")); estimatedBalanceBTCLabel.setText(controller.getLocaliser().bitcoinValueToString(estimatedBalance, true, false)); estimatedBalanceBTCLabel.setToolTipText(controller.getLocaliser().getString("multiBitFrame.balanceLabel.tooltip")); estimatedBalanceFiatLabel.setToolTipText(controller.getLocaliser().getString("multiBitFrame.balanceLabel.tooltip")); if (CurrencyConverter.INSTANCE.getRate() != null && CurrencyConverter.INSTANCE.isShowingFiat()) { Money fiat = CurrencyConverter.INSTANCE.convertFromBTCToFiat(estimatedBalance); estimatedBalanceFiatLabel.setText("(" + CurrencyConverter.INSTANCE.getFiatAsLocalisedString(fiat) + ")"); } else { estimatedBalanceFiatLabel.setText(" "); } if (availableToSpend != null && availableToSpend.equals(estimatedBalance)) { availableBalanceBTCButton.setText(" "); availableBalanceFiatButton.setText(" "); availableBalanceLabelButton.setEnabled(false); availableBalanceBTCButton.setEnabled(false); availableBalanceFiatButton.setEnabled(false); availableBalanceLabelButton.setVisible(false); availableBalanceBTCButton.setVisible(false); availableBalanceFiatButton.setVisible(false); } else { availableBalanceBTCButton .setText(controller.getLocaliser().bitcoinValueToString(availableToSpend, true, false)); if (CurrencyConverter.INSTANCE.getRate() != null && CurrencyConverter.INSTANCE.isShowingFiat()) { Money fiat = CurrencyConverter.INSTANCE.convertFromBTCToFiat(availableToSpend); if (fiat != null) { availableBalanceFiatButton.setText("(" + CurrencyConverter.INSTANCE.getFiatAsLocalisedString(fiat) + ")"); } } else { availableBalanceFiatButton.setText(" "); } availableBalanceLabelButton.setEnabled(true); availableBalanceBTCButton.setEnabled(true); availableBalanceFiatButton.setEnabled(true); availableBalanceLabelButton.setVisible(true); availableBalanceBTCButton.setVisible(true); availableBalanceFiatButton.setVisible(true); } } String titleText = localiser.getString("multiBitFrame.title"); if (this.bitcoinController.getModel().getActiveWallet() != null) { titleText = titleText + SEPARATOR + this.bitcoinController.getModel().getActivePerWalletModelData().getWalletDescription() + SEPARATOR + this.bitcoinController.getModel().getActivePerWalletModelData().getWalletFilename(); } setTitle(titleText); } } // Macify application methods. @Override @Deprecated public void handleAbout(ApplicationEvent event) { controller.displayView(View.HELP_ABOUT_VIEW); event.setHandled(true); } @Override @Deprecated public void handleOpenApplication(ApplicationEvent event) { // Ok, we know our application started. // Not much to do about that.. } @Override @Deprecated public void handleOpenFile(ApplicationEvent event) { // TODO i18n required. JOptionPane.showMessageDialog(this, "Sorry, opening of files with double click is not yet implemented. Wallet was " + event.getFilename()); } @Override @Deprecated public void handlePreferences(ApplicationEvent event) { controller.displayView(View.PREFERENCES_VIEW); } @Override @Deprecated public void handlePrintFile(ApplicationEvent event) { // TODO i18n required. JOptionPane.showMessageDialog(this, "Sorry, printing not implemented"); } @Override @Deprecated public void handleQuit(ApplicationEvent event) { throw new UnsupportedOperationException("Deprecated."); } @Override public void handleReOpenApplication(ApplicationEvent event) { setVisible(true); } public void setUpdatesStoppedTooltip(JComponent component) { // Multiline tool tip text. String toolTipText = "<html><font face=\"sansserif\">"; toolTipText = toolTipText + controller.getLocaliser().getString("singleWalletPanel.dataHasChanged.tooltip.1") + "<br>"; toolTipText = toolTipText + controller.getLocaliser().getString("singleWalletPanel.dataHasChanged.tooltip.2") + "<br>"; toolTipText = toolTipText + "</font></html>"; component.setToolTipText(toolTipText); } public void bringToFront() { java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { toFront(); repaint(); } }); } public void calculateDividerPosition() { int dividerPosition = SingleWalletPanel.calculateNormalWidth((JComponent) (walletsView)) + WALLET_WIDTH_DELTA; if (((WalletListPanel) walletsView).getScrollPane().getVerticalScrollBar().isVisible()) { dividerPosition += SCROLL_BAR_DELTA; } if (walletsView != null && walletsView.getPreferredSize() != null && walletsView.getPreferredSize().width > dividerPosition) { dividerPosition = walletsView.getPreferredSize().width; } if (ComponentOrientation.RIGHT_TO_LEFT == ComponentOrientation.getOrientation(controller.getLocaliser().getLocale())) { int width = getWidth(); if (width == 0) { width = (int) this.getPreferredSize().getWidth(); } dividerPosition = width - dividerPosition; // - WalletListPanel.LEFT_BORDER - WalletListPanel.RIGHT_BORDER - 2; } splitPane.setEnabled(true); splitPane.setDividerLocation(dividerPosition); splitPane.setEnabled(ComponentOrientation.LEFT_TO_RIGHT.equals(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()))); } public WalletListPanel getWalletsView() { return walletsView; } public void onDeadTransaction(Wallet wallet, Transaction deadTx, Transaction replacementTx) { } @Override public void onKeyAdded(ECKey key) { } public JPanel getHeaderPanel() { return headerPanel; } public TickerTablePanel getTickerTablePanel() { return tickerTablePanel; } public JSplitPane getSplitPane() { return splitPane; } @Override public void onWalletChanged(Wallet wallet) { fireDataChangedUpdateNow(DisplayHint.WALLET_TRANSACTIONS_HAVE_CHANGED); } @Override public void lostExchangeRate(ExchangeRate exchangeRate) { updateHeader(); } @Override public void foundExchangeRate(ExchangeRate exchangeRate) { updateHeader(); } @Override public void updatedExchangeRate(ExchangeRate exchangeRate) { updateHeader(); } public Timer getTickerTimer1() { return tickerTimer1; } public void setTickerTimer1(Timer tickerTimer1) { this.tickerTimer1 = tickerTimer1; } public Timer getTickerTimer2() { return tickerTimer2; } public void setTickerTimer2(Timer tickerTimer2) { this.tickerTimer2 = tickerTimer2; } public TickerTimerTask getTickerTimerTask1() { return tickerTimerTask1; } public TickerTimerTask getTickerTimerTask2() { return tickerTimerTask2; } public void setTickerTimerTask1(TickerTimerTask tickerTimerTask1) { this.tickerTimerTask1 = tickerTimerTask1; } public void setTickerTimerTask2(TickerTimerTask tickerTimerTask2) { this.tickerTimerTask2 = tickerTimerTask2; } }
true
true
private void addMenuBar(GridBagConstraints constraints, Container contentPane) { ComponentOrientation componentOrientation = ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()); // Create the menu bar. JMenuBar menuBar = new JMenuBar(); menuBar.setComponentOrientation(componentOrientation); // Create the toolBar. JPanel toolBarPanel = new JPanel(); toolBarPanel.setOpaque(false); MnemonicUtil mnemonicUtil = new MnemonicUtil(controller.getLocaliser()); // Build the File menu. JMenu fileMenu = new JMenu(localiser.getString("multiBitFrame.fileMenuText")); fileMenu.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); fileMenu.setComponentOrientation(componentOrientation); fileMenu.setMnemonic(mnemonicUtil.getMnemonic("multiBitFrame.fileMenuMnemonic")); menuBar.add(fileMenu); // Build the Trade menu. JMenu tradeMenu = new JMenu(localiser.getString("multiBitFrame.tradeMenuText")); tradeMenu.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); tradeMenu.setComponentOrientation(componentOrientation); tradeMenu.setMnemonic(mnemonicUtil.getMnemonic("multiBitFrame.tradeMenuMnemonic")); menuBar.add(tradeMenu); // Build the View menu. JMenu viewMenu = new JMenu(localiser.getString("multiBitFrame.viewMenuText")); viewMenu.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); viewMenu.setComponentOrientation(componentOrientation); viewMenu.setMnemonic(mnemonicUtil.getMnemonic("multiBitFrame.viewMenuMnemonic")); menuBar.add(viewMenu); // Build the Tools menu. JMenu toolsMenu = new JMenu(localiser.getString("multiBitFrame.toolsMenuText")); toolsMenu.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); toolsMenu.setComponentOrientation(componentOrientation); toolsMenu.setMnemonic(mnemonicUtil.getMnemonic("multiBitFrame.toolsMenuMnemonic")); menuBar.add(toolsMenu); // Build the Help menu. JMenu helpMenu = new JMenu(localiser.getString("multiBitFrame.helpMenuText")); helpMenu.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); helpMenu.setComponentOrientation(componentOrientation); helpMenu.setMnemonic(mnemonicUtil.getMnemonic("multiBitFrame.helpMenuMnemonic")); menuBar.add(helpMenu); // Create new wallet action. CreateWalletSubmitAction createNewWalletAction = new CreateWalletSubmitAction(this.bitcoinController, ImageLoader.createImageIcon(ImageLoader.CREATE_NEW_ICON_FILE), this); JMenuItem menuItem = new JMenuItem(createNewWalletAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); fileMenu.add(menuItem); // Open wallet action. OpenWalletAction openWalletAction = new OpenWalletAction(this.bitcoinController, ImageLoader.createImageIcon(ImageLoader.OPEN_WALLET_ICON_FILE), this); menuItem = new JMenuItem(openWalletAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); fileMenu.add(menuItem); CloseWalletAction closeWalletAction = new CloseWalletAction(this.bitcoinController, ImageLoader.createImageIcon(ImageLoader.CLOSE_WALLET_ICON_FILE), this); menuItem = new JMenuItem(closeWalletAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); fileMenu.add(menuItem); fileMenu.addSeparator(); // See if user has enabled the delete wallet action String showDeleteWalletString = this.bitcoinController.getModel().getUserPreference(BitcoinModel.SHOW_DELETE_WALLET); if (Boolean.TRUE.toString().equalsIgnoreCase(showDeleteWalletString)) { DeleteWalletAction deleteWalletAction = new DeleteWalletAction(this.bitcoinController, ImageLoader.createImageIcon(ImageLoader.DELETE_WALLET_ICON_FILE), this); menuItem = new JMenuItem(deleteWalletAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); fileMenu.add(menuItem); fileMenu.addSeparator(); } // Add password action. addPasswordAction = new MultiBitWalletBusyAction(this.bitcoinController, ImageLoader.ADD_PASSWORD_ICON_FILE, "addPasswordAction.text", "addPasswordAction.tooltip", "addPasswordAction.mnemonic", View.ADD_PASSWORD_VIEW); menuItem = new JMenuItem(addPasswordAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); fileMenu.add(menuItem); // Change password action. changePasswordAction = new MultiBitWalletBusyAction(this.bitcoinController, ImageLoader.CHANGE_PASSWORD_ICON_FILE, "changePasswordAction.text", "changePasswordAction.tooltip", "changePasswordAction.mnemonic", View.CHANGE_PASSWORD_VIEW); menuItem = new JMenuItem(changePasswordAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); fileMenu.add(menuItem); // Remove password action. removePasswordAction = new MultiBitWalletBusyAction(this.bitcoinController, ImageLoader.REMOVE_PASSWORD_ICON_FILE, "removePasswordAction.text", "removePasswordAction.tooltip", "removePasswordAction.mnemonic", View.REMOVE_PASSWORD_VIEW); menuItem = new JMenuItem(removePasswordAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); fileMenu.add(menuItem); // Exit action. if (application != null && !application.isMac()) { // Non Macs have an Exit Menu item. fileMenu.addSeparator(); { AbstractAction exitAction = new AbstractExitAction(this.controller) { @Override public void actionPerformed(ActionEvent e) { quitEventListener.onQuitEvent(null, multiBitFrameQuitResponse); } }; menuItem = new JMenuItem(exitAction); } menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); fileMenu.add(menuItem); } // Show welcome action. MultiBitAction showWelcomeAction = new MultiBitAction(controller, ImageLoader.WELCOME_ICON_FILE, "welcomePanel.text", "welcomePanel.title", "welcomePanel.mnemonic", View.WELCOME_VIEW); menuItem = new JMenuItem(showWelcomeAction); showWelcomeAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("welcomePanel.title"))); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); helpMenu.add(menuItem); MultiBitAction showHelpContentsAction; if (ComponentOrientation.LEFT_TO_RIGHT == ComponentOrientation.getOrientation(controller.getLocaliser().getLocale())) { showHelpContentsAction = new MultiBitAction(controller, ImageLoader.HELP_CONTENTS_ICON_FILE, "showHelpContentsAction.text", "showHelpContentsAction.tooltip", "showHelpContentsAction.mnemonic", View.HELP_CONTENTS_VIEW); } else { showHelpContentsAction = new MultiBitAction(controller, ImageLoader.HELP_CONTENTS_RTL_ICON_FILE, "showHelpContentsAction.text", "showHelpContentsAction.tooltip", "showHelpContentsAction.mnemonic", View.HELP_CONTENTS_VIEW); } showHelpContentsAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("showHelpContentsAction.tooltip"))); menuItem = new JMenuItem(showHelpContentsAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); helpMenu.add(menuItem); if (application != null && !application.isMac()) { // Non Macs have a Help About menu item. MultiBitAction helpAboutAction = new MultiBitAction(controller, ImageLoader.MULTIBIT_SMALL_ICON_FILE, "helpAboutAction.text", "helpAboutAction.tooltip", "helpAboutAction.mnemonic", View.HELP_ABOUT_VIEW); helpAboutAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("helpAboutAction.tooltip"))); menuItem = new JMenuItem(helpAboutAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); helpMenu.add(menuItem); } // View Transactions action. MultiBitAction showTransactionsAction = new MultiBitAction(controller, ImageLoader.TRANSACTIONS_ICON_FILE, "showTransactionsAction.text", "showTransactionsAction.tooltip", "showTransactionsAction.mnemonic", View.TRANSACTIONS_VIEW); showTransactionsAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("showTransactionsAction.tooltip"))); menuItem = new JMenuItem(showTransactionsAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); viewMenu.add(menuItem); // View Charts action. MultiBitAction showChartsAction = new MultiBitAction(controller, ImageLoader.CHART_LINE_ICON_FILE, "chartsPanelAction.text", "chartsPanelAction.tooltip", "chartsPanelAction.mnemonic", View.CHARTS_VIEW); showChartsAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("chartsPanelAction.tooltip"))); menuItem = new JMenuItem(showChartsAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); viewMenu.add(menuItem); // Show messages action. MultiBitAction showMessagesAction = new MultiBitAction(controller, ImageLoader.MESSAGES_ICON_FILE, "messagesPanel.text", "messagesPanel.tooltip", "messagesPanel.mnemonic", View.MESSAGES_VIEW); showMessagesAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("messagesPanel.tooltip"))); menuItem = new JMenuItem(showMessagesAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); viewMenu.add(menuItem); // Send bitcoin action. MultiBitAction sendBitcoinAction = new MultiBitAction(controller, ImageLoader.SEND_BITCOIN_ICON_FILE, "sendBitcoinAction.text", "sendBitcoinAction.tooltip", "sendBitcoinAction.mnemonic", View.SEND_BITCOIN_VIEW); sendBitcoinAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("sendBitcoinAction.tooltip"))); menuItem = new JMenuItem(sendBitcoinAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); tradeMenu.add(menuItem); MultiBitAction receiveBitcoinAction = new MultiBitAction(controller, ImageLoader.RECEIVE_BITCOIN_ICON_FILE, "receiveBitcoinAction.text", "receiveBitcoinAction.tooltip", "receiveBitcoinAction.mnemonic", View.RECEIVE_BITCOIN_VIEW); receiveBitcoinAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("receiveBitcoinAction.tooltip"))); menuItem = new JMenuItem(receiveBitcoinAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); tradeMenu.add(menuItem); // Show preferences. if (application != null && !application.isMac()) { // Non Macs have a Preferences menu item. MultiBitAction showPreferencesAction = new MultiBitAction(controller, ImageLoader.PREFERENCES_ICON_FILE, "showPreferencesAction.text", "showPreferencesAction.tooltip", "showPreferencesAction.mnemonic", View.PREFERENCES_VIEW); showPreferencesAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("showPreferencesAction.tooltip"))); menuItem = new JMenuItem(showPreferencesAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); viewMenu.add(menuItem); } viewMenu.addSeparator(); // Show ticker. String viewTicker = controller.getModel().getUserPreference(ExchangeModel.TICKER_SHOW); boolean isTickerVisible = !Boolean.FALSE.toString().equals(viewTicker); String tickerKey; if (isTickerVisible) { tickerKey = "multiBitFrame.ticker.hide.text"; } else { tickerKey = "multiBitFrame.ticker.show.text"; } final JMenuItem showTicker = new JMenuItem(controller.getLocaliser().getString(tickerKey)); showTicker.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); showTicker.setComponentOrientation(componentOrientation); showTicker.setIcon(ImageLoader.createImageIcon(ImageLoader.MONEY_ICON_FILE)); if (tickerTablePanel != null) { tickerTablePanel.setVisible(isTickerVisible); } final MultiBitFrame thisFrame = this; showTicker.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { if (tickerTablePanel != null) { if (tickerTablePanel.isVisible()) { tickerTablePanel.setVisible(false); controller.getModel().setUserPreference(ExchangeModel.TICKER_SHOW, Boolean.FALSE.toString()); showTicker.setText(controller.getLocaliser().getString("multiBitFrame.ticker.show.text")); } else { tickerTablePanel.setVisible(true); controller.getModel().setUserPreference(ExchangeModel.TICKER_SHOW, Boolean.TRUE.toString()); showTicker.setText(controller.getLocaliser().getString("multiBitFrame.ticker.hide.text")); // Cancel any existing timer. if (tickerTimer1 != null) { tickerTimer1.cancel(); } if (tickerTimer2 != null) { tickerTimer2.cancel(); } // Start ticker timer. tickerTimer1 = new Timer(); tickerTimer1.schedule(new TickerTimerTask(exchangeController, thisFrame, true), 0, TickerTimerTask.DEFAULT_REPEAT_RATE); boolean showSecondRow = Boolean.TRUE.toString().equals( controller.getModel().getUserPreference(ExchangeModel.TICKER_SHOW_SECOND_ROW)); if (showSecondRow) { tickerTimer2 = new Timer(); tickerTimer2.schedule(new TickerTimerTask(exchangeController, thisFrame, false), TickerTimerTask.TASK_SEPARATION, TickerTimerTask.DEFAULT_REPEAT_RATE); } } } } }); viewMenu.add(showTicker); // Sign message. signMessageAction = new MultiBitWalletBusyAction(this.bitcoinController, ImageLoader.MESSAGE_SIGN_ICON_FILE, "signMessageAction.text", "signMessageAction.tooltip", "signMessageAction.mnemonic", View.SIGN_MESSAGE_VIEW); menuItem = new JMenuItem(signMessageAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); toolsMenu.add(menuItem); // Verify message. MultiBitAction verifyMessageAction = new MultiBitAction(this.bitcoinController, ImageLoader.MESSAGE_VERIFY_ICON_FILE, "verifyMessageAction.text", "verifyMessageAction.tooltip", "verifyMessageAction.mnemonic", View.VERIFY_MESSAGE_VIEW); menuItem = new JMenuItem(verifyMessageAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); toolsMenu.add(menuItem); toolsMenu.addSeparator(); // Import private keys. showImportPrivateKeysAction = new MultiBitWalletBusyAction(this.bitcoinController, ImageLoader.IMPORT_PRIVATE_KEYS_ICON_FILE, "showImportPrivateKeysAction.text", "showImportPrivateKeysAction.tooltip", "showImportPrivateKeysAction.mnemonic", View.SHOW_IMPORT_PRIVATE_KEYS_VIEW); menuItem = new JMenuItem(showImportPrivateKeysAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); toolsMenu.add(menuItem); // Export private keys. showExportPrivateKeysAction = new MultiBitWalletBusyAction(this.bitcoinController, ImageLoader.EXPORT_PRIVATE_KEYS_ICON_FILE, "showExportPrivateKeysAction.text", "showExportPrivateKeysAction.tooltip", "showExportPrivateKeysAction.mnemonic", View.SHOW_EXPORT_PRIVATE_KEYS_VIEW); menuItem = new JMenuItem(showExportPrivateKeysAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); toolsMenu.add(menuItem); toolsMenu.addSeparator(); resetTransactionsAction = new MultiBitWalletBusyAction(this.bitcoinController, ImageLoader.RESET_TRANSACTIONS_ICON_FILE, "resetTransactionsAction.text", "resetTransactionsAction.tooltip", "resetTransactionsAction.mnemonic", View.RESET_TRANSACTIONS_VIEW); resetTransactionsAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("resetTransactionsAction.tooltip"))); menuItem = new JMenuItem(resetTransactionsAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); toolsMenu.add(menuItem); setJMenuBar(menuBar); return; }
private void addMenuBar(GridBagConstraints constraints, Container contentPane) { ComponentOrientation componentOrientation = ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()); // Create the menu bar. JMenuBar menuBar = new JMenuBar(); menuBar.setComponentOrientation(componentOrientation); // Create the toolBar. JPanel toolBarPanel = new JPanel(); toolBarPanel.setOpaque(false); MnemonicUtil mnemonicUtil = new MnemonicUtil(controller.getLocaliser()); // Build the File menu. JMenu fileMenu = new JMenu(localiser.getString("multiBitFrame.fileMenuText")); fileMenu.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); fileMenu.setComponentOrientation(componentOrientation); fileMenu.setMnemonic(mnemonicUtil.getMnemonic("multiBitFrame.fileMenuMnemonic")); menuBar.add(fileMenu); // Build the Trade menu. JMenu tradeMenu = new JMenu(localiser.getString("multiBitFrame.tradeMenuText")); tradeMenu.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); tradeMenu.setComponentOrientation(componentOrientation); tradeMenu.setMnemonic(mnemonicUtil.getMnemonic("multiBitFrame.tradeMenuMnemonic")); menuBar.add(tradeMenu); // Build the View menu. JMenu viewMenu = new JMenu(localiser.getString("multiBitFrame.viewMenuText")); viewMenu.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); viewMenu.setComponentOrientation(componentOrientation); viewMenu.setMnemonic(mnemonicUtil.getMnemonic("multiBitFrame.viewMenuMnemonic")); menuBar.add(viewMenu); // Build the Tools menu. JMenu toolsMenu = new JMenu(localiser.getString("multiBitFrame.toolsMenuText")); toolsMenu.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); toolsMenu.setComponentOrientation(componentOrientation); toolsMenu.setMnemonic(mnemonicUtil.getMnemonic("multiBitFrame.toolsMenuMnemonic")); menuBar.add(toolsMenu); // Build the Help menu. JMenu helpMenu = new JMenu(localiser.getString("multiBitFrame.helpMenuText")); helpMenu.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); helpMenu.setComponentOrientation(componentOrientation); helpMenu.setMnemonic(mnemonicUtil.getMnemonic("multiBitFrame.helpMenuMnemonic")); menuBar.add(helpMenu); // Create new wallet action. CreateWalletSubmitAction createNewWalletAction = new CreateWalletSubmitAction(this.bitcoinController, ImageLoader.createImageIcon(ImageLoader.CREATE_NEW_ICON_FILE), this); JMenuItem menuItem = new JMenuItem(createNewWalletAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); fileMenu.add(menuItem); // Open wallet action. OpenWalletAction openWalletAction = new OpenWalletAction(this.bitcoinController, ImageLoader.createImageIcon(ImageLoader.OPEN_WALLET_ICON_FILE), this); menuItem = new JMenuItem(openWalletAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); fileMenu.add(menuItem); CloseWalletAction closeWalletAction = new CloseWalletAction(this.bitcoinController, ImageLoader.createImageIcon(ImageLoader.CLOSE_WALLET_ICON_FILE), this); menuItem = new JMenuItem(closeWalletAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); fileMenu.add(menuItem); fileMenu.addSeparator(); // See if user has enabled the delete wallet action String showDeleteWalletString = this.bitcoinController.getModel().getUserPreference(BitcoinModel.SHOW_DELETE_WALLET); if (Boolean.TRUE.toString().equalsIgnoreCase(showDeleteWalletString)) { DeleteWalletAction deleteWalletAction = new DeleteWalletAction(this.bitcoinController, ImageLoader.createImageIcon(ImageLoader.DELETE_WALLET_ICON_FILE), this); menuItem = new JMenuItem(deleteWalletAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); fileMenu.add(menuItem); fileMenu.addSeparator(); } // Add password action. addPasswordAction = new MultiBitWalletBusyAction(this.bitcoinController, ImageLoader.ADD_PASSWORD_ICON_FILE, "addPasswordAction.text", "addPasswordAction.tooltip", "addPasswordAction.mnemonic", View.ADD_PASSWORD_VIEW); menuItem = new JMenuItem(addPasswordAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); fileMenu.add(menuItem); // Change password action. changePasswordAction = new MultiBitWalletBusyAction(this.bitcoinController, ImageLoader.CHANGE_PASSWORD_ICON_FILE, "changePasswordAction.text", "changePasswordAction.tooltip", "changePasswordAction.mnemonic", View.CHANGE_PASSWORD_VIEW); menuItem = new JMenuItem(changePasswordAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); fileMenu.add(menuItem); // Remove password action. removePasswordAction = new MultiBitWalletBusyAction(this.bitcoinController, ImageLoader.REMOVE_PASSWORD_ICON_FILE, "removePasswordAction.text", "removePasswordAction.tooltip", "removePasswordAction.mnemonic", View.REMOVE_PASSWORD_VIEW); menuItem = new JMenuItem(removePasswordAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); fileMenu.add(menuItem); // Exit action. if (application != null && !application.isMac()) { // Non Macs have an Exit Menu item. fileMenu.addSeparator(); { AbstractAction exitAction = new AbstractExitAction(this.controller) { @Override public void actionPerformed(ActionEvent e) { quitEventListener.onQuitEvent(null, multiBitFrameQuitResponse); } }; menuItem = new JMenuItem(exitAction); } menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); fileMenu.add(menuItem); } // Show welcome action. MultiBitAction showWelcomeAction = new MultiBitAction(controller, ImageLoader.WELCOME_ICON_FILE, "welcomePanel.text", "welcomePanel.title", "welcomePanel.mnemonic", View.WELCOME_VIEW); menuItem = new JMenuItem(showWelcomeAction); showWelcomeAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("welcomePanel.title"))); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); helpMenu.add(menuItem); MultiBitAction showHelpContentsAction; if (ComponentOrientation.LEFT_TO_RIGHT == ComponentOrientation.getOrientation(controller.getLocaliser().getLocale())) { showHelpContentsAction = new MultiBitAction(controller, ImageLoader.HELP_CONTENTS_ICON_FILE, "showHelpContentsAction.text", "showHelpContentsAction.tooltip", "showHelpContentsAction.mnemonic", View.HELP_CONTENTS_VIEW); } else { showHelpContentsAction = new MultiBitAction(controller, ImageLoader.HELP_CONTENTS_RTL_ICON_FILE, "showHelpContentsAction.text", "showHelpContentsAction.tooltip", "showHelpContentsAction.mnemonic", View.HELP_CONTENTS_VIEW); } showHelpContentsAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("showHelpContentsAction.tooltip"))); menuItem = new JMenuItem(showHelpContentsAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); helpMenu.add(menuItem); if (application != null && !application.isMac()) { // Non Macs have a Help About menu item. MultiBitAction helpAboutAction = new MultiBitAction(controller, ImageLoader.MULTIBIT_SMALL_ICON_FILE, "helpAboutAction.text", "helpAboutAction.tooltip", "helpAboutAction.mnemonic", View.HELP_ABOUT_VIEW); helpAboutAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("helpAboutAction.tooltip"))); menuItem = new JMenuItem(helpAboutAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); helpMenu.add(menuItem); } // View Transactions action. MultiBitAction showTransactionsAction = new MultiBitAction(controller, ImageLoader.TRANSACTIONS_ICON_FILE, "showTransactionsAction.text", "showTransactionsAction.tooltip", "showTransactionsAction.mnemonic", View.TRANSACTIONS_VIEW); showTransactionsAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("showTransactionsAction.tooltip"))); menuItem = new JMenuItem(showTransactionsAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); viewMenu.add(menuItem); // View Charts action. MultiBitAction showChartsAction = new MultiBitAction(controller, ImageLoader.CHART_LINE_ICON_FILE, "chartsPanelAction.text", "chartsPanelAction.tooltip", "chartsPanelAction.mnemonic", View.CHARTS_VIEW); showChartsAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("chartsPanelAction.tooltip"))); menuItem = new JMenuItem(showChartsAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); viewMenu.add(menuItem); // Show messages action. MultiBitAction showMessagesAction = new MultiBitAction(controller, ImageLoader.MESSAGES_ICON_FILE, "messagesPanel.text", "messagesPanel.tooltip", "messagesPanel.mnemonic", View.MESSAGES_VIEW); showMessagesAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("messagesPanel.tooltip"))); menuItem = new JMenuItem(showMessagesAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); viewMenu.add(menuItem); // Send bitcoin action. MultiBitAction sendBitcoinAction = new MultiBitAction(controller, ImageLoader.SEND_BITCOIN_ICON_FILE, "sendBitcoinAction.text", "sendBitcoinAction.tooltip", "sendBitcoinAction.mnemonic", View.SEND_BITCOIN_VIEW); sendBitcoinAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("sendBitcoinAction.tooltip"))); menuItem = new JMenuItem(sendBitcoinAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); tradeMenu.add(menuItem); MultiBitAction receiveBitcoinAction = new MultiBitAction(controller, ImageLoader.RECEIVE_BITCOIN_ICON_FILE, "receiveBitcoinAction.text", "receiveBitcoinAction.tooltip", "receiveBitcoinAction.mnemonic", View.RECEIVE_BITCOIN_VIEW); receiveBitcoinAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("receiveBitcoinAction.tooltip"))); menuItem = new JMenuItem(receiveBitcoinAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); tradeMenu.add(menuItem); // Show preferences. if (application != null && !application.isMac()) { // Non Macs have a Preferences menu item. MultiBitAction showPreferencesAction = new MultiBitAction(controller, ImageLoader.PREFERENCES_ICON_FILE, "showPreferencesAction.text", "showPreferencesAction.tooltip", "showPreferencesAction.mnemonic", View.PREFERENCES_VIEW); showPreferencesAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("showPreferencesAction.tooltip"))); menuItem = new JMenuItem(showPreferencesAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); viewMenu.add(menuItem); } viewMenu.addSeparator(); // Show ticker. String viewTicker = controller.getModel().getUserPreference(ExchangeModel.TICKER_SHOW); boolean isTickerVisible = !Boolean.FALSE.toString().equals(viewTicker); String tickerKey; if (isTickerVisible) { tickerKey = "multiBitFrame.ticker.hide.text"; } else { tickerKey = "multiBitFrame.ticker.show.text"; } final JMenuItem showTicker = new JMenuItem(controller.getLocaliser().getString(tickerKey)); showTicker.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); showTicker.setComponentOrientation(componentOrientation); showTicker.setIcon(ImageLoader.createImageIcon(ImageLoader.MONEY_ICON_FILE)); if (tickerTablePanel != null) { tickerTablePanel.setVisible(isTickerVisible); } final MultiBitFrame thisFrame = this; showTicker.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { if (tickerTablePanel != null) { if (tickerTablePanel.isVisible()) { tickerTablePanel.setVisible(false); controller.getModel().setUserPreference(ExchangeModel.TICKER_SHOW, Boolean.FALSE.toString()); showTicker.setText(controller.getLocaliser().getString("multiBitFrame.ticker.show.text")); } else { tickerTablePanel.setVisible(true); controller.getModel().setUserPreference(ExchangeModel.TICKER_SHOW, Boolean.TRUE.toString()); showTicker.setText(controller.getLocaliser().getString("multiBitFrame.ticker.hide.text")); // Cancel any existing timer. if (tickerTimer1 != null) { tickerTimer1.cancel(); } if (tickerTimer2 != null) { tickerTimer2.cancel(); } // Start ticker timer. tickerTimer1 = new Timer(); tickerTimer1.schedule(new TickerTimerTask(exchangeController, thisFrame, true), 0, TickerTimerTask.DEFAULT_REPEAT_RATE); boolean showSecondRow = Boolean.TRUE.toString().equals( controller.getModel().getUserPreference(ExchangeModel.TICKER_SHOW_SECOND_ROW)); if (showSecondRow) { tickerTimer2 = new Timer(); tickerTimer2.schedule(new TickerTimerTask(exchangeController, thisFrame, false), TickerTimerTask.TASK_SEPARATION, TickerTimerTask.DEFAULT_REPEAT_RATE); } } } } }); viewMenu.add(showTicker); // Sign message. signMessageAction = new MultiBitWalletBusyAction(this.bitcoinController, ImageLoader.MESSAGE_SIGN_ICON_FILE, "signMessageAction.text", "signMessageAction.tooltip", "signMessageAction.mnemonic", View.SIGN_MESSAGE_VIEW); menuItem = new JMenuItem(signMessageAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); toolsMenu.add(menuItem); // Verify message. MultiBitAction verifyMessageAction = new MultiBitAction(this.bitcoinController, ImageLoader.MESSAGE_VERIFY_ICON_FILE, "verifyMessageAction.text", "verifyMessageAction.tooltip", "verifyMessageAction.mnemonic", View.VERIFY_MESSAGE_VIEW); verifyMessageAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("verifyMessageAction.tooltip"))); menuItem = new JMenuItem(verifyMessageAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); toolsMenu.add(menuItem); toolsMenu.addSeparator(); // Import private keys. showImportPrivateKeysAction = new MultiBitWalletBusyAction(this.bitcoinController, ImageLoader.IMPORT_PRIVATE_KEYS_ICON_FILE, "showImportPrivateKeysAction.text", "showImportPrivateKeysAction.tooltip", "showImportPrivateKeysAction.mnemonic", View.SHOW_IMPORT_PRIVATE_KEYS_VIEW); menuItem = new JMenuItem(showImportPrivateKeysAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); toolsMenu.add(menuItem); // Export private keys. showExportPrivateKeysAction = new MultiBitWalletBusyAction(this.bitcoinController, ImageLoader.EXPORT_PRIVATE_KEYS_ICON_FILE, "showExportPrivateKeysAction.text", "showExportPrivateKeysAction.tooltip", "showExportPrivateKeysAction.mnemonic", View.SHOW_EXPORT_PRIVATE_KEYS_VIEW); menuItem = new JMenuItem(showExportPrivateKeysAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); toolsMenu.add(menuItem); toolsMenu.addSeparator(); resetTransactionsAction = new MultiBitWalletBusyAction(this.bitcoinController, ImageLoader.RESET_TRANSACTIONS_ICON_FILE, "resetTransactionsAction.text", "resetTransactionsAction.tooltip", "resetTransactionsAction.mnemonic", View.RESET_TRANSACTIONS_VIEW); resetTransactionsAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("resetTransactionsAction.tooltip"))); menuItem = new JMenuItem(resetTransactionsAction); menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); menuItem.setComponentOrientation(componentOrientation); toolsMenu.add(menuItem); setJMenuBar(menuBar); return; }
diff --git a/illaeasynpc/src/illarion/easynpc/parser/talk/TalkingLine.java b/illaeasynpc/src/illarion/easynpc/parser/talk/TalkingLine.java index 7f5f4ce0..2b8d1c19 100644 --- a/illaeasynpc/src/illarion/easynpc/parser/talk/TalkingLine.java +++ b/illaeasynpc/src/illarion/easynpc/parser/talk/TalkingLine.java @@ -1,304 +1,304 @@ /* * This file is part of the Illarion easyNPC Editor. * * Copyright © 2012 - Illarion e.V. * * The Illarion easyNPC Editor 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. * * The Illarion easyNPC Editor 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 the Illarion easyNPC Editor. If not, see <http://www.gnu.org/licenses/>. */ package illarion.easynpc.parser.talk; import illarion.easynpc.EasyNpcScript; import illarion.easynpc.Lang; import illarion.easynpc.ParsedNpc; import illarion.easynpc.docu.DocuEntry; import illarion.easynpc.parsed.ParsedTalk; import illarion.easynpc.parsed.talk.TalkCondition; import illarion.easynpc.parsed.talk.TalkConsequence; import org.fife.ui.rsyntaxtextarea.TokenMap; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; /** * This class is used to store talking informations of a NPC. It stores the data * about one line of talking with all triggers, answers, consequences and * conditions. * * @author Martin Karing &lt;[email protected]&gt; */ public final class TalkingLine { /** * The string used to split the conditions and the consequences of the * talking line. */ @SuppressWarnings("nls") private static final String SPLIT_STRING = "->"; /** * The documentation entry for the conditions. */ @Nonnull private final DocuEntry conditionDocu; /** * The list of condition parsers. */ @Nonnull private final ArrayList<ConditionParser> condPar; /** * The documentation entry for the consequences. */ @Nonnull private final DocuEntry consequenceDocu; /** * The list of consequence parsers. */ @Nonnull private final ArrayList<ConsequenceParser> consPar; /** * The constructor that sets up all known parsers this class requires to * work properly. */ public TalkingLine() { condPar = new ArrayList<ConditionParser>(); consPar = new ArrayList<ConsequenceParser>(); condPar.add(new illarion.easynpc.parser.talk.conditions.State()); condPar.add(new illarion.easynpc.parser.talk.conditions.Skill()); condPar.add(new illarion.easynpc.parser.talk.conditions.Attribute()); condPar.add(new illarion.easynpc.parser.talk.conditions.MagicType()); condPar.add(new illarion.easynpc.parser.talk.conditions.Money()); condPar.add(new illarion.easynpc.parser.talk.conditions.Race()); condPar.add(new illarion.easynpc.parser.talk.conditions.Rank()); condPar.add(new illarion.easynpc.parser.talk.conditions.Queststatus()); condPar.add(new illarion.easynpc.parser.talk.conditions.Item()); condPar.add(new illarion.easynpc.parser.talk.conditions.Language()); condPar.add(new illarion.easynpc.parser.talk.conditions.Chance()); condPar.add(new illarion.easynpc.parser.talk.conditions.Town()); condPar.add(new illarion.easynpc.parser.talk.conditions.TalkMode()); condPar.add(new illarion.easynpc.parser.talk.conditions.Sex()); condPar.add(new illarion.easynpc.parser.talk.conditions.Trigger()); condPar.add(new illarion.easynpc.parser.talk.conditions.Admin()); condPar.add(new illarion.easynpc.parser.talk.conditions.Talkstate()); condPar.add(new illarion.easynpc.parser.talk.conditions.Number()); consPar.add(new illarion.easynpc.parser.talk.consequences.Inform()); consPar.add(new illarion.easynpc.parser.talk.consequences.State()); consPar.add(new illarion.easynpc.parser.talk.consequences.Skill()); consPar.add(new illarion.easynpc.parser.talk.consequences.Attribute()); consPar.add(new illarion.easynpc.parser.talk.consequences.Rune()); consPar.add(new illarion.easynpc.parser.talk.consequences.Money()); consPar.add(new illarion.easynpc.parser.talk.consequences.DeleteItem()); consPar.add(new illarion.easynpc.parser.talk.consequences.Item()); consPar.add(new illarion.easynpc.parser.talk.consequences.Queststatus()); consPar.add(new illarion.easynpc.parser.talk.consequences.Rankpoints()); consPar.add(new illarion.easynpc.parser.talk.consequences.Talkstate()); consPar.add(new illarion.easynpc.parser.talk.consequences.Town()); consPar.add(new illarion.easynpc.parser.talk.consequences.Treasure()); consPar.add(new illarion.easynpc.parser.talk.consequences.Warp()); - consPar.add(new illarion.easynpc.parser.talk.consequences.Gemcraft()); consPar.add(new illarion.easynpc.parser.talk.consequences.Answer()); consPar.add(new illarion.easynpc.parser.talk.consequences.Trade()); + consPar.add(new illarion.easynpc.parser.talk.consequences.Gemcraft()); consPar.add(new illarion.easynpc.parser.talk.consequences.Introduce()); final List<ConditionParser> conditionsList = condPar; final List<ConsequenceParser> consequenceList = consPar; conditionDocu = new DocuEntry() { @SuppressWarnings("nls") @Override public DocuEntry getChild(final int index) { if ((index < 0) || (index >= conditionsList.size())) { throw new IllegalArgumentException("Index out of range"); } return conditionsList.get(index); } @Override public int getChildCount() { return conditionsList.size(); } @SuppressWarnings("nls") @Override public String getDescription() { return Lang.getMsg(TalkingLine.class, "Conditions.Docu.description"); } @Nullable @Override public String getExample() { return null; } @Nullable @Override public String getSyntax() { return null; } @Override @SuppressWarnings("nls") public String getTitle() { return Lang.getMsg(TalkingLine.class, "Conditions.Docu.title"); } }; consequenceDocu = new DocuEntry() { @SuppressWarnings("nls") @Override public DocuEntry getChild(final int index) { if ((index < 0) || (index >= consequenceList.size())) { throw new IllegalArgumentException("Index out of range"); } return consequenceList.get(index); } @Override public int getChildCount() { return consequenceList.size(); } @SuppressWarnings("nls") @Override public String getDescription() { return Lang.getMsg(TalkingLine.class, "Consequence.Docu.description"); } @Nullable @Override public String getExample() { return null; } @Nullable @Override public String getSyntax() { return null; } @Override @SuppressWarnings("nls") public String getTitle() { return Lang .getMsg(TalkingLine.class, "Consequence.Docu.title"); } }; } /** * Get the documentation entry for the conditions. * * @return the conditions documentation entry */ @Nullable public DocuEntry getConditionDocuEntry() { return conditionDocu; } /** * Get the documentation entry for the consequences. * * @return the consequences documentation entry */ @Nullable public DocuEntry getConsequenceDocuEntry() { return consequenceDocu; } /** * Parse a talking line into a properly parsed line. * * @param line the line to parse * @param npc the npc that receives the data parsed here */ @SuppressWarnings("nls") public void parseLine(@Nonnull final EasyNpcScript.Line line, @Nonnull final ParsedNpc npc) { final String[] workingLines = line.getLine().split(SPLIT_STRING); if (workingLines.length != 2) { npc.addError(line, "Invalid line fetched!"); return; } String conditions = workingLines[0] + ','; String consequences = workingLines[1] + ','; final ParsedTalk parsedLine = new ParsedTalk(); for (final ConditionParser parser : condPar) { parser.setLine(conditions); parser.setErrorParent(npc, line); TalkCondition con = null; while (true) { con = parser.extract(); if (con == null) { break; } parsedLine.addCondition(con); } conditions = parser.getNewLine(); parser.cleanup(); } for (final ConsequenceParser parser : consPar) { parser.setLine(consequences); parser.setErrorParent(npc, line); TalkConsequence con = null; while (true) { con = parser.extract(); if (con == null) { break; } parsedLine.addConsequence(con); } consequences = parser.getNewLine(); parser.cleanup(); } if (!conditions.isEmpty()) { npc.addError(line, Lang.getMsg(getClass(), "remainConditions") + ' ' + conditions); } if (!consequences.isEmpty()) { npc.addError(line, Lang.getMsg(getClass(), "remainConsequences") + ' ' + consequences); } npc.addNpcData(parsedLine); } public void enlistHighlightedWords(final TokenMap map) { for (final ConditionParser parser : condPar) { parser.enlistHighlightedWords(map); } for (final ConsequenceParser parser : consPar) { parser.enlistHighlightedWords(map); } } }
false
true
public TalkingLine() { condPar = new ArrayList<ConditionParser>(); consPar = new ArrayList<ConsequenceParser>(); condPar.add(new illarion.easynpc.parser.talk.conditions.State()); condPar.add(new illarion.easynpc.parser.talk.conditions.Skill()); condPar.add(new illarion.easynpc.parser.talk.conditions.Attribute()); condPar.add(new illarion.easynpc.parser.talk.conditions.MagicType()); condPar.add(new illarion.easynpc.parser.talk.conditions.Money()); condPar.add(new illarion.easynpc.parser.talk.conditions.Race()); condPar.add(new illarion.easynpc.parser.talk.conditions.Rank()); condPar.add(new illarion.easynpc.parser.talk.conditions.Queststatus()); condPar.add(new illarion.easynpc.parser.talk.conditions.Item()); condPar.add(new illarion.easynpc.parser.talk.conditions.Language()); condPar.add(new illarion.easynpc.parser.talk.conditions.Chance()); condPar.add(new illarion.easynpc.parser.talk.conditions.Town()); condPar.add(new illarion.easynpc.parser.talk.conditions.TalkMode()); condPar.add(new illarion.easynpc.parser.talk.conditions.Sex()); condPar.add(new illarion.easynpc.parser.talk.conditions.Trigger()); condPar.add(new illarion.easynpc.parser.talk.conditions.Admin()); condPar.add(new illarion.easynpc.parser.talk.conditions.Talkstate()); condPar.add(new illarion.easynpc.parser.talk.conditions.Number()); consPar.add(new illarion.easynpc.parser.talk.consequences.Inform()); consPar.add(new illarion.easynpc.parser.talk.consequences.State()); consPar.add(new illarion.easynpc.parser.talk.consequences.Skill()); consPar.add(new illarion.easynpc.parser.talk.consequences.Attribute()); consPar.add(new illarion.easynpc.parser.talk.consequences.Rune()); consPar.add(new illarion.easynpc.parser.talk.consequences.Money()); consPar.add(new illarion.easynpc.parser.talk.consequences.DeleteItem()); consPar.add(new illarion.easynpc.parser.talk.consequences.Item()); consPar.add(new illarion.easynpc.parser.talk.consequences.Queststatus()); consPar.add(new illarion.easynpc.parser.talk.consequences.Rankpoints()); consPar.add(new illarion.easynpc.parser.talk.consequences.Talkstate()); consPar.add(new illarion.easynpc.parser.talk.consequences.Town()); consPar.add(new illarion.easynpc.parser.talk.consequences.Treasure()); consPar.add(new illarion.easynpc.parser.talk.consequences.Warp()); consPar.add(new illarion.easynpc.parser.talk.consequences.Gemcraft()); consPar.add(new illarion.easynpc.parser.talk.consequences.Answer()); consPar.add(new illarion.easynpc.parser.talk.consequences.Trade()); consPar.add(new illarion.easynpc.parser.talk.consequences.Introduce()); final List<ConditionParser> conditionsList = condPar; final List<ConsequenceParser> consequenceList = consPar; conditionDocu = new DocuEntry() { @SuppressWarnings("nls") @Override public DocuEntry getChild(final int index) { if ((index < 0) || (index >= conditionsList.size())) { throw new IllegalArgumentException("Index out of range"); } return conditionsList.get(index); } @Override public int getChildCount() { return conditionsList.size(); } @SuppressWarnings("nls") @Override public String getDescription() { return Lang.getMsg(TalkingLine.class, "Conditions.Docu.description"); } @Nullable @Override public String getExample() { return null; } @Nullable @Override public String getSyntax() { return null; } @Override @SuppressWarnings("nls") public String getTitle() { return Lang.getMsg(TalkingLine.class, "Conditions.Docu.title"); } }; consequenceDocu = new DocuEntry() { @SuppressWarnings("nls") @Override public DocuEntry getChild(final int index) { if ((index < 0) || (index >= consequenceList.size())) { throw new IllegalArgumentException("Index out of range"); } return consequenceList.get(index); } @Override public int getChildCount() { return consequenceList.size(); } @SuppressWarnings("nls") @Override public String getDescription() { return Lang.getMsg(TalkingLine.class, "Consequence.Docu.description"); } @Nullable @Override public String getExample() { return null; } @Nullable @Override public String getSyntax() { return null; } @Override @SuppressWarnings("nls") public String getTitle() { return Lang .getMsg(TalkingLine.class, "Consequence.Docu.title"); } }; }
public TalkingLine() { condPar = new ArrayList<ConditionParser>(); consPar = new ArrayList<ConsequenceParser>(); condPar.add(new illarion.easynpc.parser.talk.conditions.State()); condPar.add(new illarion.easynpc.parser.talk.conditions.Skill()); condPar.add(new illarion.easynpc.parser.talk.conditions.Attribute()); condPar.add(new illarion.easynpc.parser.talk.conditions.MagicType()); condPar.add(new illarion.easynpc.parser.talk.conditions.Money()); condPar.add(new illarion.easynpc.parser.talk.conditions.Race()); condPar.add(new illarion.easynpc.parser.talk.conditions.Rank()); condPar.add(new illarion.easynpc.parser.talk.conditions.Queststatus()); condPar.add(new illarion.easynpc.parser.talk.conditions.Item()); condPar.add(new illarion.easynpc.parser.talk.conditions.Language()); condPar.add(new illarion.easynpc.parser.talk.conditions.Chance()); condPar.add(new illarion.easynpc.parser.talk.conditions.Town()); condPar.add(new illarion.easynpc.parser.talk.conditions.TalkMode()); condPar.add(new illarion.easynpc.parser.talk.conditions.Sex()); condPar.add(new illarion.easynpc.parser.talk.conditions.Trigger()); condPar.add(new illarion.easynpc.parser.talk.conditions.Admin()); condPar.add(new illarion.easynpc.parser.talk.conditions.Talkstate()); condPar.add(new illarion.easynpc.parser.talk.conditions.Number()); consPar.add(new illarion.easynpc.parser.talk.consequences.Inform()); consPar.add(new illarion.easynpc.parser.talk.consequences.State()); consPar.add(new illarion.easynpc.parser.talk.consequences.Skill()); consPar.add(new illarion.easynpc.parser.talk.consequences.Attribute()); consPar.add(new illarion.easynpc.parser.talk.consequences.Rune()); consPar.add(new illarion.easynpc.parser.talk.consequences.Money()); consPar.add(new illarion.easynpc.parser.talk.consequences.DeleteItem()); consPar.add(new illarion.easynpc.parser.talk.consequences.Item()); consPar.add(new illarion.easynpc.parser.talk.consequences.Queststatus()); consPar.add(new illarion.easynpc.parser.talk.consequences.Rankpoints()); consPar.add(new illarion.easynpc.parser.talk.consequences.Talkstate()); consPar.add(new illarion.easynpc.parser.talk.consequences.Town()); consPar.add(new illarion.easynpc.parser.talk.consequences.Treasure()); consPar.add(new illarion.easynpc.parser.talk.consequences.Warp()); consPar.add(new illarion.easynpc.parser.talk.consequences.Answer()); consPar.add(new illarion.easynpc.parser.talk.consequences.Trade()); consPar.add(new illarion.easynpc.parser.talk.consequences.Gemcraft()); consPar.add(new illarion.easynpc.parser.talk.consequences.Introduce()); final List<ConditionParser> conditionsList = condPar; final List<ConsequenceParser> consequenceList = consPar; conditionDocu = new DocuEntry() { @SuppressWarnings("nls") @Override public DocuEntry getChild(final int index) { if ((index < 0) || (index >= conditionsList.size())) { throw new IllegalArgumentException("Index out of range"); } return conditionsList.get(index); } @Override public int getChildCount() { return conditionsList.size(); } @SuppressWarnings("nls") @Override public String getDescription() { return Lang.getMsg(TalkingLine.class, "Conditions.Docu.description"); } @Nullable @Override public String getExample() { return null; } @Nullable @Override public String getSyntax() { return null; } @Override @SuppressWarnings("nls") public String getTitle() { return Lang.getMsg(TalkingLine.class, "Conditions.Docu.title"); } }; consequenceDocu = new DocuEntry() { @SuppressWarnings("nls") @Override public DocuEntry getChild(final int index) { if ((index < 0) || (index >= consequenceList.size())) { throw new IllegalArgumentException("Index out of range"); } return consequenceList.get(index); } @Override public int getChildCount() { return consequenceList.size(); } @SuppressWarnings("nls") @Override public String getDescription() { return Lang.getMsg(TalkingLine.class, "Consequence.Docu.description"); } @Nullable @Override public String getExample() { return null; } @Nullable @Override public String getSyntax() { return null; } @Override @SuppressWarnings("nls") public String getTitle() { return Lang .getMsg(TalkingLine.class, "Consequence.Docu.title"); } }; }
diff --git a/hazelcast/src/test/java/com/hazelcast/concurrent/countdownlatch/CountDownLatchTest.java b/hazelcast/src/test/java/com/hazelcast/concurrent/countdownlatch/CountDownLatchTest.java index 6f89f837c0..43b258064a 100644 --- a/hazelcast/src/test/java/com/hazelcast/concurrent/countdownlatch/CountDownLatchTest.java +++ b/hazelcast/src/test/java/com/hazelcast/concurrent/countdownlatch/CountDownLatchTest.java @@ -1,164 +1,167 @@ /* * Copyright (c) 2008-2013, Hazelcast, Inc. 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.hazelcast.concurrent.countdownlatch; import com.hazelcast.config.Config; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.ICountDownLatch; import com.hazelcast.spi.exception.DistributedObjectDestroyedException; import com.hazelcast.test.HazelcastJUnit4ClassRunner; import com.hazelcast.test.HazelcastTestSupport; import com.hazelcast.test.TestHazelcastInstanceFactory; import com.hazelcast.test.annotation.ClientCompatibleTest; import com.hazelcast.test.annotation.ParallelTest; import org.junit.Assert; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import java.util.concurrent.TimeUnit; /** * @author mdogan 1/16/13 */ @RunWith(HazelcastJUnit4ClassRunner.class) @Category(ParallelTest.class) public class CountDownLatchTest extends HazelcastTestSupport { @Test @ClientCompatibleTest public void testSimpleUsage() { final int k = 5; final Config config = new Config(); TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(k); final HazelcastInstance[] instances = factory.newInstances(config); ICountDownLatch latch = instances[0].getCountDownLatch("test"); latch.trySetCount(k - 1); Assert.assertEquals(k - 1, latch.getCount()); new Thread() { public void run() { for (int i = 1; i < k; i++) { try { sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } final ICountDownLatch l = instances[i].getCountDownLatch("test"); l.countDown(); Assert.assertEquals(k - 1 - i, l.getCount()); } } }.start(); try { Assert.assertTrue(latch.await(5000, TimeUnit.MILLISECONDS)); } catch (Exception e) { e.printStackTrace(); Assert.fail(e.getMessage()); } Assert.assertEquals(0, latch.getCount()); } @Test @ClientCompatibleTest public void testAwaitFail() { final int k = 3; final Config config = new Config(); TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(k); final HazelcastInstance[] instances = factory.newInstances(config); ICountDownLatch latch = instances[0].getCountDownLatch("test"); latch.trySetCount(k - 1); try { long t = System.currentTimeMillis(); Assert.assertFalse(latch.await(100, TimeUnit.MILLISECONDS)); final long elapsed = System.currentTimeMillis() - t; Assert.assertTrue(elapsed >= 100); } catch (Exception e) { e.printStackTrace(); Assert.fail(e.getMessage()); } } @Test(expected = DistributedObjectDestroyedException.class) @ClientCompatibleTest public void testLatchDestroyed() throws Exception { TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2); final Config config = new Config(); HazelcastInstance hz1 = factory.newHazelcastInstance(config); HazelcastInstance hz2 = factory.newHazelcastInstance(config); final ICountDownLatch latch = hz1.getCountDownLatch("test"); latch.trySetCount(2); new Thread() { public void run() { try { sleep(1000); } catch (InterruptedException e) { return; } latch.destroy(); } }.start(); hz2.getCountDownLatch("test").await(5, TimeUnit.SECONDS); } @Test @ClientCompatibleTest public void testLatchMigration() throws InterruptedException { TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(5); HazelcastInstance hz1 = factory.newHazelcastInstance(new Config()); HazelcastInstance hz2 = factory.newHazelcastInstance(new Config()); + warmUpPartitions(hz2, hz1); final ICountDownLatch latch1 = hz1.getCountDownLatch("test"); latch1.trySetCount(10); - Thread.sleep(100); + Thread.sleep(500); final ICountDownLatch latch2 = hz2.getCountDownLatch("test"); Assert.assertEquals(10, latch2.getCount()); latch2.countDown(); Assert.assertEquals(9, latch1.getCount()); hz1.getLifecycleService().shutdown(); Assert.assertEquals(9, latch2.getCount()); HazelcastInstance hz3 = factory.newHazelcastInstance(new Config()); + warmUpPartitions(hz3); final ICountDownLatch latch3 = hz3.getCountDownLatch("test"); latch3.countDown(); Assert.assertEquals(8, latch3.getCount()); hz2.getLifecycleService().shutdown(); latch3.countDown(); Assert.assertEquals(7, latch3.getCount()); HazelcastInstance hz4 = factory.newHazelcastInstance(new Config()); HazelcastInstance hz5 = factory.newHazelcastInstance(new Config()); + warmUpPartitions(hz5, hz4); Thread.sleep(250); hz3.getLifecycleService().shutdown(); final ICountDownLatch latch4 = hz4.getCountDownLatch("test"); Assert.assertEquals(7, latch4.getCount()); final ICountDownLatch latch5 = hz5.getCountDownLatch("test"); latch5.countDown(); Assert.assertEquals(6, latch5.getCount()); latch5.countDown(); Assert.assertEquals(5, latch4.getCount()); Assert.assertEquals(5, latch5.getCount()); } }
false
true
public void testLatchMigration() throws InterruptedException { TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(5); HazelcastInstance hz1 = factory.newHazelcastInstance(new Config()); HazelcastInstance hz2 = factory.newHazelcastInstance(new Config()); final ICountDownLatch latch1 = hz1.getCountDownLatch("test"); latch1.trySetCount(10); Thread.sleep(100); final ICountDownLatch latch2 = hz2.getCountDownLatch("test"); Assert.assertEquals(10, latch2.getCount()); latch2.countDown(); Assert.assertEquals(9, latch1.getCount()); hz1.getLifecycleService().shutdown(); Assert.assertEquals(9, latch2.getCount()); HazelcastInstance hz3 = factory.newHazelcastInstance(new Config()); final ICountDownLatch latch3 = hz3.getCountDownLatch("test"); latch3.countDown(); Assert.assertEquals(8, latch3.getCount()); hz2.getLifecycleService().shutdown(); latch3.countDown(); Assert.assertEquals(7, latch3.getCount()); HazelcastInstance hz4 = factory.newHazelcastInstance(new Config()); HazelcastInstance hz5 = factory.newHazelcastInstance(new Config()); Thread.sleep(250); hz3.getLifecycleService().shutdown(); final ICountDownLatch latch4 = hz4.getCountDownLatch("test"); Assert.assertEquals(7, latch4.getCount()); final ICountDownLatch latch5 = hz5.getCountDownLatch("test"); latch5.countDown(); Assert.assertEquals(6, latch5.getCount()); latch5.countDown(); Assert.assertEquals(5, latch4.getCount()); Assert.assertEquals(5, latch5.getCount()); }
public void testLatchMigration() throws InterruptedException { TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(5); HazelcastInstance hz1 = factory.newHazelcastInstance(new Config()); HazelcastInstance hz2 = factory.newHazelcastInstance(new Config()); warmUpPartitions(hz2, hz1); final ICountDownLatch latch1 = hz1.getCountDownLatch("test"); latch1.trySetCount(10); Thread.sleep(500); final ICountDownLatch latch2 = hz2.getCountDownLatch("test"); Assert.assertEquals(10, latch2.getCount()); latch2.countDown(); Assert.assertEquals(9, latch1.getCount()); hz1.getLifecycleService().shutdown(); Assert.assertEquals(9, latch2.getCount()); HazelcastInstance hz3 = factory.newHazelcastInstance(new Config()); warmUpPartitions(hz3); final ICountDownLatch latch3 = hz3.getCountDownLatch("test"); latch3.countDown(); Assert.assertEquals(8, latch3.getCount()); hz2.getLifecycleService().shutdown(); latch3.countDown(); Assert.assertEquals(7, latch3.getCount()); HazelcastInstance hz4 = factory.newHazelcastInstance(new Config()); HazelcastInstance hz5 = factory.newHazelcastInstance(new Config()); warmUpPartitions(hz5, hz4); Thread.sleep(250); hz3.getLifecycleService().shutdown(); final ICountDownLatch latch4 = hz4.getCountDownLatch("test"); Assert.assertEquals(7, latch4.getCount()); final ICountDownLatch latch5 = hz5.getCountDownLatch("test"); latch5.countDown(); Assert.assertEquals(6, latch5.getCount()); latch5.countDown(); Assert.assertEquals(5, latch4.getCount()); Assert.assertEquals(5, latch5.getCount()); }
diff --git a/ngrinder-core/src/main/java/org/ngrinder/NGrinderStarter.java b/ngrinder-core/src/main/java/org/ngrinder/NGrinderStarter.java index 07da5658..4c93b9f7 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/NGrinderStarter.java +++ b/ngrinder-core/src/main/java/org/ngrinder/NGrinderStarter.java @@ -1,321 +1,321 @@ /* * 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.ngrinder; import ch.qos.logback.classic.joran.JoranConfigurator; import ch.qos.logback.core.Context; import ch.qos.logback.core.joran.spi.JoranException; import net.grinder.AgentControllerDaemon; import net.grinder.util.VersionNumber; import org.apache.commons.lang.StringUtils; import org.hyperic.sigar.ProcState; import org.hyperic.sigar.Sigar; import org.hyperic.sigar.SigarException; import org.ngrinder.infra.AgentConfig; import org.ngrinder.monitor.MonitorConstants; import org.ngrinder.monitor.agent.AgentMonitorServer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FilenameFilter; import java.net.InetAddress; import static net.grinder.util.NetworkUtil.getAddressWithSocket; import static net.grinder.util.NetworkUtil.getIP; import static org.apache.commons.lang.StringUtils.defaultIfBlank; import static org.ngrinder.common.util.NoOp.noOp; /** * Main class to start agent or monitor. * * @author Mavlarn * @author JunHo Yoon * @since 3.0 */ public class NGrinderStarter { private static final Logger LOG = LoggerFactory.getLogger(NGrinderStarter.class); private AgentConfig agentConfig; private AgentControllerDaemon agentController; /** * Constructor. */ public NGrinderStarter() { init(); } protected void init() { // Check agent start mode checkRunningDirectory(); agentConfig = new AgentConfig(); agentConfig.init(); // Configure log. configureLogging(); } private void configureLogging() { Boolean verboseMode = agentConfig.getPropertyBoolean("verbose", false); File logDirectory = agentConfig.getHome().getLogDirectory(); configureLogging(verboseMode, logDirectory); } protected void checkRunningDirectory() { if (!isValidCurrentDirectory()) { staticPrintHelpAndExit("nGrinder agent should start in the folder where nGrinder agent binary exists."); } } /* * Get the start mode, "agent" or "monitor". If it is not set in configuration, it will return "agent". */ public String getStartMode() { return agentConfig.getAgentProperties().getProperty("start.mode", "agent"); } /** * Get agent version. * * @return version string */ public String getVersion() { return agentConfig.getInternalProperty("ngrinder.version", "UNKNOWN"); } /** * Start the performance monitor. */ public void startMonitor() { LOG.info("***************************************************"); LOG.info("* Start nGrinder Monitor... "); LOG.info("***************************************************"); MonitorConstants.init(agentConfig); try { int monitorPort = agentConfig.getPropertyInt(AgentConfig.MONITOR_LISTEN_PORT, MonitorConstants.DEFAULT_MONITOR_PORT); AgentMonitorServer.getInstance().init(monitorPort, agentConfig); AgentMonitorServer.getInstance().start(); } catch (Exception e) { LOG.error("ERROR: {}", e.getMessage()); printHelpAndExit("Error while starting Monitor", e); } } /** * Stop monitors. */ public void stopMonitor() { AgentMonitorServer.getInstance().stop(); } /** * Start ngrinder agent. * * @param directControllerIP controllerIp to connect directly; */ public void startAgent(String directControllerIP) { LOG.info("***************************************************"); LOG.info(" Start nGrinder Agent ..."); LOG.info("***************************************************"); if (StringUtils.isEmpty(System.getenv("JAVA_HOME"))) { - LOG.error("Hey!! JAVA_HOME env var was not provided. " + LOG.info("Hey!! JAVA_HOME env var was not provided. " + "Please provide JAVA_HOME env var before running agent." + "Otherwise you can not execute the agent in the security mode."); } boolean serverMode = agentConfig.isServerMode(); if (!serverMode) { - LOG.info("JVM server mode is disabled. If you turn on ngrinder.servermode in agent.conf." + LOG.info("JVM server mode is disabled. If you turn on agent.servermode in agent.conf." + " It will provide the better agent performance."); } String controllerIP = getIP(defaultIfBlank(directControllerIP, agentConfig.getControllerIP())); int controllerPort = agentConfig.getControllerPort(); agentConfig.setControllerIP(controllerIP); String region = agentConfig.getRegion(); LOG.info("connecting to controller {}:{}", controllerIP, controllerPort); try { InetAddress localAddress = getAddressWithSocket(controllerIP, controllerPort); System.setProperty("java.rmi.server.hostname", localAddress.getHostAddress()); agentController = new AgentControllerDaemon(agentConfig); agentController.run(); } catch (Exception e) { LOG.error("Error while connecting to : {}:{}", controllerIP, controllerPort); printHelpAndExit("Error while starting Agent", e); } } /** * Stop the ngrinder agent. */ public void stopAgent() { LOG.info("Stop nGrinder agent!"); agentController.shutdown(); } private void configureLogging(boolean verbose, File logDirectory) { final Context context = (Context) LoggerFactory.getILoggerFactory(); final JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(context); context.putProperty("LOG_LEVEL", verbose ? "TRACE" : "INFO"); context.putProperty("LOG_DIRECTORY", logDirectory.getAbsolutePath()); try { configurator.doConfigure(NGrinderStarter.class.getResource("/logback-agent.xml")); } catch (JoranException e) { staticPrintHelpAndExit("Can not configure logger on " + logDirectory.getAbsolutePath() + ".\n Please check if it's writable."); } } /** * Print help and exit. This is provided for mocking. * * @param message message */ protected void printHelpAndExit(String message) { staticPrintHelpAndExit(message); } /** * print help and exit. This is provided for mocking. * * @param message message * @param e exception */ protected void printHelpAndExit(String message, Exception e) { staticPrintHelpAndExit(message, e); } /** * Agent starter. * * @param args arguments */ public static void main(String[] args) { NGrinderStarter starter = new NGrinderStarter(); checkJavaVersion(); String startMode = System.getProperty("start.mode"); LOG.info("- Passing mode " + startMode); LOG.info("- nGrinder version " + starter.getVersion()); if ("stopagent".equalsIgnoreCase(startMode)) { starter.stopProcess("agent"); return; } else if ("stopmonitor".equalsIgnoreCase(startMode)) { starter.stopProcess("monitor"); return; } startMode = (startMode == null) ? starter.getStartMode() : startMode; starter.checkDuplicatedRun(startMode); if (startMode.equalsIgnoreCase("agent")) { String controllerIp = System.getProperty("controller"); starter.startAgent(controllerIp); } else if (startMode.equalsIgnoreCase("monitor")) { starter.startMonitor(); } else { staticPrintHelpAndExit("Invalid agent.conf, 'start.mode' must be set as 'monitor' or 'agent'."); } } static void checkJavaVersion() { String curJavaVersion = System.getProperty("java.version", "1.6"); checkJavaVersion(curJavaVersion); } static void checkJavaVersion(String curJavaVersion) { if (new VersionNumber(curJavaVersion).compareTo(new VersionNumber("1.6")) < 0) { LOG.info("- Current java version {} is less than 1.6. nGrinder Agent might not work well", curJavaVersion); } } /** * Stop process. * * @param mode agent or monitor. */ protected void stopProcess(String mode) { String pid = agentConfig.getAgentPidProperties(mode); try { if (StringUtils.isNotBlank(pid)) { new Sigar().kill(pid, 15); } agentConfig.updateAgentPidProperties(mode); } catch (SigarException e) { printHelpAndExit(String.format("Error occurred while terminating %s process.\n" + "It can be already stopped or you may not have the permission.\n" + "If everything is OK. Please stop it manually.", mode), e); } } /** * Check if the process is already running in this env. * * @param startMode monitor or agent */ public void checkDuplicatedRun(String startMode) { Sigar sigar = new Sigar(); String existingPid = this.agentConfig.getAgentPidProperties(startMode); if (StringUtils.isNotEmpty(existingPid)) { try { ProcState procState = sigar.getProcState(existingPid); if (procState.getState() == ProcState.RUN || procState.getState() == ProcState.IDLE || procState.getState() == ProcState.SLEEP) { printHelpAndExit("Currently " + startMode + " is running with pid " + existingPid + ". Please stop it before run"); } agentConfig.updateAgentPidProperties(startMode); } catch (SigarException e) { noOp(); } } this.agentConfig.saveAgentPidProperties(String.valueOf(sigar.getPid()), startMode); } /** * Check the current directory is valid or not. * <p/> * ngrinder agent should run in the folder agent exists. * * @return true if it's valid */ boolean isValidCurrentDirectory() { File currentFolder = new File(System.getProperty("user.dir")); String[] list = currentFolder.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return (name.startsWith("run_agent") && (name.endsWith(".sh") || name.endsWith(".bat"))); } }); return (list != null && list.length != 0); } private static void staticPrintHelpAndExit(String message) { staticPrintHelpAndExit(message, null); } private static void staticPrintHelpAndExit(String message, Exception e) { if (e == null) { LOG.error(message); } else { LOG.error(message, e); } System.exit(-1); } }
false
true
public void startAgent(String directControllerIP) { LOG.info("***************************************************"); LOG.info(" Start nGrinder Agent ..."); LOG.info("***************************************************"); if (StringUtils.isEmpty(System.getenv("JAVA_HOME"))) { LOG.error("Hey!! JAVA_HOME env var was not provided. " + "Please provide JAVA_HOME env var before running agent." + "Otherwise you can not execute the agent in the security mode."); } boolean serverMode = agentConfig.isServerMode(); if (!serverMode) { LOG.info("JVM server mode is disabled. If you turn on ngrinder.servermode in agent.conf." + " It will provide the better agent performance."); } String controllerIP = getIP(defaultIfBlank(directControllerIP, agentConfig.getControllerIP())); int controllerPort = agentConfig.getControllerPort(); agentConfig.setControllerIP(controllerIP); String region = agentConfig.getRegion(); LOG.info("connecting to controller {}:{}", controllerIP, controllerPort); try { InetAddress localAddress = getAddressWithSocket(controllerIP, controllerPort); System.setProperty("java.rmi.server.hostname", localAddress.getHostAddress()); agentController = new AgentControllerDaemon(agentConfig); agentController.run(); } catch (Exception e) { LOG.error("Error while connecting to : {}:{}", controllerIP, controllerPort); printHelpAndExit("Error while starting Agent", e); } }
public void startAgent(String directControllerIP) { LOG.info("***************************************************"); LOG.info(" Start nGrinder Agent ..."); LOG.info("***************************************************"); if (StringUtils.isEmpty(System.getenv("JAVA_HOME"))) { LOG.info("Hey!! JAVA_HOME env var was not provided. " + "Please provide JAVA_HOME env var before running agent." + "Otherwise you can not execute the agent in the security mode."); } boolean serverMode = agentConfig.isServerMode(); if (!serverMode) { LOG.info("JVM server mode is disabled. If you turn on agent.servermode in agent.conf." + " It will provide the better agent performance."); } String controllerIP = getIP(defaultIfBlank(directControllerIP, agentConfig.getControllerIP())); int controllerPort = agentConfig.getControllerPort(); agentConfig.setControllerIP(controllerIP); String region = agentConfig.getRegion(); LOG.info("connecting to controller {}:{}", controllerIP, controllerPort); try { InetAddress localAddress = getAddressWithSocket(controllerIP, controllerPort); System.setProperty("java.rmi.server.hostname", localAddress.getHostAddress()); agentController = new AgentControllerDaemon(agentConfig); agentController.run(); } catch (Exception e) { LOG.error("Error while connecting to : {}:{}", controllerIP, controllerPort); printHelpAndExit("Error while starting Agent", e); } }
diff --git a/src/test/java/org/apache/commons/math/util/FastMathStrictComparisonTest.java b/src/test/java/org/apache/commons/math/util/FastMathStrictComparisonTest.java index cd9ecf8c1..59ad38501 100644 --- a/src/test/java/org/apache/commons/math/util/FastMathStrictComparisonTest.java +++ b/src/test/java/org/apache/commons/math/util/FastMathStrictComparisonTest.java @@ -1,248 +1,248 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.commons.math.util; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; /** * Test to compare FastMath results against StrictMath results for boundary values. * <p> * Running all tests independently: <br/> * {@code mvn test -Dtest=FastMathStrictComparisonTest}<br/> * or just run tests against a single method (e.g. scalb):<br/> * {@code mvn test -Dtest=FastMathStrictComparisonTest -DargLine="-DtestMethod=scalb"} */ @RunWith(Parameterized.class) public class FastMathStrictComparisonTest { // Values which often need special handling private static final Double[] DOUBLE_SPECIAL_VALUES = { -0.0, +0.0, // 1,2 Double.NaN, // 3 Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, // 4,5 -Double.MAX_VALUE, Double.MAX_VALUE, // 6,7 // decreasing order of absolute value to help catch first failure -MathUtils.EPSILON, MathUtils.EPSILON, // 8,9 -MathUtils.SAFE_MIN, MathUtils.SAFE_MIN, // 10,11 -Double.MIN_VALUE, Double.MIN_VALUE, // 12,13 }; private static final Float [] FLOAT_SPECIAL_VALUES = { -0.0f, +0.0f, // 1,2 Float.NaN, // 3 Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY, // 4,5 Float.MIN_VALUE, Float.MAX_VALUE, // 6,7 -Float.MIN_VALUE, -Float.MAX_VALUE, // 8,9 }; private static final Object [] LONG_SPECIAL_VALUES = { -1,0,1, // 1,2,3 Long.MIN_VALUE, Long.MAX_VALUE, // 4,5 }; private static final Object[] INT_SPECIAL_VALUES = { -1,0,1, // 1,2,3 Integer.MIN_VALUE, Integer.MAX_VALUE, // 4,5 }; private final Method mathMethod; private final Method fastMethod; private final Type[] types; private final Object[][] valueArrays; public FastMathStrictComparisonTest(Method m, Method f, Type[] types, Object[][] data) throws Exception{ this.mathMethod=m; this.fastMethod=f; this.types=types; this.valueArrays=data; } @Test public void test1() throws Exception{ setupMethodCall(mathMethod, fastMethod, types, valueArrays); } private static boolean isNumber(Double d) { return !(d.isInfinite() || d.isNaN()); } private static boolean isNumber(Float f) { return !(f.isInfinite() || f.isNaN()); } private static void reportFailedResults(Method mathMethod, Object[] params, Object expected, Object actual, int[] entries){ final String methodName = mathMethod.getName(); String format = null; long actL=0; long expL=0; if (expected instanceof Double) { Double exp = (Double) expected; Double act = (Double) actual; if (isNumber(exp) && isNumber(act) && exp != 0) { // show difference as hex actL = Double.doubleToLongBits(act); expL = Double.doubleToLongBits(exp); if (Math.abs(actL-expL)==1) { // Not 100% sure off-by-one errors are allowed everywhere, so only allow for these methods if (methodName.equals("toRadians") || methodName.equals("atan2")) { return; } } format = "%016x"; } } else if (expected instanceof Float ){ Float exp = (Float) expected; Float act = (Float) actual; if (isNumber(exp) && isNumber(act) && exp != 0) { // show difference as hex actL = Float.floatToIntBits(act); expL = Float.floatToIntBits(exp); format = "%08x"; } } StringBuilder sb = new StringBuilder(); sb.append(mathMethod.getReturnType().getSimpleName()); sb.append(" "); sb.append(methodName); sb.append("("); String sep = ""; for(Object o : params){ sb.append(sep); sb.append(o); sep=", "; } sb.append(") expected "); if (format != null){ sb.append(String.format(format, expL)); } else { sb.append(expected); } sb.append(" actual "); if (format != null){ sb.append(String.format(format, actL)); } else { sb.append(actual); } sb.append(" entries "); sb.append(Arrays.toString(entries)); String message = sb.toString(); - final boolean fatal = false; + final boolean fatal = true; if (fatal) { Assert.fail(message); } else { System.out.println(message); } } private static void callMethods(Method mathMethod, Method fastMethod, Object[] params, int[] entries) throws IllegalAccessException, InvocationTargetException { try { Object expected = mathMethod.invoke(mathMethod, params); Object actual = fastMethod.invoke(mathMethod, params); if (!expected.equals(actual)) { reportFailedResults(mathMethod, params, expected, actual, entries); } } catch (IllegalArgumentException e) { Assert.fail(mathMethod+" "+e); } } private static void setupMethodCall(Method mathMethod, Method fastMethod, Type[] types, Object[][] valueArrays) throws Exception { Object[] params = new Object[types.length]; int entry1 = 0; int[] entries = new int[types.length]; for(Object d : valueArrays[0]) { entry1++; params[0] = d; entries[0] = entry1; if (params.length > 1){ int entry2 = 0; for(Object d1 : valueArrays[1]) { entry2++; params[1] = d1; entries[1] = entry2; callMethods(mathMethod, fastMethod, params, entries); } } else { callMethods(mathMethod, fastMethod, params, entries); } } } @Parameters public static List<Object[]> data() throws Exception { String singleMethod = System.getProperty("testMethod"); List<Object[]> list = new ArrayList<Object[]>(); for(Method mathMethod : StrictMath.class.getDeclaredMethods()) { method: if (Modifier.isPublic(mathMethod.getModifiers())){// Only test public methods Type []types = mathMethod.getGenericParameterTypes(); if (types.length >=1) { // Only check methods with at least one parameter try { // Get the corresponding FastMath method Method fastMethod = FastMath.class.getDeclaredMethod(mathMethod.getName(), (Class[]) types); if (Modifier.isPublic(fastMethod.getModifiers())) { // It must be public too if (singleMethod != null && !fastMethod.getName().equals(singleMethod)) { break method; } Object [][] values = new Object[types.length][]; int index = 0; for(Type t : types) { if (t.equals(double.class)){ values[index]=DOUBLE_SPECIAL_VALUES; } else if (t.equals(float.class)) { values[index]=FLOAT_SPECIAL_VALUES; } else if (t.equals(long.class)) { values[index]=LONG_SPECIAL_VALUES; } else if (t.equals(int.class)) { values[index]=INT_SPECIAL_VALUES; } else { System.out.println("Cannot handle class "+t+" for "+mathMethod); break method; } index++; } // System.out.println(fastMethod); /* * The current implementation runs each method as a separate test. * Could be amended to run each value as a separate test */ list.add(new Object[]{mathMethod, fastMethod, types, values}); // setupMethodCall(mathMethod, fastMethod, params, data); } else { System.out.println("Cannot find public FastMath method corresponding to: "+mathMethod); } } catch (NoSuchMethodException e) { System.out.println("Cannot find FastMath method corresponding to: "+mathMethod); } } } } return list; } }
true
true
private static void reportFailedResults(Method mathMethod, Object[] params, Object expected, Object actual, int[] entries){ final String methodName = mathMethod.getName(); String format = null; long actL=0; long expL=0; if (expected instanceof Double) { Double exp = (Double) expected; Double act = (Double) actual; if (isNumber(exp) && isNumber(act) && exp != 0) { // show difference as hex actL = Double.doubleToLongBits(act); expL = Double.doubleToLongBits(exp); if (Math.abs(actL-expL)==1) { // Not 100% sure off-by-one errors are allowed everywhere, so only allow for these methods if (methodName.equals("toRadians") || methodName.equals("atan2")) { return; } } format = "%016x"; } } else if (expected instanceof Float ){ Float exp = (Float) expected; Float act = (Float) actual; if (isNumber(exp) && isNumber(act) && exp != 0) { // show difference as hex actL = Float.floatToIntBits(act); expL = Float.floatToIntBits(exp); format = "%08x"; } } StringBuilder sb = new StringBuilder(); sb.append(mathMethod.getReturnType().getSimpleName()); sb.append(" "); sb.append(methodName); sb.append("("); String sep = ""; for(Object o : params){ sb.append(sep); sb.append(o); sep=", "; } sb.append(") expected "); if (format != null){ sb.append(String.format(format, expL)); } else { sb.append(expected); } sb.append(" actual "); if (format != null){ sb.append(String.format(format, actL)); } else { sb.append(actual); } sb.append(" entries "); sb.append(Arrays.toString(entries)); String message = sb.toString(); final boolean fatal = false; if (fatal) { Assert.fail(message); } else { System.out.println(message); } }
private static void reportFailedResults(Method mathMethod, Object[] params, Object expected, Object actual, int[] entries){ final String methodName = mathMethod.getName(); String format = null; long actL=0; long expL=0; if (expected instanceof Double) { Double exp = (Double) expected; Double act = (Double) actual; if (isNumber(exp) && isNumber(act) && exp != 0) { // show difference as hex actL = Double.doubleToLongBits(act); expL = Double.doubleToLongBits(exp); if (Math.abs(actL-expL)==1) { // Not 100% sure off-by-one errors are allowed everywhere, so only allow for these methods if (methodName.equals("toRadians") || methodName.equals("atan2")) { return; } } format = "%016x"; } } else if (expected instanceof Float ){ Float exp = (Float) expected; Float act = (Float) actual; if (isNumber(exp) && isNumber(act) && exp != 0) { // show difference as hex actL = Float.floatToIntBits(act); expL = Float.floatToIntBits(exp); format = "%08x"; } } StringBuilder sb = new StringBuilder(); sb.append(mathMethod.getReturnType().getSimpleName()); sb.append(" "); sb.append(methodName); sb.append("("); String sep = ""; for(Object o : params){ sb.append(sep); sb.append(o); sep=", "; } sb.append(") expected "); if (format != null){ sb.append(String.format(format, expL)); } else { sb.append(expected); } sb.append(" actual "); if (format != null){ sb.append(String.format(format, actL)); } else { sb.append(actual); } sb.append(" entries "); sb.append(Arrays.toString(entries)); String message = sb.toString(); final boolean fatal = true; if (fatal) { Assert.fail(message); } else { System.out.println(message); } }
diff --git a/src/btwmod/protectedzones/mod_ProtectedZones.java b/src/btwmod/protectedzones/mod_ProtectedZones.java index 342b2f7..cb6de58 100644 --- a/src/btwmod/protectedzones/mod_ProtectedZones.java +++ b/src/btwmod/protectedzones/mod_ProtectedZones.java @@ -1,460 +1,460 @@ package btwmod.protectedzones; import java.util.ArrayList; import java.util.List; import java.util.Set; import net.minecraft.server.MinecraftServer; import net.minecraft.src.Block; import net.minecraft.src.BlockButton; import net.minecraft.src.BlockContainer; import net.minecraft.src.BlockRail; import net.minecraft.src.Entity; import net.minecraft.src.EntityHanging; import net.minecraft.src.EntityLiving; import net.minecraft.src.EntityMooshroom; import net.minecraft.src.EntityPlayer; import net.minecraft.src.EntityVillager; import net.minecraft.src.FCBlockBloodMoss; import net.minecraft.src.FCEntityCanvas; import net.minecraft.src.Facing; import net.minecraft.src.Item; import net.minecraft.src.ItemStack; import net.minecraft.src.MathHelper; import net.minecraft.src.ServerCommandManager; import net.minecraft.src.World; import net.minecraft.src.mod_FCBetterThanWolves; import btwmods.CommandsAPI; import btwmods.EntityAPI; import btwmods.IMod; import btwmods.ModLoader; import btwmods.PlayerAPI; import btwmods.Util; import btwmods.WorldAPI; import btwmods.entity.EntityEvent; import btwmods.entity.IEntityListener; import btwmods.events.APIEvent; import btwmods.io.Settings; import btwmods.player.IPlayerActionListener; import btwmods.player.PlayerActionEvent; import btwmods.player.PlayerBlockEvent; import btwmods.player.IPlayerBlockListener; import btwmods.util.Area; import btwmods.world.BlockEvent; import btwmods.world.BlockEventBase; import btwmods.world.IBlockListener; public class mod_ProtectedZones implements IMod, IPlayerBlockListener, IBlockListener, IPlayerActionListener, IEntityListener { public enum ACTION { DIG, ACTIVATE, EXPLODE, ATTACK_ENTITY, USE_ENTITY, ITEM_USE_CHECK_EDIT, IS_ENTITY_INVULNERABLE, BURN, IS_FLAMMABLE, FIRE_SPREAD_ATTEMPT, CAN_PUSH, TRAMPLE_FARMLAND }; private Settings data; private ProtectedZones[] zonesByDimension; private CommandZone commandZone; private MinecraftServer server; private ServerCommandManager commandManager; private Set ops; private boolean alwaysAllowOps = true; @Override public String getName() { return "Protected Zones"; } @Override public void init(Settings settings, Settings data) throws Exception { server = MinecraftServer.getServer(); commandManager = (ServerCommandManager)server.getCommandManager(); PlayerAPI.addListener(this); WorldAPI.addListener(this); EntityAPI.addListener(this); CommandsAPI.registerCommand(commandZone = new CommandZone(this), this); alwaysAllowOps = settings.getBoolean("alwaysAllowOps", alwaysAllowOps); ops = server.getConfigurationManager().getOps(); this.data = data; zonesByDimension = new ProtectedZones[server.worldServers.length]; for (int i = 0; i < server.worldServers.length; i++) { zonesByDimension[i] = new ProtectedZones(); } int zoneCount = data.getInt("count", 0); for (int i = 1; i <= zoneCount; i++) { if (data.hasSection("zone" + i) && !add(new ZoneSettings(data.getSectionAsSettings("zone" + i)))) { ModLoader.outputError(getName() + " failed to load zone " + i + " as it has a duplicate name or has invalid dimensions."); } } } @Override public void unload() throws Exception { PlayerAPI.removeListener(this); WorldAPI.removeListener(this); EntityAPI.removeListener(this); CommandsAPI.unregisterCommand(commandZone); } @Override public IMod getMod() { return this; } public boolean add(ZoneSettings zoneSettings) { return zoneSettings != null && zonesByDimension[Util.getWorldIndexFromDimension(zoneSettings.dimension)].add(zoneSettings); } public boolean remove(int dimension, String name) { return name != null && zonesByDimension[Util.getWorldIndexFromDimension(dimension)].removeZone(name); } public boolean remove(ZoneSettings zoneSettings) { return zoneSettings != null && remove(zoneSettings.dimension, zoneSettings.name); } public ZoneSettings get(int dimension, String name) { return zonesByDimension[Util.getWorldIndexFromDimension(dimension)].getZone(name); } public List<String> getZoneNames() { ArrayList names = new ArrayList(); for (ProtectedZones zones : zonesByDimension) { names.addAll(zones.getZoneNames()); } return names; } public List<String> getZoneNames(int dimension) { return zonesByDimension[Util.getWorldIndexFromDimension(dimension)].getZoneNames(); } public static boolean isProtectedBlockType(ACTION action, Block block) { if (action == ACTION.ACTIVATE) { if (block instanceof BlockRail) return false; if (block == Block.workbench) return false; if (block == mod_FCBetterThanWolves.fcAnvil) return false; if (block == Block.lever) return false; if (block instanceof BlockButton) return false; if (block == Block.enderChest) return false; if (block == Block.enchantmentTable) return false; if (block == Block.bed) return false; if (block == mod_FCBetterThanWolves.fcInfernalEnchanter) return false; } return true; } public static boolean isProtectedEntityType(ACTION action, Entity entity) { if (entity instanceof EntityLiving) { if (entity instanceof EntityVillager && action != ACTION.USE_ENTITY) return true; if (entity instanceof EntityMooshroom) return true; } else if (entity instanceof EntityHanging) { return true; } else if (entity instanceof FCEntityCanvas) { return true; } return false; } public boolean isOp(String username) { return ops.contains(username.trim().toLowerCase()); } public boolean isPlayerGloballyAllowed(String username) { return alwaysAllowOps && isOp(username); } protected boolean isProtectedEntity(ACTION action, EntityPlayer player, Entity entity, int x, int y, int z) { if (!isProtectedEntityType(action, entity)) return false; if (player != null && isPlayerGloballyAllowed(player.username)) return false; List<Area<ZoneSettings>> areas = zonesByDimension[Util.getWorldIndexFromDimension(entity.worldObj.provider.dimensionId)].get(x, y, z); for (Area<ZoneSettings> area : areas) { ZoneSettings settings = area.data; if (settings != null && settings.protectEntities != ZoneSettings.PERMISSION.OFF) { boolean isProtected = true; if (entity instanceof EntityMooshroom) { if (settings.allowMooshroom) isProtected = false; else if (player != null && action == ACTION.USE_ENTITY) { ItemStack heldItem = player.getHeldItem(); if (heldItem != null && heldItem.getItem() == Item.bowlEmpty) { isProtected = false; } } } else if (entity instanceof EntityVillager && settings.allowVillagers) { isProtected = false; } if (isProtected && player != null && settings.protectEntities == ZoneSettings.PERMISSION.WHITELIST && settings.isPlayerWhitelisted(player.username)) isProtected = false; if (isProtected) { if (settings.sendDebugMessages) commandManager.notifyAdmins(server, 0, "Protect " + entity.getEntityName() + " " + action + " " + x + "," + y + "," + z + (player == null ? "" : " from " + player.username + " by " + area.data.name + "#" + area.data.getAreaIndex(area)), new Object[0]); return true; } } } return false; } protected boolean isProtectedBlock(APIEvent event, ACTION action, EntityPlayer player, Block block, World world, int x, int y, int z) { if (!isProtectedBlockType(action, block)) return false; if (player != null && isPlayerGloballyAllowed(player.username)) return true; List<Area<ZoneSettings>> areas = zonesByDimension[Util.getWorldIndexFromDimension(world.provider.dimensionId)].get(x, y, z); for (Area<ZoneSettings> area : areas) { ZoneSettings settings = area.data; ItemStack itemStack = null; if (settings != null) { boolean isProtected = false; switch (action) { case EXPLODE: if (settings.protectExplosions) isProtected = true; break; case IS_FLAMMABLE: case BURN: case FIRE_SPREAD_ATTEMPT: if (settings.protectBurning) isProtected = true; break; case CAN_PUSH: // Protect against pistons from outside the area. if (event instanceof BlockEvent && settings.protectEdits != ZoneSettings.PERMISSION.OFF) { BlockEvent blockEvent = (BlockEvent)event; isProtected = true; // Check all areas for the ZoneSettings. for (Area zoneArea : area.data.areas) { if (zoneArea.isWithin(blockEvent.getPistonX(), blockEvent.getPistonY(), blockEvent.getPistonZ())) { isProtected = false; break; } } } break; default: if (settings.protectEdits != ZoneSettings.PERMISSION.OFF) { isProtected = true; // Allow immature bloodmoss to be destroyed. if ((action == ACTION.DIG) && block instanceof FCBlockBloodMoss && event instanceof BlockEventBase && (((BlockEventBase)event).getMetadata() & 7) < 7) { isProtected = false; } if (isProtected && player != null) { if (isProtected && action == ACTION.ACTIVATE) { if ((block == Block.doorWood || block == Block.trapdoor || block == Block.fenceGate) && settings.isPlayerAllowed(player.username, settings.allowDoors)) isProtected = false; else if (block instanceof BlockContainer && settings.isPlayerAllowed(player.username, settings.allowContainers)) isProtected = false; } if (isProtected && settings.allowOps && isOp(player.username)) isProtected = false; if (isProtected && settings.protectEdits == ZoneSettings.PERMISSION.WHITELIST && settings.isPlayerWhitelisted(player.username)) isProtected = false; } } break; } if (isProtected) { if (settings.sendDebugMessages) { - if (itemStack != null && event instanceof PlayerBlockEvent) { + if (itemStack == null && event instanceof PlayerBlockEvent) { itemStack = ((PlayerBlockEvent)event).getItemStack(); } String message = "Protect" + " " + action + (block == null ? "" : " " + block.getBlockName()) + (itemStack == null ? "" : " " + itemStack.getItemName()) + " " + x + "," + y + "," + z + " by " + area.data.name + "#" + area.data.getAreaIndex(area); if (player == null) commandManager.notifyAdmins(server, 0, message + (player == null ? "" : " from " + player.username), new Object[0]); else player.sendChatToPlayer(message); } return true; } } } return false; } @Override public void onPlayerBlockAction(PlayerBlockEvent event) { ACTION action = null; switch (event.getType()) { case ACTIVATION_ATTEMPT: action = ACTION.ACTIVATE; break; case ACTIVATED: break; case REMOVE_ATTEMPT: action = ACTION.DIG; break; case REMOVED: break; case ITEM_USE_ATTEMPT: break; case ITEM_USE_CHECK_EDIT: action = ACTION.ITEM_USE_CHECK_EDIT; break; case ITEM_USED: break; case GET_ENDERCHEST_INVENTORY: break; } if (action != null && isProtectedBlock(event, action, event.getPlayer(), event.getBlock(), event.getWorld(), event.getX(), event.getY(), event.getZ())) { if (event.getType() == PlayerBlockEvent.TYPE.ACTIVATION_ATTEMPT) event.markHandled(); else event.markNotAllowed(); } } @Override public void onBlockAction(BlockEvent event) { if (event.getType() == BlockEvent.TYPE.EXPLODE_ATTEMPT) { if (isProtectedBlock(event, ACTION.EXPLODE, null, event.getBlock(), event.getWorld(), event.getX(), event.getY(), event.getZ())) { event.markNotAllowed(); } } else if (event.getType() == BlockEvent.TYPE.BURN_ATTEMPT) { if (isProtectedBlock(event, ACTION.BURN, null, event.getBlock(), event.getWorld(), event.getX(), event.getY(), event.getZ())) { event.markNotAllowed(); } } else if (event.getType() == BlockEvent.TYPE.IS_FLAMMABLE_BLOCK) { if (isProtectedBlock(event, ACTION.IS_FLAMMABLE, null, event.getBlock(), event.getWorld(), event.getX(), event.getY(), event.getZ())) { event.markNotFlammable(); } } else if (event.getType() == BlockEvent.TYPE.FIRE_SPREAD_ATTEMPT) { if (isProtectedBlock(event, ACTION.FIRE_SPREAD_ATTEMPT, null, event.getBlock(), event.getWorld(), event.getX(), event.getY(), event.getZ())) { event.markNotAllowed(); } } else if (event.getType() == BlockEvent.TYPE.CAN_PUSH_BLOCK) { if (isProtectedBlock(event, ACTION.CAN_PUSH, null, event.getBlock(), event.getWorld(), event.getX(), event.getY(), event.getZ())) { event.markNotAllowed(); } else { int nextX = event.getX() + Facing.offsetsXForSide[event.getPistonOrientation()]; int nextY = event.getY() + Facing.offsetsYForSide[event.getPistonOrientation()]; int nextZ = event.getZ() + Facing.offsetsZForSide[event.getPistonOrientation()]; int nextBlockId = event.getWorld().getBlockId(nextX, nextY, nextZ); if (isProtectedBlock(event, ACTION.CAN_PUSH, null, nextBlockId > 0 ? Block.blocksList[nextBlockId] : null, event.getWorld(), nextX, nextY, nextZ)) { event.markNotAllowed(); } } } } @Override public void onPlayerAction(PlayerActionEvent event) { if (event.getType() == PlayerActionEvent.TYPE.PLAYER_USE_ENTITY_ATTEMPT) { if (isProtectedEntity(event.isLeftClick() ? ACTION.ATTACK_ENTITY : ACTION.USE_ENTITY, event.getPlayer(), event.getEntity(), MathHelper.floor_double(event.getEntity().posX), MathHelper.floor_double(event.getEntity().posY), MathHelper.floor_double(event.getEntity().posZ))) { event.markNotAllowed(); } } } @Override public void onEntityAction(EntityEvent event) { if (event.getType() == EntityEvent.TYPE.IS_ENTITY_INVULNERABLE) { if (isProtectedEntity(ACTION.IS_ENTITY_INVULNERABLE, null, event.getEntity(), event.getX(), event.getY(), event.getZ())) { event.markIsInvulnerable(); } } else if (event.getType() == EntityEvent.TYPE.TRAMPLE_FARMLAND_ATTEMPT) { if (isProtectedBlock(event, ACTION.TRAMPLE_FARMLAND, null, Block.tilledField, event.getWorld(), event.getBlockX(), event.getBlockY(), event.getBlockZ())) { event.markNotAllowed(); } } /*else if (event.getType() == EntityEvent.TYPE.EXPLODE_ATTEMPT) { if (isProtectedEntity(ACTION.EXPLODE, null, event.getEntity(), MathHelper.floor_double(event.getEntity().posX), MathHelper.floor_double(event.getEntity().posY), MathHelper.floor_double(event.getEntity().posZ))) { event.markNotAllowed(); } }*/ } public void saveAreas() { data.clear(); int count = 1; for (ProtectedZones zones : zonesByDimension) { for (ZoneSettings zoneSettings : zones.getZones()) { zoneSettings.saveToSettings(data, "zone" + count); count++; } } data.setInt("count", count); data.saveSettings(this); } }
true
true
protected boolean isProtectedBlock(APIEvent event, ACTION action, EntityPlayer player, Block block, World world, int x, int y, int z) { if (!isProtectedBlockType(action, block)) return false; if (player != null && isPlayerGloballyAllowed(player.username)) return true; List<Area<ZoneSettings>> areas = zonesByDimension[Util.getWorldIndexFromDimension(world.provider.dimensionId)].get(x, y, z); for (Area<ZoneSettings> area : areas) { ZoneSettings settings = area.data; ItemStack itemStack = null; if (settings != null) { boolean isProtected = false; switch (action) { case EXPLODE: if (settings.protectExplosions) isProtected = true; break; case IS_FLAMMABLE: case BURN: case FIRE_SPREAD_ATTEMPT: if (settings.protectBurning) isProtected = true; break; case CAN_PUSH: // Protect against pistons from outside the area. if (event instanceof BlockEvent && settings.protectEdits != ZoneSettings.PERMISSION.OFF) { BlockEvent blockEvent = (BlockEvent)event; isProtected = true; // Check all areas for the ZoneSettings. for (Area zoneArea : area.data.areas) { if (zoneArea.isWithin(blockEvent.getPistonX(), blockEvent.getPistonY(), blockEvent.getPistonZ())) { isProtected = false; break; } } } break; default: if (settings.protectEdits != ZoneSettings.PERMISSION.OFF) { isProtected = true; // Allow immature bloodmoss to be destroyed. if ((action == ACTION.DIG) && block instanceof FCBlockBloodMoss && event instanceof BlockEventBase && (((BlockEventBase)event).getMetadata() & 7) < 7) { isProtected = false; } if (isProtected && player != null) { if (isProtected && action == ACTION.ACTIVATE) { if ((block == Block.doorWood || block == Block.trapdoor || block == Block.fenceGate) && settings.isPlayerAllowed(player.username, settings.allowDoors)) isProtected = false; else if (block instanceof BlockContainer && settings.isPlayerAllowed(player.username, settings.allowContainers)) isProtected = false; } if (isProtected && settings.allowOps && isOp(player.username)) isProtected = false; if (isProtected && settings.protectEdits == ZoneSettings.PERMISSION.WHITELIST && settings.isPlayerWhitelisted(player.username)) isProtected = false; } } break; } if (isProtected) { if (settings.sendDebugMessages) { if (itemStack != null && event instanceof PlayerBlockEvent) { itemStack = ((PlayerBlockEvent)event).getItemStack(); } String message = "Protect" + " " + action + (block == null ? "" : " " + block.getBlockName()) + (itemStack == null ? "" : " " + itemStack.getItemName()) + " " + x + "," + y + "," + z + " by " + area.data.name + "#" + area.data.getAreaIndex(area); if (player == null) commandManager.notifyAdmins(server, 0, message + (player == null ? "" : " from " + player.username), new Object[0]); else player.sendChatToPlayer(message); } return true; } } } return false; }
protected boolean isProtectedBlock(APIEvent event, ACTION action, EntityPlayer player, Block block, World world, int x, int y, int z) { if (!isProtectedBlockType(action, block)) return false; if (player != null && isPlayerGloballyAllowed(player.username)) return true; List<Area<ZoneSettings>> areas = zonesByDimension[Util.getWorldIndexFromDimension(world.provider.dimensionId)].get(x, y, z); for (Area<ZoneSettings> area : areas) { ZoneSettings settings = area.data; ItemStack itemStack = null; if (settings != null) { boolean isProtected = false; switch (action) { case EXPLODE: if (settings.protectExplosions) isProtected = true; break; case IS_FLAMMABLE: case BURN: case FIRE_SPREAD_ATTEMPT: if (settings.protectBurning) isProtected = true; break; case CAN_PUSH: // Protect against pistons from outside the area. if (event instanceof BlockEvent && settings.protectEdits != ZoneSettings.PERMISSION.OFF) { BlockEvent blockEvent = (BlockEvent)event; isProtected = true; // Check all areas for the ZoneSettings. for (Area zoneArea : area.data.areas) { if (zoneArea.isWithin(blockEvent.getPistonX(), blockEvent.getPistonY(), blockEvent.getPistonZ())) { isProtected = false; break; } } } break; default: if (settings.protectEdits != ZoneSettings.PERMISSION.OFF) { isProtected = true; // Allow immature bloodmoss to be destroyed. if ((action == ACTION.DIG) && block instanceof FCBlockBloodMoss && event instanceof BlockEventBase && (((BlockEventBase)event).getMetadata() & 7) < 7) { isProtected = false; } if (isProtected && player != null) { if (isProtected && action == ACTION.ACTIVATE) { if ((block == Block.doorWood || block == Block.trapdoor || block == Block.fenceGate) && settings.isPlayerAllowed(player.username, settings.allowDoors)) isProtected = false; else if (block instanceof BlockContainer && settings.isPlayerAllowed(player.username, settings.allowContainers)) isProtected = false; } if (isProtected && settings.allowOps && isOp(player.username)) isProtected = false; if (isProtected && settings.protectEdits == ZoneSettings.PERMISSION.WHITELIST && settings.isPlayerWhitelisted(player.username)) isProtected = false; } } break; } if (isProtected) { if (settings.sendDebugMessages) { if (itemStack == null && event instanceof PlayerBlockEvent) { itemStack = ((PlayerBlockEvent)event).getItemStack(); } String message = "Protect" + " " + action + (block == null ? "" : " " + block.getBlockName()) + (itemStack == null ? "" : " " + itemStack.getItemName()) + " " + x + "," + y + "," + z + " by " + area.data.name + "#" + area.data.getAreaIndex(area); if (player == null) commandManager.notifyAdmins(server, 0, message + (player == null ? "" : " from " + player.username), new Object[0]); else player.sendChatToPlayer(message); } return true; } } } return false; }
diff --git a/src/com/android/packageinstaller/PackageInstallerActivity.java b/src/com/android/packageinstaller/PackageInstallerActivity.java index d0c50fc9..4a6db210 100644 --- a/src/com/android/packageinstaller/PackageInstallerActivity.java +++ b/src/com/android/packageinstaller/PackageInstallerActivity.java @@ -1,689 +1,690 @@ /* ** ** Copyright 2007, The Android Open Source 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. */ package com.android.packageinstaller; import android.app.Activity; import android.app.ActivityManagerNative; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageUserState; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.PackageParser; import android.content.pm.VerificationParams; import android.graphics.Rect; import android.net.Uri; import android.os.Bundle; import android.provider.Settings; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AppSecurityPermissions; import android.widget.Button; import android.widget.ScrollView; import android.widget.TabHost; import android.widget.TabWidget; import android.widget.TextView; import java.io.File; import java.util.ArrayList; /* * This activity is launched when a new application is installed via side loading * The package is first parsed and the user is notified of parse errors via a dialog. * If the package is successfully parsed, the user is notified to turn on the install unknown * applications setting. A memory check is made at this point and the user is notified of out * of memory conditions if any. If the package is already existing on the device, * a confirmation dialog (to replace the existing package) is presented to the user. * Based on the user response the package is then installed by launching InstallAppConfirm * sub activity. All state transitions are handled in this activity */ public class PackageInstallerActivity extends Activity implements OnCancelListener, OnClickListener { private static final String TAG = "PackageInstaller"; private Uri mPackageURI; private Uri mOriginatingURI; private Uri mReferrerURI; private int mOriginatingUid = VerificationParams.NO_UID; private boolean localLOGV = false; PackageManager mPm; PackageInfo mPkgInfo; ApplicationInfo mSourceInfo; // ApplicationInfo object primarily used for already existing applications private ApplicationInfo mAppInfo = null; // View for install progress View mInstallConfirm; // Buttons to indicate user acceptance private Button mOk; private Button mCancel; CaffeinatedScrollView mScrollView = null; private boolean mOkCanInstall = false; static final String PREFS_ALLOWED_SOURCES = "allowed_sources"; // Dialog identifiers used in showDialog private static final int DLG_BASE = 0; private static final int DLG_UNKNOWN_APPS = DLG_BASE + 1; private static final int DLG_PACKAGE_ERROR = DLG_BASE + 2; private static final int DLG_OUT_OF_SPACE = DLG_BASE + 3; private static final int DLG_INSTALL_ERROR = DLG_BASE + 4; private static final int DLG_ALLOW_SOURCE = DLG_BASE + 5; /** * This is a helper class that implements the management of tabs and all * details of connecting a ViewPager with associated TabHost. It relies on a * trick. Normally a tab host has a simple API for supplying a View or * Intent that each tab will show. This is not sufficient for switching * between pages. So instead we make the content part of the tab host * 0dp high (it is not shown) and the TabsAdapter supplies its own dummy * view to show as the tab content. It listens to changes in tabs, and takes * care of switch to the correct paged in the ViewPager whenever the selected * tab changes. */ public static class TabsAdapter extends PagerAdapter implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener { private final Context mContext; private final TabHost mTabHost; private final ViewPager mViewPager; private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>(); private final Rect mTempRect = new Rect(); static final class TabInfo { private final String tag; private final View view; TabInfo(String _tag, View _view) { tag = _tag; view = _view; } } static class DummyTabFactory implements TabHost.TabContentFactory { private final Context mContext; public DummyTabFactory(Context context) { mContext = context; } @Override public View createTabContent(String tag) { View v = new View(mContext); v.setMinimumWidth(0); v.setMinimumHeight(0); return v; } } public TabsAdapter(Activity activity, TabHost tabHost, ViewPager pager) { mContext = activity; mTabHost = tabHost; mViewPager = pager; mTabHost.setOnTabChangedListener(this); mViewPager.setAdapter(this); mViewPager.setOnPageChangeListener(this); } public void addTab(TabHost.TabSpec tabSpec, View view) { tabSpec.setContent(new DummyTabFactory(mContext)); String tag = tabSpec.getTag(); TabInfo info = new TabInfo(tag, view); mTabs.add(info); mTabHost.addTab(tabSpec); notifyDataSetChanged(); } @Override public int getCount() { return mTabs.size(); } @Override public Object instantiateItem(ViewGroup container, int position) { View view = mTabs.get(position).view; container.addView(view); return view; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View)object); } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public void onTabChanged(String tabId) { int position = mTabHost.getCurrentTab(); mViewPager.setCurrentItem(position); } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { // Unfortunately when TabHost changes the current tab, it kindly // also takes care of putting focus on it when not in touch mode. // The jerk. // This hack tries to prevent this from pulling focus out of our // ViewPager. TabWidget widget = mTabHost.getTabWidget(); int oldFocusability = widget.getDescendantFocusability(); widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS); mTabHost.setCurrentTab(position); widget.setDescendantFocusability(oldFocusability); // Scroll the current tab into visibility if needed. View tab = widget.getChildTabViewAt(position); mTempRect.set(tab.getLeft(), tab.getTop(), tab.getRight(), tab.getBottom()); widget.requestRectangleOnScreen(mTempRect, false); // Make sure the scrollbars are visible for a moment after selection final View contentView = mTabs.get(position).view; if (contentView instanceof CaffeinatedScrollView) { ((CaffeinatedScrollView) contentView).awakenScrollBars(); } } @Override public void onPageScrollStateChanged(int state) { } } private void startInstallConfirm() { TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost); tabHost.setup(); ViewPager viewPager = (ViewPager)findViewById(R.id.pager); TabsAdapter adapter = new TabsAdapter(this, tabHost, viewPager); boolean permVisible = false; mScrollView = null; mOkCanInstall = false; int msg = 0; if (mPkgInfo != null) { AppSecurityPermissions perms = new AppSecurityPermissions(this, mPkgInfo); final int NP = perms.getPermissionCount(AppSecurityPermissions.WHICH_PERSONAL); final int ND = perms.getPermissionCount(AppSecurityPermissions.WHICH_DEVICE); if (mAppInfo != null) { msg = (mAppInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0 ? R.string.install_confirm_question_update_system : R.string.install_confirm_question_update; mScrollView = new CaffeinatedScrollView(this); mScrollView.setFillViewport(true); if (perms.getPermissionCount(AppSecurityPermissions.WHICH_NEW) > 0) { permVisible = true; mScrollView.addView(perms.getPermissionsView( AppSecurityPermissions.WHICH_NEW)); } else { LayoutInflater inflater = (LayoutInflater)getSystemService( Context.LAYOUT_INFLATER_SERVICE); TextView label = (TextView)inflater.inflate(R.layout.label, null); label.setText(R.string.no_new_perms); mScrollView.addView(label); } adapter.addTab(tabHost.newTabSpec("new").setIndicator( getText(R.string.newPerms)), mScrollView); } else { findViewById(R.id.tabscontainer).setVisibility(View.GONE); findViewById(R.id.divider).setVisibility(View.VISIBLE); } if (NP > 0 || ND > 0) { permVisible = true; LayoutInflater inflater = (LayoutInflater)getSystemService( Context.LAYOUT_INFLATER_SERVICE); View root = inflater.inflate(R.layout.permissions_list, null); if (mScrollView == null) { mScrollView = (CaffeinatedScrollView)root.findViewById(R.id.scrollview); } if (NP > 0) { ((ViewGroup)root.findViewById(R.id.privacylist)).addView( perms.getPermissionsView(AppSecurityPermissions.WHICH_PERSONAL)); } else { root.findViewById(R.id.privacylist).setVisibility(View.GONE); } if (ND > 0) { ((ViewGroup)root.findViewById(R.id.devicelist)).addView( perms.getPermissionsView(AppSecurityPermissions.WHICH_DEVICE)); } else { root.findViewById(R.id.devicelist).setVisibility(View.GONE); } adapter.addTab(tabHost.newTabSpec("all").setIndicator( getText(R.string.allPerms)), root); } } if (!permVisible) { - if (msg == 0) { - if (mAppInfo != null) { - // This is an update to an application, but there are no - // permissions at all. - msg = (mAppInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0 - ? R.string.install_confirm_question_update_system_no_perms - : R.string.install_confirm_question_update_no_perms; - } else { - // This is a new application with no permissions. - msg = R.string.install_confirm_question_no_perms; - } + if (mAppInfo != null) { + // This is an update to an application, but there are no + // permissions at all. + msg = (mAppInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0 + ? R.string.install_confirm_question_update_system_no_perms + : R.string.install_confirm_question_update_no_perms; + } else { + // This is a new application with no permissions. + msg = R.string.install_confirm_question_no_perms; } tabHost.setVisibility(View.GONE); + findViewById(R.id.filler).setVisibility(View.VISIBLE); + findViewById(R.id.divider).setVisibility(View.GONE); + mScrollView = null; } if (msg != 0) { ((TextView)findViewById(R.id.install_confirm_question)).setText(msg); } mInstallConfirm.setVisibility(View.VISIBLE); mOk = (Button)findViewById(R.id.ok_button); mCancel = (Button)findViewById(R.id.cancel_button); mOk.setOnClickListener(this); mCancel.setOnClickListener(this); if (mScrollView == null) { // There is nothing to scroll view, so the ok button is immediately // set to install. mOk.setText(R.string.install); mOkCanInstall = true; } else { mScrollView.setFullScrollAction(new Runnable() { @Override public void run() { mOk.setText(R.string.install); mOkCanInstall = true; } }); } } private void showDialogInner(int id) { // TODO better fix for this? Remove dialog so that it gets created again removeDialog(id); showDialog(id); } @Override public Dialog onCreateDialog(int id, Bundle bundle) { switch (id) { case DLG_UNKNOWN_APPS: return new AlertDialog.Builder(this) .setTitle(R.string.unknown_apps_dlg_title) .setMessage(R.string.unknown_apps_dlg_text) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Log.i(TAG, "Finishing off activity so that user can navigate to settings manually"); finish(); }}) .setPositiveButton(R.string.settings, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Log.i(TAG, "Launching settings"); launchSettingsAppAndFinish(); } }) .setOnCancelListener(this) .create(); case DLG_PACKAGE_ERROR : return new AlertDialog.Builder(this) .setTitle(R.string.Parse_error_dlg_title) .setMessage(R.string.Parse_error_dlg_text) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }) .setOnCancelListener(this) .create(); case DLG_OUT_OF_SPACE: // Guaranteed not to be null. will default to package name if not set by app CharSequence appTitle = mPm.getApplicationLabel(mPkgInfo.applicationInfo); String dlgText = getString(R.string.out_of_space_dlg_text, appTitle.toString()); return new AlertDialog.Builder(this) .setTitle(R.string.out_of_space_dlg_title) .setMessage(dlgText) .setPositiveButton(R.string.manage_applications, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { //launch manage applications Intent intent = new Intent("android.intent.action.MANAGE_PACKAGE_STORAGE"); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); finish(); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Log.i(TAG, "Canceling installation"); finish(); } }) .setOnCancelListener(this) .create(); case DLG_INSTALL_ERROR : // Guaranteed not to be null. will default to package name if not set by app CharSequence appTitle1 = mPm.getApplicationLabel(mPkgInfo.applicationInfo); String dlgText1 = getString(R.string.install_failed_msg, appTitle1.toString()); return new AlertDialog.Builder(this) .setTitle(R.string.install_failed) .setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }) .setMessage(dlgText1) .setOnCancelListener(this) .create(); case DLG_ALLOW_SOURCE: CharSequence appTitle2 = mPm.getApplicationLabel(mSourceInfo); String dlgText2 = getString(R.string.allow_source_dlg_text, appTitle2.toString()); return new AlertDialog.Builder(this) .setTitle(R.string.allow_source_dlg_title) .setMessage(dlgText2) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { setResult(RESULT_CANCELED); finish(); }}) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { SharedPreferences prefs = getSharedPreferences(PREFS_ALLOWED_SOURCES, Context.MODE_PRIVATE); prefs.edit().putBoolean(mSourceInfo.packageName, true).apply(); startInstallConfirm(); } }) .setOnCancelListener(this) .create(); } return null; } private void launchSettingsAppAndFinish() { // Create an intent to launch SettingsTwo activity Intent launchSettingsIntent = new Intent(Settings.ACTION_SECURITY_SETTINGS); launchSettingsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(launchSettingsIntent); finish(); } private boolean isInstallingUnknownAppsAllowed() { return Settings.Global.getInt(getContentResolver(), Settings.Global.INSTALL_NON_MARKET_APPS, 0) > 0; } private void initiateInstall() { String pkgName = mPkgInfo.packageName; // Check if there is already a package on the device with this name // but it has been renamed to something else. String[] oldName = mPm.canonicalToCurrentPackageNames(new String[] { pkgName }); if (oldName != null && oldName.length > 0 && oldName[0] != null) { pkgName = oldName[0]; mPkgInfo.packageName = pkgName; mPkgInfo.applicationInfo.packageName = pkgName; } // Check if package is already installed. display confirmation dialog if replacing pkg try { // This is a little convoluted because we want to get all uninstalled // apps, but this may include apps with just data, and if it is just // data we still want to count it as "installed". mAppInfo = mPm.getApplicationInfo(pkgName, PackageManager.GET_UNINSTALLED_PACKAGES); if ((mAppInfo.flags&ApplicationInfo.FLAG_INSTALLED) == 0) { mAppInfo = null; } } catch (NameNotFoundException e) { mAppInfo = null; } startInstallConfirm(); } void setPmResult(int pmResult) { Intent result = new Intent(); result.putExtra(Intent.EXTRA_INSTALL_RESULT, pmResult); setResult(pmResult == PackageManager.INSTALL_SUCCEEDED ? RESULT_OK : RESULT_FIRST_USER, result); } @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); // get intent information final Intent intent = getIntent(); mPackageURI = intent.getData(); mOriginatingURI = intent.getParcelableExtra(Intent.EXTRA_ORIGINATING_URI); mReferrerURI = intent.getParcelableExtra(Intent.EXTRA_REFERRER); mPm = getPackageManager(); final String scheme = mPackageURI.getScheme(); if (scheme != null && !"file".equals(scheme) && !"package".equals(scheme)) { Log.w(TAG, "Unsupported scheme " + scheme); setPmResult(PackageManager.INSTALL_FAILED_INVALID_URI); return; } final PackageUtil.AppSnippet as; if ("package".equals(mPackageURI.getScheme())) { try { mPkgInfo = mPm.getPackageInfo(mPackageURI.getSchemeSpecificPart(), PackageManager.GET_PERMISSIONS | PackageManager.GET_UNINSTALLED_PACKAGES); } catch (NameNotFoundException e) { } if (mPkgInfo == null) { Log.w(TAG, "Requested package " + mPackageURI.getScheme() + " not available. Discontinuing installation"); showDialogInner(DLG_PACKAGE_ERROR); setPmResult(PackageManager.INSTALL_FAILED_INVALID_APK); return; } as = new PackageUtil.AppSnippet(mPm.getApplicationLabel(mPkgInfo.applicationInfo), mPm.getApplicationIcon(mPkgInfo.applicationInfo)); } else { final File sourceFile = new File(mPackageURI.getPath()); PackageParser.Package parsed = PackageUtil.getPackageInfo(sourceFile); // Check for parse errors if (parsed == null) { Log.w(TAG, "Parse error when parsing manifest. Discontinuing installation"); showDialogInner(DLG_PACKAGE_ERROR); setPmResult(PackageManager.INSTALL_FAILED_INVALID_APK); return; } mPkgInfo = PackageParser.generatePackageInfo(parsed, null, PackageManager.GET_PERMISSIONS, 0, 0, null, new PackageUserState()); as = PackageUtil.getAppSnippet(this, mPkgInfo.applicationInfo, sourceFile); } //set view setContentView(R.layout.install_start); mInstallConfirm = findViewById(R.id.install_confirm_panel); mInstallConfirm.setVisibility(View.INVISIBLE); PackageUtil.initSnippetForNewApp(this, as, R.id.app_snippet); mOriginatingUid = getOriginatingUid(intent); // Deal with install source. String callerPackage = getCallingPackage(); if (callerPackage != null && intent.getBooleanExtra( Intent.EXTRA_NOT_UNKNOWN_SOURCE, false)) { try { mSourceInfo = mPm.getApplicationInfo(callerPackage, 0); if (mSourceInfo != null) { if ((mSourceInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { // System apps don't need to be approved. initiateInstall(); return; } /* for now this is disabled, since the user would need to * have enabled the global "unknown sources" setting in the * first place in order to get here. SharedPreferences prefs = getSharedPreferences(PREFS_ALLOWED_SOURCES, Context.MODE_PRIVATE); if (prefs.getBoolean(mSourceInfo.packageName, false)) { // User has already allowed this one. initiateInstall(); return; } //ask user to enable setting first showDialogInner(DLG_ALLOW_SOURCE); return; */ } } catch (NameNotFoundException e) { } } // Check unknown sources. if (!isInstallingUnknownAppsAllowed()) { //ask user to enable setting first showDialogInner(DLG_UNKNOWN_APPS); return; } initiateInstall(); } /** Get the ApplicationInfo for the calling package, if available */ private ApplicationInfo getSourceInfo() { String callingPackage = getCallingPackage(); if (callingPackage != null) { try { return mPm.getApplicationInfo(callingPackage, 0); } catch (NameNotFoundException ex) { // ignore } } return null; } /** Get the originating uid if possible, or VerificationParams.NO_UID if not available */ private int getOriginatingUid(Intent intent) { // The originating uid from the intent. We only trust/use this if it comes from a // system application int uidFromIntent = intent.getIntExtra(Intent.EXTRA_ORIGINATING_UID, VerificationParams.NO_UID); // Get the source info from the calling package, if available. This will be the // definitive calling package, but it only works if the intent was started using // startActivityForResult, ApplicationInfo sourceInfo = getSourceInfo(); if (sourceInfo != null) { if (uidFromIntent != VerificationParams.NO_UID && (mSourceInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { return uidFromIntent; } // We either didn't get a uid in the intent, or we don't trust it. Use the // uid of the calling package instead. return sourceInfo.uid; } // We couldn't get the specific calling package. Let's get the uid instead int callingUid; try { callingUid = ActivityManagerNative.getDefault() .getLaunchedFromUid(getActivityToken()); } catch (android.os.RemoteException ex) { Log.w(TAG, "Could not determine the launching uid."); // nothing else we can do return VerificationParams.NO_UID; } // If we got a uid from the intent, we need to verify that the caller is a // system package before we use it if (uidFromIntent != VerificationParams.NO_UID) { String[] callingPackages = mPm.getPackagesForUid(callingUid); if (callingPackages != null) { for (String packageName: callingPackages) { try { ApplicationInfo applicationInfo = mPm.getApplicationInfo(packageName, 0); if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { return uidFromIntent; } } catch (NameNotFoundException ex) { // ignore it, and try the next package } } } } // We either didn't get a uid from the intent, or we don't trust it. Use the // calling uid instead. return callingUid; } // Generic handling when pressing back key public void onCancel(DialogInterface dialog) { finish(); } public void onClick(View v) { if(v == mOk) { if (mOkCanInstall || mScrollView == null) { // Start subactivity to actually install the application Intent newIntent = new Intent(); newIntent.putExtra(PackageUtil.INTENT_ATTR_APPLICATION_INFO, mPkgInfo.applicationInfo); newIntent.setData(mPackageURI); newIntent.setClass(this, InstallAppProgress.class); String installerPackageName = getIntent().getStringExtra( Intent.EXTRA_INSTALLER_PACKAGE_NAME); if (mOriginatingURI != null) { newIntent.putExtra(Intent.EXTRA_ORIGINATING_URI, mOriginatingURI); } if (mReferrerURI != null) { newIntent.putExtra(Intent.EXTRA_REFERRER, mReferrerURI); } if (mOriginatingUid != VerificationParams.NO_UID) { newIntent.putExtra(Intent.EXTRA_ORIGINATING_UID, mOriginatingUid); } if (installerPackageName != null) { newIntent.putExtra(Intent.EXTRA_INSTALLER_PACKAGE_NAME, installerPackageName); } if (getIntent().getBooleanExtra(Intent.EXTRA_RETURN_RESULT, false)) { newIntent.putExtra(Intent.EXTRA_RETURN_RESULT, true); newIntent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT); } if(localLOGV) Log.i(TAG, "downloaded app uri="+mPackageURI); startActivity(newIntent); finish(); } else { mScrollView.pageScroll(View.FOCUS_DOWN); } } else if(v == mCancel) { // Cancel and finish setResult(RESULT_CANCELED); finish(); } } }
false
true
private void startInstallConfirm() { TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost); tabHost.setup(); ViewPager viewPager = (ViewPager)findViewById(R.id.pager); TabsAdapter adapter = new TabsAdapter(this, tabHost, viewPager); boolean permVisible = false; mScrollView = null; mOkCanInstall = false; int msg = 0; if (mPkgInfo != null) { AppSecurityPermissions perms = new AppSecurityPermissions(this, mPkgInfo); final int NP = perms.getPermissionCount(AppSecurityPermissions.WHICH_PERSONAL); final int ND = perms.getPermissionCount(AppSecurityPermissions.WHICH_DEVICE); if (mAppInfo != null) { msg = (mAppInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0 ? R.string.install_confirm_question_update_system : R.string.install_confirm_question_update; mScrollView = new CaffeinatedScrollView(this); mScrollView.setFillViewport(true); if (perms.getPermissionCount(AppSecurityPermissions.WHICH_NEW) > 0) { permVisible = true; mScrollView.addView(perms.getPermissionsView( AppSecurityPermissions.WHICH_NEW)); } else { LayoutInflater inflater = (LayoutInflater)getSystemService( Context.LAYOUT_INFLATER_SERVICE); TextView label = (TextView)inflater.inflate(R.layout.label, null); label.setText(R.string.no_new_perms); mScrollView.addView(label); } adapter.addTab(tabHost.newTabSpec("new").setIndicator( getText(R.string.newPerms)), mScrollView); } else { findViewById(R.id.tabscontainer).setVisibility(View.GONE); findViewById(R.id.divider).setVisibility(View.VISIBLE); } if (NP > 0 || ND > 0) { permVisible = true; LayoutInflater inflater = (LayoutInflater)getSystemService( Context.LAYOUT_INFLATER_SERVICE); View root = inflater.inflate(R.layout.permissions_list, null); if (mScrollView == null) { mScrollView = (CaffeinatedScrollView)root.findViewById(R.id.scrollview); } if (NP > 0) { ((ViewGroup)root.findViewById(R.id.privacylist)).addView( perms.getPermissionsView(AppSecurityPermissions.WHICH_PERSONAL)); } else { root.findViewById(R.id.privacylist).setVisibility(View.GONE); } if (ND > 0) { ((ViewGroup)root.findViewById(R.id.devicelist)).addView( perms.getPermissionsView(AppSecurityPermissions.WHICH_DEVICE)); } else { root.findViewById(R.id.devicelist).setVisibility(View.GONE); } adapter.addTab(tabHost.newTabSpec("all").setIndicator( getText(R.string.allPerms)), root); } } if (!permVisible) { if (msg == 0) { if (mAppInfo != null) { // This is an update to an application, but there are no // permissions at all. msg = (mAppInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0 ? R.string.install_confirm_question_update_system_no_perms : R.string.install_confirm_question_update_no_perms; } else { // This is a new application with no permissions. msg = R.string.install_confirm_question_no_perms; } } tabHost.setVisibility(View.GONE); } if (msg != 0) { ((TextView)findViewById(R.id.install_confirm_question)).setText(msg); } mInstallConfirm.setVisibility(View.VISIBLE); mOk = (Button)findViewById(R.id.ok_button); mCancel = (Button)findViewById(R.id.cancel_button); mOk.setOnClickListener(this); mCancel.setOnClickListener(this); if (mScrollView == null) { // There is nothing to scroll view, so the ok button is immediately // set to install. mOk.setText(R.string.install); mOkCanInstall = true; } else { mScrollView.setFullScrollAction(new Runnable() { @Override public void run() { mOk.setText(R.string.install); mOkCanInstall = true; } }); } }
private void startInstallConfirm() { TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost); tabHost.setup(); ViewPager viewPager = (ViewPager)findViewById(R.id.pager); TabsAdapter adapter = new TabsAdapter(this, tabHost, viewPager); boolean permVisible = false; mScrollView = null; mOkCanInstall = false; int msg = 0; if (mPkgInfo != null) { AppSecurityPermissions perms = new AppSecurityPermissions(this, mPkgInfo); final int NP = perms.getPermissionCount(AppSecurityPermissions.WHICH_PERSONAL); final int ND = perms.getPermissionCount(AppSecurityPermissions.WHICH_DEVICE); if (mAppInfo != null) { msg = (mAppInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0 ? R.string.install_confirm_question_update_system : R.string.install_confirm_question_update; mScrollView = new CaffeinatedScrollView(this); mScrollView.setFillViewport(true); if (perms.getPermissionCount(AppSecurityPermissions.WHICH_NEW) > 0) { permVisible = true; mScrollView.addView(perms.getPermissionsView( AppSecurityPermissions.WHICH_NEW)); } else { LayoutInflater inflater = (LayoutInflater)getSystemService( Context.LAYOUT_INFLATER_SERVICE); TextView label = (TextView)inflater.inflate(R.layout.label, null); label.setText(R.string.no_new_perms); mScrollView.addView(label); } adapter.addTab(tabHost.newTabSpec("new").setIndicator( getText(R.string.newPerms)), mScrollView); } else { findViewById(R.id.tabscontainer).setVisibility(View.GONE); findViewById(R.id.divider).setVisibility(View.VISIBLE); } if (NP > 0 || ND > 0) { permVisible = true; LayoutInflater inflater = (LayoutInflater)getSystemService( Context.LAYOUT_INFLATER_SERVICE); View root = inflater.inflate(R.layout.permissions_list, null); if (mScrollView == null) { mScrollView = (CaffeinatedScrollView)root.findViewById(R.id.scrollview); } if (NP > 0) { ((ViewGroup)root.findViewById(R.id.privacylist)).addView( perms.getPermissionsView(AppSecurityPermissions.WHICH_PERSONAL)); } else { root.findViewById(R.id.privacylist).setVisibility(View.GONE); } if (ND > 0) { ((ViewGroup)root.findViewById(R.id.devicelist)).addView( perms.getPermissionsView(AppSecurityPermissions.WHICH_DEVICE)); } else { root.findViewById(R.id.devicelist).setVisibility(View.GONE); } adapter.addTab(tabHost.newTabSpec("all").setIndicator( getText(R.string.allPerms)), root); } } if (!permVisible) { if (mAppInfo != null) { // This is an update to an application, but there are no // permissions at all. msg = (mAppInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0 ? R.string.install_confirm_question_update_system_no_perms : R.string.install_confirm_question_update_no_perms; } else { // This is a new application with no permissions. msg = R.string.install_confirm_question_no_perms; } tabHost.setVisibility(View.GONE); findViewById(R.id.filler).setVisibility(View.VISIBLE); findViewById(R.id.divider).setVisibility(View.GONE); mScrollView = null; } if (msg != 0) { ((TextView)findViewById(R.id.install_confirm_question)).setText(msg); } mInstallConfirm.setVisibility(View.VISIBLE); mOk = (Button)findViewById(R.id.ok_button); mCancel = (Button)findViewById(R.id.cancel_button); mOk.setOnClickListener(this); mCancel.setOnClickListener(this); if (mScrollView == null) { // There is nothing to scroll view, so the ok button is immediately // set to install. mOk.setText(R.string.install); mOkCanInstall = true; } else { mScrollView.setFullScrollAction(new Runnable() { @Override public void run() { mOk.setText(R.string.install); mOkCanInstall = true; } }); } }
diff --git a/gpswinggui/src/main/java/org/geopublishing/geopublisher/CliOptions.java b/gpswinggui/src/main/java/org/geopublishing/geopublisher/CliOptions.java index 254139c2..4972d09c 100644 --- a/gpswinggui/src/main/java/org/geopublishing/geopublisher/CliOptions.java +++ b/gpswinggui/src/main/java/org/geopublishing/geopublisher/CliOptions.java @@ -1,301 +1,304 @@ package org.geopublishing.geopublisher; import java.awt.GraphicsEnvironment; import java.io.File; import javax.swing.SwingUtilities; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import org.geopublishing.atlasViewer.AtlasConfig; import org.geopublishing.geopublisher.export.JarExportUtil; import org.geopublishing.geopublisher.swing.GeopublisherGUI; import skrueger.versionnumber.ReleaseUtil; import skrueger.versionnumber.ReleaseUtil.License; /** * This class manages all the command line options of Geopublisher. */ public class CliOptions extends Options { public static final String VERSION = "v"; public static final String HELP = "h"; public static final String EXPORT = "e"; public static final String AWCFOLDER = "a"; public static final String FORCE = "f"; public static final String DISK = "d"; public static final String JWS = "j"; static final String ZIPDISK = "z"; private static final String LICENSE = "l"; private static final Logger log = Logger.getLogger(CliOptions.class); public static enum Errors { PARSEEXCEPTION(1), AWCPARAM_MISSING(2), AWCPARAM_ILLEGAL(3), EXPORTDIR_MISSING( 4), EXPORTDIR_ILLEGAL(5), EXPORTDIR_NOTEMPTYNOFORCE(6), EXPORT_FAILED( 7), NOHEAD(8); private final int errCode; Errors(int errCode) { this.errCode = errCode; }; public boolean equals(int errCode) { return getErrCode() == errCode; } public int getErrCode() { return errCode; } } public CliOptions() { addOption(new Option(HELP, "help", false, "print this message")); addOption(new Option(VERSION, "verbose", false, "print verbose information while running")); addOption(new Option(LICENSE, "license", false, "print license information")); Option optAwc = new Option(AWCFOLDER, "atlas", true, "folder to load the atlas from (atlas.gpa)"); optAwc.setArgName("srcDir"); addOption(optAwc); Option optExport = new Option( EXPORT, "export", true, "exports an atlas to a given directory, combine this option with -f / -d and/or -j."); optExport.setArgName("dstDir"); addOption(optExport); Option diskOption = new Option(DISK, "disk", false, "create DISK version of atlas when exporting"); addOption(diskOption); addOption(new Option(JWS, "jws", false, "create JavaWebStart version of atlas when exporting")); addOption(new Option(ZIPDISK, "zipdisk", false, "zip the DISK folder after export")); addOption(new Option(FORCE, "force", false, "overwrite any existing files during export")); } public CommandLine parse(String[] args) throws ParseException { CommandLineParser parser = new PosixParser(); return parser.parse(this, args); } public void printHelp() { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("geopublisher", this); } /** * @return <code>-1</code> means the application GUI is open and the program * should not exit. <code>0</code> the program exits normally after * successful execution. */ public static int performArgs(final String[] args) { /** Any number >= 0 will result in exit **/ boolean exitAfterInterpret = false; CliOptions.Errors errorDuringInterpret = null; boolean startGui = false; /** Any atlas to load **/ File awcFile = null; /** Export folder to use **/ File exportFile = null; CliOptions cliOptions = new CliOptions(); try { final CommandLine commandLine = cliOptions.parse(args); // Help if (commandLine.hasOption(CliOptions.HELP)) { cliOptions.printHelp(); exitAfterInterpret = true; } // Show license if (commandLine.hasOption(CliOptions.LICENSE)) { /** Output information about the GPL license **/ System.out.println(ReleaseUtil.getLicense(License.GPL3, "Geopublisher")); } // AWC folder if (!commandLine.hasOption(CliOptions.AWCFOLDER) && commandLine.hasOption(CliOptions.EXPORT)) { System.out.println("Paramter " + CliOptions.AWCFOLDER + " is needed."); exitAfterInterpret = true; errorDuringInterpret = Errors.AWCPARAM_MISSING; } else if (commandLine.hasOption(CliOptions.AWCFOLDER)) { awcFile = new File(commandLine.getOptionValue( CliOptions.AWCFOLDER).trim()); if (AtlasConfig.isAtlasDir(awcFile)) { } else if (AtlasConfig.isAtlasDir(awcFile.getParentFile())) { awcFile = awcFile.getParentFile(); } else { File awcFile2 = new File(new File("."), commandLine .getOptionValue(CliOptions.AWCFOLDER).trim()); if (AtlasConfig.isAtlasDir(awcFile2)) { awcFile = awcFile2; } else if (AtlasConfig.isAtlasDir(awcFile2.getParentFile())) { awcFile = awcFile2.getParentFile(); } else { System.out .println("'" + awcFile + "' is no valid atlas directory. It should contain an atlas.gpa."); exitAfterInterpret = true; errorDuringInterpret = Errors.AWCPARAM_ILLEGAL; } } } // export? if (!commandLine.hasOption(CliOptions.EXPORT)) { // Use the GUI startGui = true; } else { exportFile = new File(commandLine.getOptionValue( CliOptions.EXPORT).trim()); if (!exportFile.isDirectory()) { System.out.println("Not a valid export directory: " + exportFile); exitAfterInterpret = true; errorDuringInterpret = Errors.EXPORTDIR_ILLEGAL; } else { // Check export dir if (exportFile.list().length > 0 && !commandLine.hasOption(CliOptions.FORCE)) { System.out .println("Export directory is not empty. Use --force to delete any older atlases."); exitAfterInterpret = true; errorDuringInterpret = Errors.EXPORTDIR_NOTEMPTYNOFORCE; } } } if (startGui && GraphicsEnvironment.isHeadless() && !exitAfterInterpret && errorDuringInterpret == null) { exitAfterInterpret = true; errorDuringInterpret = Errors.NOHEAD; System.err .println("Can open Geopublisher windows because your environment doesn't provide a window system. You may only use pure CLI commands like export (-e)."); } if (exitAfterInterpret || errorDuringInterpret != null) { - System.out - .println("Error " + errorDuringInterpret.getErrCode()); - // System.exit(); - return errorDuringInterpret.getErrCode(); + if (errorDuringInterpret != null) { + System.out.println("Error " + + errorDuringInterpret.getErrCode()); + // System.exit(); + return errorDuringInterpret.getErrCode(); + } else + return 0; } /*** * Start Running the commands */ if (startGui) { final File awcFileToLoad = awcFile; SwingUtilities.invokeLater(new Runnable() { @Override public void run() { // Load an atlas with GUI GeopublisherGUI instance = GeopublisherGUI .getInstance(false); if (commandLine.hasOption(CliOptions.VERSION)) { // exitAfterInterpret = true; // Logger.getLogger("root").setLevel(Level.ALL); Logger.getRootLogger().setLevel( org.apache.log4j.Level.DEBUG); } else { Logger.getRootLogger().setLevel( org.apache.log4j.Level.WARN); // Logger.getLogger("root").setLevel(Level.WARNING); } if (awcFileToLoad != null) instance.loadAtlasFromDir(awcFileToLoad); } }); return -1; } else { // Not starting GUI, initialize logging ConsoleAppender cp = new ConsoleAppender(new PatternLayout( PatternLayout.TTCC_CONVERSION_PATTERN)); cp.setName("CLI output"); cp.setTarget("System.out"); Logger.getRootLogger().addAppender(cp); if (commandLine.hasOption(CliOptions.VERSION)) Logger.getRootLogger().setLevel( org.apache.log4j.Level.DEBUG); else Logger.getRootLogger() .setLevel(org.apache.log4j.Level.WARN); if (awcFile != null) { final AtlasConfigEditable ace = new AMLImportEd() .parseAtlasConfig(null, awcFile); System.out .println("Loaded atlas: '" + ace.getTitle() + "'"); try { boolean toDisk = commandLine.hasOption(DISK); boolean toJws = commandLine.hasOption(JWS); // If nothing is selected, all export modes are selected if (!toDisk && !toJws) toDisk = toJws = true; JarExportUtil jeu = new JarExportUtil(ace, exportFile, toDisk, toJws, false); jeu.setZipDiskAfterExport(commandLine .hasOption(ZIPDISK)); jeu.export(null); } catch (Exception e) { errorDuringInterpret = Errors.EXPORT_FAILED; return Errors.EXPORT_FAILED.errCode; } } } // Do not System.exit() return 0; } catch (ParseException exp) { // oops, something went wrong System.err.println("Parsing failed. Reason: " + exp.getMessage()); cliOptions.printHelp(); return CliOptions.Errors.PARSEEXCEPTION.getErrCode(); } } }
true
true
public static int performArgs(final String[] args) { /** Any number >= 0 will result in exit **/ boolean exitAfterInterpret = false; CliOptions.Errors errorDuringInterpret = null; boolean startGui = false; /** Any atlas to load **/ File awcFile = null; /** Export folder to use **/ File exportFile = null; CliOptions cliOptions = new CliOptions(); try { final CommandLine commandLine = cliOptions.parse(args); // Help if (commandLine.hasOption(CliOptions.HELP)) { cliOptions.printHelp(); exitAfterInterpret = true; } // Show license if (commandLine.hasOption(CliOptions.LICENSE)) { /** Output information about the GPL license **/ System.out.println(ReleaseUtil.getLicense(License.GPL3, "Geopublisher")); } // AWC folder if (!commandLine.hasOption(CliOptions.AWCFOLDER) && commandLine.hasOption(CliOptions.EXPORT)) { System.out.println("Paramter " + CliOptions.AWCFOLDER + " is needed."); exitAfterInterpret = true; errorDuringInterpret = Errors.AWCPARAM_MISSING; } else if (commandLine.hasOption(CliOptions.AWCFOLDER)) { awcFile = new File(commandLine.getOptionValue( CliOptions.AWCFOLDER).trim()); if (AtlasConfig.isAtlasDir(awcFile)) { } else if (AtlasConfig.isAtlasDir(awcFile.getParentFile())) { awcFile = awcFile.getParentFile(); } else { File awcFile2 = new File(new File("."), commandLine .getOptionValue(CliOptions.AWCFOLDER).trim()); if (AtlasConfig.isAtlasDir(awcFile2)) { awcFile = awcFile2; } else if (AtlasConfig.isAtlasDir(awcFile2.getParentFile())) { awcFile = awcFile2.getParentFile(); } else { System.out .println("'" + awcFile + "' is no valid atlas directory. It should contain an atlas.gpa."); exitAfterInterpret = true; errorDuringInterpret = Errors.AWCPARAM_ILLEGAL; } } } // export? if (!commandLine.hasOption(CliOptions.EXPORT)) { // Use the GUI startGui = true; } else { exportFile = new File(commandLine.getOptionValue( CliOptions.EXPORT).trim()); if (!exportFile.isDirectory()) { System.out.println("Not a valid export directory: " + exportFile); exitAfterInterpret = true; errorDuringInterpret = Errors.EXPORTDIR_ILLEGAL; } else { // Check export dir if (exportFile.list().length > 0 && !commandLine.hasOption(CliOptions.FORCE)) { System.out .println("Export directory is not empty. Use --force to delete any older atlases."); exitAfterInterpret = true; errorDuringInterpret = Errors.EXPORTDIR_NOTEMPTYNOFORCE; } } } if (startGui && GraphicsEnvironment.isHeadless() && !exitAfterInterpret && errorDuringInterpret == null) { exitAfterInterpret = true; errorDuringInterpret = Errors.NOHEAD; System.err .println("Can open Geopublisher windows because your environment doesn't provide a window system. You may only use pure CLI commands like export (-e)."); } if (exitAfterInterpret || errorDuringInterpret != null) { System.out .println("Error " + errorDuringInterpret.getErrCode()); // System.exit(); return errorDuringInterpret.getErrCode(); } /*** * Start Running the commands */ if (startGui) { final File awcFileToLoad = awcFile; SwingUtilities.invokeLater(new Runnable() { @Override public void run() { // Load an atlas with GUI GeopublisherGUI instance = GeopublisherGUI .getInstance(false); if (commandLine.hasOption(CliOptions.VERSION)) { // exitAfterInterpret = true; // Logger.getLogger("root").setLevel(Level.ALL); Logger.getRootLogger().setLevel( org.apache.log4j.Level.DEBUG); } else { Logger.getRootLogger().setLevel( org.apache.log4j.Level.WARN); // Logger.getLogger("root").setLevel(Level.WARNING); } if (awcFileToLoad != null) instance.loadAtlasFromDir(awcFileToLoad); } }); return -1; } else { // Not starting GUI, initialize logging ConsoleAppender cp = new ConsoleAppender(new PatternLayout( PatternLayout.TTCC_CONVERSION_PATTERN)); cp.setName("CLI output"); cp.setTarget("System.out"); Logger.getRootLogger().addAppender(cp); if (commandLine.hasOption(CliOptions.VERSION)) Logger.getRootLogger().setLevel( org.apache.log4j.Level.DEBUG); else Logger.getRootLogger() .setLevel(org.apache.log4j.Level.WARN); if (awcFile != null) { final AtlasConfigEditable ace = new AMLImportEd() .parseAtlasConfig(null, awcFile); System.out .println("Loaded atlas: '" + ace.getTitle() + "'"); try { boolean toDisk = commandLine.hasOption(DISK); boolean toJws = commandLine.hasOption(JWS); // If nothing is selected, all export modes are selected if (!toDisk && !toJws) toDisk = toJws = true; JarExportUtil jeu = new JarExportUtil(ace, exportFile, toDisk, toJws, false); jeu.setZipDiskAfterExport(commandLine .hasOption(ZIPDISK)); jeu.export(null); } catch (Exception e) { errorDuringInterpret = Errors.EXPORT_FAILED; return Errors.EXPORT_FAILED.errCode; } } } // Do not System.exit() return 0; } catch (ParseException exp) { // oops, something went wrong System.err.println("Parsing failed. Reason: " + exp.getMessage()); cliOptions.printHelp(); return CliOptions.Errors.PARSEEXCEPTION.getErrCode(); } }
public static int performArgs(final String[] args) { /** Any number >= 0 will result in exit **/ boolean exitAfterInterpret = false; CliOptions.Errors errorDuringInterpret = null; boolean startGui = false; /** Any atlas to load **/ File awcFile = null; /** Export folder to use **/ File exportFile = null; CliOptions cliOptions = new CliOptions(); try { final CommandLine commandLine = cliOptions.parse(args); // Help if (commandLine.hasOption(CliOptions.HELP)) { cliOptions.printHelp(); exitAfterInterpret = true; } // Show license if (commandLine.hasOption(CliOptions.LICENSE)) { /** Output information about the GPL license **/ System.out.println(ReleaseUtil.getLicense(License.GPL3, "Geopublisher")); } // AWC folder if (!commandLine.hasOption(CliOptions.AWCFOLDER) && commandLine.hasOption(CliOptions.EXPORT)) { System.out.println("Paramter " + CliOptions.AWCFOLDER + " is needed."); exitAfterInterpret = true; errorDuringInterpret = Errors.AWCPARAM_MISSING; } else if (commandLine.hasOption(CliOptions.AWCFOLDER)) { awcFile = new File(commandLine.getOptionValue( CliOptions.AWCFOLDER).trim()); if (AtlasConfig.isAtlasDir(awcFile)) { } else if (AtlasConfig.isAtlasDir(awcFile.getParentFile())) { awcFile = awcFile.getParentFile(); } else { File awcFile2 = new File(new File("."), commandLine .getOptionValue(CliOptions.AWCFOLDER).trim()); if (AtlasConfig.isAtlasDir(awcFile2)) { awcFile = awcFile2; } else if (AtlasConfig.isAtlasDir(awcFile2.getParentFile())) { awcFile = awcFile2.getParentFile(); } else { System.out .println("'" + awcFile + "' is no valid atlas directory. It should contain an atlas.gpa."); exitAfterInterpret = true; errorDuringInterpret = Errors.AWCPARAM_ILLEGAL; } } } // export? if (!commandLine.hasOption(CliOptions.EXPORT)) { // Use the GUI startGui = true; } else { exportFile = new File(commandLine.getOptionValue( CliOptions.EXPORT).trim()); if (!exportFile.isDirectory()) { System.out.println("Not a valid export directory: " + exportFile); exitAfterInterpret = true; errorDuringInterpret = Errors.EXPORTDIR_ILLEGAL; } else { // Check export dir if (exportFile.list().length > 0 && !commandLine.hasOption(CliOptions.FORCE)) { System.out .println("Export directory is not empty. Use --force to delete any older atlases."); exitAfterInterpret = true; errorDuringInterpret = Errors.EXPORTDIR_NOTEMPTYNOFORCE; } } } if (startGui && GraphicsEnvironment.isHeadless() && !exitAfterInterpret && errorDuringInterpret == null) { exitAfterInterpret = true; errorDuringInterpret = Errors.NOHEAD; System.err .println("Can open Geopublisher windows because your environment doesn't provide a window system. You may only use pure CLI commands like export (-e)."); } if (exitAfterInterpret || errorDuringInterpret != null) { if (errorDuringInterpret != null) { System.out.println("Error " + errorDuringInterpret.getErrCode()); // System.exit(); return errorDuringInterpret.getErrCode(); } else return 0; } /*** * Start Running the commands */ if (startGui) { final File awcFileToLoad = awcFile; SwingUtilities.invokeLater(new Runnable() { @Override public void run() { // Load an atlas with GUI GeopublisherGUI instance = GeopublisherGUI .getInstance(false); if (commandLine.hasOption(CliOptions.VERSION)) { // exitAfterInterpret = true; // Logger.getLogger("root").setLevel(Level.ALL); Logger.getRootLogger().setLevel( org.apache.log4j.Level.DEBUG); } else { Logger.getRootLogger().setLevel( org.apache.log4j.Level.WARN); // Logger.getLogger("root").setLevel(Level.WARNING); } if (awcFileToLoad != null) instance.loadAtlasFromDir(awcFileToLoad); } }); return -1; } else { // Not starting GUI, initialize logging ConsoleAppender cp = new ConsoleAppender(new PatternLayout( PatternLayout.TTCC_CONVERSION_PATTERN)); cp.setName("CLI output"); cp.setTarget("System.out"); Logger.getRootLogger().addAppender(cp); if (commandLine.hasOption(CliOptions.VERSION)) Logger.getRootLogger().setLevel( org.apache.log4j.Level.DEBUG); else Logger.getRootLogger() .setLevel(org.apache.log4j.Level.WARN); if (awcFile != null) { final AtlasConfigEditable ace = new AMLImportEd() .parseAtlasConfig(null, awcFile); System.out .println("Loaded atlas: '" + ace.getTitle() + "'"); try { boolean toDisk = commandLine.hasOption(DISK); boolean toJws = commandLine.hasOption(JWS); // If nothing is selected, all export modes are selected if (!toDisk && !toJws) toDisk = toJws = true; JarExportUtil jeu = new JarExportUtil(ace, exportFile, toDisk, toJws, false); jeu.setZipDiskAfterExport(commandLine .hasOption(ZIPDISK)); jeu.export(null); } catch (Exception e) { errorDuringInterpret = Errors.EXPORT_FAILED; return Errors.EXPORT_FAILED.errCode; } } } // Do not System.exit() return 0; } catch (ParseException exp) { // oops, something went wrong System.err.println("Parsing failed. Reason: " + exp.getMessage()); cliOptions.printHelp(); return CliOptions.Errors.PARSEEXCEPTION.getErrCode(); } }
diff --git a/server/IDSWrapper/src/uk/ac/ids/resources/GenericResource.java b/server/IDSWrapper/src/uk/ac/ids/resources/GenericResource.java index 1206d7b..905e70c 100644 --- a/server/IDSWrapper/src/uk/ac/ids/resources/GenericResource.java +++ b/server/IDSWrapper/src/uk/ac/ids/resources/GenericResource.java @@ -1,352 +1,352 @@ package uk.ac.ids.resources; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.logging.Logger; import org.restlet.data.MediaType; import org.restlet.data.Reference; import org.restlet.data.Status; import org.restlet.ext.freemarker.TemplateRepresentation; import org.restlet.ext.rdf.Graph; import org.restlet.ext.rdf.Literal; import org.restlet.representation.Representation; import org.restlet.resource.Get; import org.restlet.resource.ResourceException; import org.restlet.resource.ServerResource; import uk.ac.ids.Main; import uk.ac.ids.data.Namespaces; import uk.ac.ids.data.Parameters; import uk.ac.ids.linker.LinkerParameters; import uk.ac.ids.linker.impl.DBpedia; import uk.ac.ids.linker.impl.GeoNames; import uk.ac.ids.linker.impl.IATI; import uk.ac.ids.linker.impl.Lexvo; import uk.ac.ids.linker.impl.ThemeChildren; import uk.ac.ids.vocabulary.OWL; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; // http://wiki.restlet.org/docs_2.1/13-restlet/28-restlet/270-restlet/245-restlet.html /** * @author Christophe Gueret <[email protected]> * @author Victor de Boer <[email protected]> * */ public class GenericResource extends ServerResource { // Logger instance protected static final Logger logger = Logger.getLogger(GenericResource.class.getName()); // Identifier of the resource private String resourceID = null; // Type (class) of the resource private String resourceType = null; // The data source (eldis / bridge) private String dataSource = null; // The graph that will contain the data about that resource private Graph graph = new Graph(); // The name of the resource; private Reference resource = null; // Set of key/value pairs for this resource private Map<String, ArrayList<String>> keyValuePairs = new HashMap<String, ArrayList<String>>(); @SuppressWarnings("serial") public static final Map<String, String> PLURAL = new HashMap<String, String>() { { put("country", "countries"); put("region", "regions"); put("document", "documents"); put("theme", "themes"); } }; private static final Reference RDFS_Resource = new Reference("http://www.w3.org/2000/01/rdf-schema#Resource"); /* * (non-Javadoc) * * @see org.restlet.resource.UniformResource#doInit() */ @Override protected void doInit() throws ResourceException { // Get the attributes value taken from the URI template resourceID = (String) getRequest().getAttributes().get("ID"); resourceType = (String) getRequest().getAttributes().get("TYPE"); dataSource = (String) getRequest().getAttributes().get("DB"); // If no ID has been given, return a 404 if (resourceID == null || resourceType == null || dataSource == null) { setStatus(Status.CLIENT_ERROR_NOT_FOUND); setExisting(false); } // Define the URI for this resource resource = new Reference(getRequest().getOriginalRef().toUri()); // Define the URI for the vocabulary Reference vocabNS = new Reference(getRequest().getOriginalRef().getHostIdentifier() + "/vocabulary"); // Load the key-values pairs from the JSON API loadKeyValuePairs(); // Process them for (Entry<String, ArrayList<String>> keyValuePair : keyValuePairs.entrySet()) { // Turn the key into a predicate Reference predicate = new Reference(keyValuePair.getKey()); // Get the range of that predicate Reference valueType = getApplication().getMappings().getRangeOf(predicate); // See if we need to rewrite the predicate into something else - Reference otherPredicate = getApplication().getMappings().getReplacementForPredicate(predicate); + Reference otherPredicate = getApplication().getMappings().getReplacementForPredicate(predicate); if (otherPredicate != null) predicate = otherPredicate; // If the predicate is relative, bind it to the vocabulary NS if (predicate.isRelative()) predicate.setBaseRef(vocabNS); // Get the values ArrayList<String> values = keyValuePair.getValue(); // See if we need to call a Linker to replace the value if (keyValuePair.getKey().equals("#language_name")) { LinkerParameters parameters = new LinkerParameters(); parameters.put(Lexvo.LANG_NAME, values.get(0)); parameters.put(Lexvo.LANG_NAME_LOCALE, "eng"); Lexvo lexvo = new Lexvo(); List<Reference> target = lexvo.getResource(parameters); if (target != null) { values.clear(); values.add(target.get(0).toUri().toString()); valueType = RDFS_Resource; } } for (String value : keyValuePair.getValue()) { // Sort of a hack: if theme parent, have the value be preceded // by a // "C" to get a correct match if (keyValuePair.getKey().equals("#cat_parent")) { value = "C" + value; } if (keyValuePair.getKey().equals("#cat_first_parent")) { value = "C" + value; } // If we know the type of this value, use it if (valueType != null) { // The target value is a Resource if (valueType.equals(RDFS_Resource)) { Reference object = new Reference(value); if (object.isRelative()) object.setBaseRef(vocabNS); graph.add(resource, predicate, object); } // The target is an internal link else if (getApplication().getMappings().isInternalType(valueType)) { String pattern = getApplication().getMappings().getPatternFor(valueType); if (pattern != null) { Reference object = new Reference(pattern.replace("{id}", value)); if (object.isRelative()) object.setBaseRef(vocabNS); graph.add(resource, predicate, object); } } // Otherwise, add a plain literal else { Literal object = new Literal(value); graph.add(resource, predicate, object); } } else { // Otherwise, add a plain literal Literal object = new Literal(value); graph.add(resource, predicate, object); } } } // Link to Geonames // TODO move that configuration in a ttl file if (resourceType.equals("country")) { GeoNames b = new GeoNames(); String countryName = keyValuePairs.get("#country_name").get(0); String countryCode = keyValuePairs.get("#iso_two_letter_code").get(0); LinkerParameters params = new LinkerParameters(); params.put(GeoNames.COUNTRY_CODE, countryCode); params.put(GeoNames.COUNTRY_NAME, countryName); List<Reference> target = b.getResource(params); if (target != null) graph.add(resource, OWL.SAME_AS, target.get(0)); } // Link to DBpedia // TODO move that configuration in a ttl file if (resourceType.equals("theme")) { DBpedia b = new DBpedia(); String themeTitle = keyValuePairs.get("#title").get(0); LinkerParameters params = new LinkerParameters(); params.put(DBpedia.THEME_TITLE, themeTitle); List<Reference> target = b.getResource(params); if (target != null) { for (Reference r : target) { graph.add(resource, OWL.SAME_AS, r); } } } // Link Theme to IATI if (resourceType.equals("theme")) { IATI iati = new IATI(); String children_url = keyValuePairs.get("#title").get(0); LinkerParameters params = new LinkerParameters(); params.put(IATI.THEME_TITLE, children_url); List<Reference> target = iati.getResource(params); if (target != null) for (Reference r : target) { graph.add(resource, OWL.SAME_AS, r); } } // Link to Theme's children // TODO move that configuration in a ttl file, fix OWL sameas if (resourceType.equals("theme")) { ThemeChildren ch = new ThemeChildren(getRequest().getOriginalRef().getHostIdentifier()); String children_url = keyValuePairs.get("#children_url").get(0); LinkerParameters params = new LinkerParameters(); params.put(ThemeChildren.CHILDREN_URL, children_url); List<Reference> target = ch.getResource(params); Reference predicate = new Reference("#child"); predicate.setBaseRef(vocabNS); if (target != null) { for (Reference r : target) { graph.add(resource, predicate, r); } } } } /* * (non-Javadoc) * * @see org.restlet.resource.Resource#getApplication() */ @Override public Main getApplication() { return (Main) super.getApplication(); } /** * Load the key values pairs from the JSON API */ private void loadKeyValuePairs() { try { // Compose the URL StringBuffer urlString = new StringBuffer("http://api.ids.ac.uk/openapi/"); urlString.append(dataSource).append("/"); urlString.append("get/").append(PLURAL.get(resourceType)).append("/"); urlString.append(resourceID).append("/full"); URL url = new URL(urlString.toString()); // Get the API key String api_key = Parameters.getInstance().get(Parameters.API_KEY); // Issue the API request StringBuffer response = new StringBuffer(); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Token-Guid", api_key); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); // Parse the response JsonParser parser = new JsonParser(); JsonElement e = parser.parse(response.toString()); if (!e.isJsonObject()) return; JsonElement element = ((JsonObject) e).get("results"); if (!element.isJsonObject()) return; for (Entry<String, JsonElement> entry : ((JsonObject) element).entrySet()) { // Ignore the objects if (entry.getValue().isJsonObject()) continue; // Prepare the list of values ArrayList<String> values = new ArrayList<String>(); // Store all the entries of the array if (entry.getValue().isJsonArray()) for (JsonElement v : (JsonArray) entry.getValue()) values.add(v.getAsString()); // Store the single value if (entry.getValue().isJsonPrimitive()) values.add(entry.getValue().getAsString()); // Store the keyValuePairs.put("#" + entry.getKey(), values); } } catch (Exception e) { e.printStackTrace(); } } /** * Returns an HTML representation of the resource * * @return an HTML representation of the resource */ @Get("html") public Representation toHTML() { Namespaces namespaces = getApplication().getNamespaces(); // TODO move creation of ids namespace at creation time if (!namespaces.isRegistered("ids:")) { Reference ns = new Reference(getRequest().getOriginalRef().getHostIdentifier() + "/vocabulary#"); namespaces.register(ns.toString(), "ids:"); } Map<String, Object> map = new HashMap<String, Object>(); map.put("resource", resource); map.put("triples", graph); map.put("ns", namespaces); return new TemplateRepresentation("resource.html", getApplication().getConfiguration(), map, MediaType.TEXT_HTML); } /** * Returns an RDF/XML representation of the resource * * @return an RDF/XML representation of the resource */ @Get("rdf") public Representation toRDFXML() { return graph.getRdfXmlRepresentation(); } }
true
true
protected void doInit() throws ResourceException { // Get the attributes value taken from the URI template resourceID = (String) getRequest().getAttributes().get("ID"); resourceType = (String) getRequest().getAttributes().get("TYPE"); dataSource = (String) getRequest().getAttributes().get("DB"); // If no ID has been given, return a 404 if (resourceID == null || resourceType == null || dataSource == null) { setStatus(Status.CLIENT_ERROR_NOT_FOUND); setExisting(false); } // Define the URI for this resource resource = new Reference(getRequest().getOriginalRef().toUri()); // Define the URI for the vocabulary Reference vocabNS = new Reference(getRequest().getOriginalRef().getHostIdentifier() + "/vocabulary"); // Load the key-values pairs from the JSON API loadKeyValuePairs(); // Process them for (Entry<String, ArrayList<String>> keyValuePair : keyValuePairs.entrySet()) { // Turn the key into a predicate Reference predicate = new Reference(keyValuePair.getKey()); // Get the range of that predicate Reference valueType = getApplication().getMappings().getRangeOf(predicate); // See if we need to rewrite the predicate into something else Reference otherPredicate = getApplication().getMappings().getReplacementForPredicate(predicate); if (otherPredicate != null) predicate = otherPredicate; // If the predicate is relative, bind it to the vocabulary NS if (predicate.isRelative()) predicate.setBaseRef(vocabNS); // Get the values ArrayList<String> values = keyValuePair.getValue(); // See if we need to call a Linker to replace the value if (keyValuePair.getKey().equals("#language_name")) { LinkerParameters parameters = new LinkerParameters(); parameters.put(Lexvo.LANG_NAME, values.get(0)); parameters.put(Lexvo.LANG_NAME_LOCALE, "eng"); Lexvo lexvo = new Lexvo(); List<Reference> target = lexvo.getResource(parameters); if (target != null) { values.clear(); values.add(target.get(0).toUri().toString()); valueType = RDFS_Resource; } } for (String value : keyValuePair.getValue()) { // Sort of a hack: if theme parent, have the value be preceded // by a // "C" to get a correct match if (keyValuePair.getKey().equals("#cat_parent")) { value = "C" + value; } if (keyValuePair.getKey().equals("#cat_first_parent")) { value = "C" + value; } // If we know the type of this value, use it if (valueType != null) { // The target value is a Resource if (valueType.equals(RDFS_Resource)) { Reference object = new Reference(value); if (object.isRelative()) object.setBaseRef(vocabNS); graph.add(resource, predicate, object); } // The target is an internal link else if (getApplication().getMappings().isInternalType(valueType)) { String pattern = getApplication().getMappings().getPatternFor(valueType); if (pattern != null) { Reference object = new Reference(pattern.replace("{id}", value)); if (object.isRelative()) object.setBaseRef(vocabNS); graph.add(resource, predicate, object); } } // Otherwise, add a plain literal else { Literal object = new Literal(value); graph.add(resource, predicate, object); } } else { // Otherwise, add a plain literal Literal object = new Literal(value); graph.add(resource, predicate, object); } } } // Link to Geonames // TODO move that configuration in a ttl file if (resourceType.equals("country")) { GeoNames b = new GeoNames(); String countryName = keyValuePairs.get("#country_name").get(0); String countryCode = keyValuePairs.get("#iso_two_letter_code").get(0); LinkerParameters params = new LinkerParameters(); params.put(GeoNames.COUNTRY_CODE, countryCode); params.put(GeoNames.COUNTRY_NAME, countryName); List<Reference> target = b.getResource(params); if (target != null) graph.add(resource, OWL.SAME_AS, target.get(0)); } // Link to DBpedia // TODO move that configuration in a ttl file if (resourceType.equals("theme")) { DBpedia b = new DBpedia(); String themeTitle = keyValuePairs.get("#title").get(0); LinkerParameters params = new LinkerParameters(); params.put(DBpedia.THEME_TITLE, themeTitle); List<Reference> target = b.getResource(params); if (target != null) { for (Reference r : target) { graph.add(resource, OWL.SAME_AS, r); } } } // Link Theme to IATI if (resourceType.equals("theme")) { IATI iati = new IATI(); String children_url = keyValuePairs.get("#title").get(0); LinkerParameters params = new LinkerParameters(); params.put(IATI.THEME_TITLE, children_url); List<Reference> target = iati.getResource(params); if (target != null) for (Reference r : target) { graph.add(resource, OWL.SAME_AS, r); } } // Link to Theme's children // TODO move that configuration in a ttl file, fix OWL sameas if (resourceType.equals("theme")) { ThemeChildren ch = new ThemeChildren(getRequest().getOriginalRef().getHostIdentifier()); String children_url = keyValuePairs.get("#children_url").get(0); LinkerParameters params = new LinkerParameters(); params.put(ThemeChildren.CHILDREN_URL, children_url); List<Reference> target = ch.getResource(params); Reference predicate = new Reference("#child"); predicate.setBaseRef(vocabNS); if (target != null) { for (Reference r : target) { graph.add(resource, predicate, r); } } } }
protected void doInit() throws ResourceException { // Get the attributes value taken from the URI template resourceID = (String) getRequest().getAttributes().get("ID"); resourceType = (String) getRequest().getAttributes().get("TYPE"); dataSource = (String) getRequest().getAttributes().get("DB"); // If no ID has been given, return a 404 if (resourceID == null || resourceType == null || dataSource == null) { setStatus(Status.CLIENT_ERROR_NOT_FOUND); setExisting(false); } // Define the URI for this resource resource = new Reference(getRequest().getOriginalRef().toUri()); // Define the URI for the vocabulary Reference vocabNS = new Reference(getRequest().getOriginalRef().getHostIdentifier() + "/vocabulary"); // Load the key-values pairs from the JSON API loadKeyValuePairs(); // Process them for (Entry<String, ArrayList<String>> keyValuePair : keyValuePairs.entrySet()) { // Turn the key into a predicate Reference predicate = new Reference(keyValuePair.getKey()); // Get the range of that predicate Reference valueType = getApplication().getMappings().getRangeOf(predicate); // See if we need to rewrite the predicate into something else Reference otherPredicate = getApplication().getMappings().getReplacementForPredicate(predicate); if (otherPredicate != null) predicate = otherPredicate; // If the predicate is relative, bind it to the vocabulary NS if (predicate.isRelative()) predicate.setBaseRef(vocabNS); // Get the values ArrayList<String> values = keyValuePair.getValue(); // See if we need to call a Linker to replace the value if (keyValuePair.getKey().equals("#language_name")) { LinkerParameters parameters = new LinkerParameters(); parameters.put(Lexvo.LANG_NAME, values.get(0)); parameters.put(Lexvo.LANG_NAME_LOCALE, "eng"); Lexvo lexvo = new Lexvo(); List<Reference> target = lexvo.getResource(parameters); if (target != null) { values.clear(); values.add(target.get(0).toUri().toString()); valueType = RDFS_Resource; } } for (String value : keyValuePair.getValue()) { // Sort of a hack: if theme parent, have the value be preceded // by a // "C" to get a correct match if (keyValuePair.getKey().equals("#cat_parent")) { value = "C" + value; } if (keyValuePair.getKey().equals("#cat_first_parent")) { value = "C" + value; } // If we know the type of this value, use it if (valueType != null) { // The target value is a Resource if (valueType.equals(RDFS_Resource)) { Reference object = new Reference(value); if (object.isRelative()) object.setBaseRef(vocabNS); graph.add(resource, predicate, object); } // The target is an internal link else if (getApplication().getMappings().isInternalType(valueType)) { String pattern = getApplication().getMappings().getPatternFor(valueType); if (pattern != null) { Reference object = new Reference(pattern.replace("{id}", value)); if (object.isRelative()) object.setBaseRef(vocabNS); graph.add(resource, predicate, object); } } // Otherwise, add a plain literal else { Literal object = new Literal(value); graph.add(resource, predicate, object); } } else { // Otherwise, add a plain literal Literal object = new Literal(value); graph.add(resource, predicate, object); } } } // Link to Geonames // TODO move that configuration in a ttl file if (resourceType.equals("country")) { GeoNames b = new GeoNames(); String countryName = keyValuePairs.get("#country_name").get(0); String countryCode = keyValuePairs.get("#iso_two_letter_code").get(0); LinkerParameters params = new LinkerParameters(); params.put(GeoNames.COUNTRY_CODE, countryCode); params.put(GeoNames.COUNTRY_NAME, countryName); List<Reference> target = b.getResource(params); if (target != null) graph.add(resource, OWL.SAME_AS, target.get(0)); } // Link to DBpedia // TODO move that configuration in a ttl file if (resourceType.equals("theme")) { DBpedia b = new DBpedia(); String themeTitle = keyValuePairs.get("#title").get(0); LinkerParameters params = new LinkerParameters(); params.put(DBpedia.THEME_TITLE, themeTitle); List<Reference> target = b.getResource(params); if (target != null) { for (Reference r : target) { graph.add(resource, OWL.SAME_AS, r); } } } // Link Theme to IATI if (resourceType.equals("theme")) { IATI iati = new IATI(); String children_url = keyValuePairs.get("#title").get(0); LinkerParameters params = new LinkerParameters(); params.put(IATI.THEME_TITLE, children_url); List<Reference> target = iati.getResource(params); if (target != null) for (Reference r : target) { graph.add(resource, OWL.SAME_AS, r); } } // Link to Theme's children // TODO move that configuration in a ttl file, fix OWL sameas if (resourceType.equals("theme")) { ThemeChildren ch = new ThemeChildren(getRequest().getOriginalRef().getHostIdentifier()); String children_url = keyValuePairs.get("#children_url").get(0); LinkerParameters params = new LinkerParameters(); params.put(ThemeChildren.CHILDREN_URL, children_url); List<Reference> target = ch.getResource(params); Reference predicate = new Reference("#child"); predicate.setBaseRef(vocabNS); if (target != null) { for (Reference r : target) { graph.add(resource, predicate, r); } } } }
diff --git a/src/java/org/lwjgl/opengl/WindowsAWTInput.java b/src/java/org/lwjgl/opengl/WindowsAWTInput.java index 3a911345..3c3ae351 100644 --- a/src/java/org/lwjgl/opengl/WindowsAWTInput.java +++ b/src/java/org/lwjgl/opengl/WindowsAWTInput.java @@ -1,194 +1,194 @@ /* * Copyright (c) 2002-2004 LWJGL Project * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'LWJGL' nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.lwjgl.opengl; import java.nio.IntBuffer; import java.nio.ByteBuffer; import org.lwjgl.LWJGLException; import org.lwjgl.LWJGLUtil; import org.lwjgl.BufferUtils; import java.awt.Cursor; import java.awt.Point; /** * * @author elias_naur <[email protected]> * @version $Revision: 2586 $ * $Id: LinuxAWTGLCanvasPeerInfo.java 2586 2006-10-20 11:51:34Z elias_naur $ */ final class WindowsAWTInput extends AbstractAWTInput { private final static int WS_CHILD = 0x40000000; private final Cursor blank_cursor; private Cursor cached_cursor; private long cached_hwnd; private WindowsDirectInputMouse cached_mouse; // private WindowsKeyboard cached_keyboard; private boolean has_grabbed; public WindowsAWTInput(AWTGLCanvas canvas) throws LWJGLException { super(canvas); int w = AWTUtil.getMinCursorSize(); int h = AWTUtil.getMinCursorSize(); blank_cursor = AWTUtil.createCursor(w, h, 0, 0, 1, BufferUtils.createIntBuffer(w*h), null); } public synchronized void destroyMouse() { if (cached_mouse != null) { grab(false); cached_mouse.destroy(); cached_mouse = null; } super.destroyMouse(); } /* public synchronized void destroyKeyboard() { if (cached_keyboard != null) { cached_keyboard.destroy(); cached_keyboard = null; } super.destroyKeyboard(); } */ public synchronized void processInput(PeerInfo peer_info) { WindowsPeerInfo windows_peerinfo = (WindowsPeerInfo)peer_info; long hwnd = windows_peerinfo.getHwnd(); try { hwnd = findTopLevelWindow(hwnd); if (cached_mouse == null || hwnd != cached_hwnd) { has_grabbed = false; cached_hwnd = hwnd; if (cached_mouse != null) { cached_mouse.destroy(); } /* if (cached_keyboard != null) { cached_keyboard.destroy(); }*/ WindowsDirectInput dinput = WindowsDisplay.createDirectInput(); cached_mouse = new WindowsDirectInputMouse(dinput, hwnd); // cached_keyboard = new WindowsKeyboard(dinput, hwnd); } if (isGrabbed()) { /** * DirectInput won't always stop the cursor from moving on top of the * task bar and clicking on it. So we'll use ClipCursor to * contain it while the cursor is grabbed. */ - WindowsDisplay.setupCursorClipping(hwnd, true); // Just clip it to a fullscreen window + WindowsDisplay.setupCursorClipping(hwnd); // Just clip it to a fullscreen window if (getCanvas().getCursor() != blank_cursor) { cached_cursor = getCanvas().getCursor(); /** * For some reason, DirectInput won't let us blank the cursor * with the EXCLUSIVE access mode, so we'll work around it with a * custom blank cursor */ getCanvas().setCursor(blank_cursor); } } else WindowsDisplay.resetCursorClipping(); grab(isGrabbed()); } catch (LWJGLException e) { LWJGLUtil.log("Failed to create windows mouse: " + e); } } private static native int getWindowStyles(long hwnd) throws LWJGLException; private static native long getParentWindow(long hwnd); private static long findTopLevelWindow(long hwnd) throws LWJGLException { int window_styles = getWindowStyles(hwnd); while ((window_styles & WS_CHILD) != 0) { hwnd = getParentWindow(hwnd); window_styles = getWindowStyles(hwnd); } return hwnd; } private void grab(boolean grab) { if (has_grabbed != grab) { cached_mouse.grab(grab); // cached_keyboard.grab(grab); has_grabbed = grab; cached_mouse.flush(); // cached_keyboard.flush(); getMouseEventQueue().clearEvents(); // getKeyboardEventQueue().clearEvents(); if (!grab) { getCanvas().setCursor(cached_cursor); } } } public synchronized void grabMouse(boolean grab) { if (grab != isGrabbed()) { /* Only ungrab since grabbing can only occur in processInput * when the hwnd is guaranteed valid */ if (cached_mouse != null && !grab) grab(grab); super.grabMouse(grab); } } public synchronized void pollMouse(IntBuffer coord_buffer, ByteBuffer buttons) { if (isGrabbed()) { if (cached_mouse != null) cached_mouse.poll(coord_buffer, buttons); } else super.pollMouse(coord_buffer, buttons); } public synchronized void readMouse(ByteBuffer buffer) { if (isGrabbed()) { if (cached_mouse != null) cached_mouse.read(buffer); } else super.readMouse(buffer); } /* public synchronized void readKeyboard(ByteBuffer buffer) { if (isGrabbed()) { if (cached_keyboard != null) cached_keyboard.read(buffer); } else super.readKeyboard(buffer); } public synchronized void pollKeyboard(ByteBuffer keyDownBuffer) { if (isGrabbed()) { if (cached_keyboard != null) cached_keyboard.poll(keyDownBuffer); } else super.pollKeyboard(keyDownBuffer); }*/ }
true
true
public synchronized void processInput(PeerInfo peer_info) { WindowsPeerInfo windows_peerinfo = (WindowsPeerInfo)peer_info; long hwnd = windows_peerinfo.getHwnd(); try { hwnd = findTopLevelWindow(hwnd); if (cached_mouse == null || hwnd != cached_hwnd) { has_grabbed = false; cached_hwnd = hwnd; if (cached_mouse != null) { cached_mouse.destroy(); } /* if (cached_keyboard != null) { cached_keyboard.destroy(); }*/ WindowsDirectInput dinput = WindowsDisplay.createDirectInput(); cached_mouse = new WindowsDirectInputMouse(dinput, hwnd); // cached_keyboard = new WindowsKeyboard(dinput, hwnd); } if (isGrabbed()) { /** * DirectInput won't always stop the cursor from moving on top of the * task bar and clicking on it. So we'll use ClipCursor to * contain it while the cursor is grabbed. */ WindowsDisplay.setupCursorClipping(hwnd, true); // Just clip it to a fullscreen window if (getCanvas().getCursor() != blank_cursor) { cached_cursor = getCanvas().getCursor(); /** * For some reason, DirectInput won't let us blank the cursor * with the EXCLUSIVE access mode, so we'll work around it with a * custom blank cursor */ getCanvas().setCursor(blank_cursor); } } else WindowsDisplay.resetCursorClipping(); grab(isGrabbed()); } catch (LWJGLException e) {
public synchronized void processInput(PeerInfo peer_info) { WindowsPeerInfo windows_peerinfo = (WindowsPeerInfo)peer_info; long hwnd = windows_peerinfo.getHwnd(); try { hwnd = findTopLevelWindow(hwnd); if (cached_mouse == null || hwnd != cached_hwnd) { has_grabbed = false; cached_hwnd = hwnd; if (cached_mouse != null) { cached_mouse.destroy(); } /* if (cached_keyboard != null) { cached_keyboard.destroy(); }*/ WindowsDirectInput dinput = WindowsDisplay.createDirectInput(); cached_mouse = new WindowsDirectInputMouse(dinput, hwnd); // cached_keyboard = new WindowsKeyboard(dinput, hwnd); } if (isGrabbed()) { /** * DirectInput won't always stop the cursor from moving on top of the * task bar and clicking on it. So we'll use ClipCursor to * contain it while the cursor is grabbed. */ WindowsDisplay.setupCursorClipping(hwnd); // Just clip it to a fullscreen window if (getCanvas().getCursor() != blank_cursor) { cached_cursor = getCanvas().getCursor(); /** * For some reason, DirectInput won't let us blank the cursor * with the EXCLUSIVE access mode, so we'll work around it with a * custom blank cursor */ getCanvas().setCursor(blank_cursor); } } else WindowsDisplay.resetCursorClipping(); grab(isGrabbed()); } catch (LWJGLException e) {
diff --git a/errai-workspaces/src/main/java/org/jboss/errai/workspaces/client/modules/auth/AuthenticationDisplay.java b/errai-workspaces/src/main/java/org/jboss/errai/workspaces/client/modules/auth/AuthenticationDisplay.java index 1b8ccd81e..cb021d6ba 100644 --- a/errai-workspaces/src/main/java/org/jboss/errai/workspaces/client/modules/auth/AuthenticationDisplay.java +++ b/errai-workspaces/src/main/java/org/jboss/errai/workspaces/client/modules/auth/AuthenticationDisplay.java @@ -1,169 +1,170 @@ /* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This 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 2.1 of * the License, or (at your option) any later version. * * This software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.errai.workspaces.client.modules.auth; import com.google.gwt.event.dom.client.*; import com.google.gwt.event.logical.shared.CloseEvent; import com.google.gwt.event.logical.shared.CloseHandler; import com.google.gwt.event.logical.shared.HasCloseHandlers; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.ui.*; import org.gwt.mosaic.ui.client.Caption; import org.gwt.mosaic.ui.client.MessageBox; import org.gwt.mosaic.ui.client.WindowPanel; import org.gwt.mosaic.ui.client.layout.BoxLayout; import org.gwt.mosaic.ui.client.layout.LayoutPanel; /** * A mosaic based based login box */ public class AuthenticationDisplay extends LayoutPanel implements AuthenticationModule.Display { private TextBox userNameInput; private PasswordTextBox passwordInput; private Button loginButton; private WindowPanel windowPanel; public AuthenticationDisplay() { super(); userNameInput = new TextBox(); passwordInput = new PasswordTextBox(); loginButton = new Button("Submit"); createLayoutWindowPanel(); } private void createLayoutWindowPanel() { windowPanel = new WindowPanel("Authentication required"); windowPanel.setAnimationEnabled(false); LayoutPanel panel = new LayoutPanel(); + //panel.addStyleName("WSLogin"); windowPanel.setWidget(panel); // create contents panel.setLayout(new BoxLayout(BoxLayout.Orientation.VERTICAL)); Grid grid = new Grid(3, 2); grid.setWidget(0, 0, new Label("Username:")); grid.setWidget(0, 1, userNameInput); grid.setWidget(1, 0, new Label("Password:")); grid.setWidget(1, 1, passwordInput); grid.setWidget(2, 0, new HTML("")); grid.setWidget(2, 1, loginButton); /** * Create a handler so that striking enter automatically * submits the login. */ KeyDownHandler clickOnEnter = new KeyDownHandler() { @Override public void onKeyDown(KeyDownEvent event) { if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { loginButton.click(); } } }; userNameInput.addKeyDownHandler(clickOnEnter); passwordInput.addKeyDownHandler(clickOnEnter); /** * Close the window immediately upon submission. */ loginButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { windowPanel.hide(); } }); panel.add(grid); windowPanel.getHeader().add(Caption.IMAGES.window().createImage()); windowPanel.addCloseHandler(new CloseHandler<PopupPanel>() { public void onClose(CloseEvent<PopupPanel> event) { windowPanel = null; } }); } @Override public void showLoginPanel() { if (null == windowPanel) createLayoutWindowPanel(); clearPanel(); windowPanel.pack(); windowPanel.center(); } @Override public void clearPanel() { userNameInput.setText(""); passwordInput.setText(""); } @Override public void hideLoginPanel() { if (windowPanel != null) windowPanel.hide(); } @Override public HasText getUsernameInput() { return userNameInput; } @Override public HasText getPasswordInput() { return passwordInput; } @Override public HasClickHandlers getSubmitButton() { return loginButton; } @Override public HasCloseHandlers getWindowPanel() { return windowPanel; } @Override public void showWelcomeMessage(final String messageText) { Timer t = new Timer() { @Override public void run() { MessageBox.info("Welcome", messageText); } }; t.schedule(500); } }
true
true
private void createLayoutWindowPanel() { windowPanel = new WindowPanel("Authentication required"); windowPanel.setAnimationEnabled(false); LayoutPanel panel = new LayoutPanel(); windowPanel.setWidget(panel); // create contents panel.setLayout(new BoxLayout(BoxLayout.Orientation.VERTICAL)); Grid grid = new Grid(3, 2); grid.setWidget(0, 0, new Label("Username:")); grid.setWidget(0, 1, userNameInput); grid.setWidget(1, 0, new Label("Password:")); grid.setWidget(1, 1, passwordInput); grid.setWidget(2, 0, new HTML("")); grid.setWidget(2, 1, loginButton); /** * Create a handler so that striking enter automatically * submits the login. */ KeyDownHandler clickOnEnter = new KeyDownHandler() { @Override public void onKeyDown(KeyDownEvent event) { if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { loginButton.click(); } } }; userNameInput.addKeyDownHandler(clickOnEnter); passwordInput.addKeyDownHandler(clickOnEnter); /** * Close the window immediately upon submission. */ loginButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { windowPanel.hide(); } }); panel.add(grid); windowPanel.getHeader().add(Caption.IMAGES.window().createImage()); windowPanel.addCloseHandler(new CloseHandler<PopupPanel>() { public void onClose(CloseEvent<PopupPanel> event) { windowPanel = null; } }); }
private void createLayoutWindowPanel() { windowPanel = new WindowPanel("Authentication required"); windowPanel.setAnimationEnabled(false); LayoutPanel panel = new LayoutPanel(); //panel.addStyleName("WSLogin"); windowPanel.setWidget(panel); // create contents panel.setLayout(new BoxLayout(BoxLayout.Orientation.VERTICAL)); Grid grid = new Grid(3, 2); grid.setWidget(0, 0, new Label("Username:")); grid.setWidget(0, 1, userNameInput); grid.setWidget(1, 0, new Label("Password:")); grid.setWidget(1, 1, passwordInput); grid.setWidget(2, 0, new HTML("")); grid.setWidget(2, 1, loginButton); /** * Create a handler so that striking enter automatically * submits the login. */ KeyDownHandler clickOnEnter = new KeyDownHandler() { @Override public void onKeyDown(KeyDownEvent event) { if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { loginButton.click(); } } }; userNameInput.addKeyDownHandler(clickOnEnter); passwordInput.addKeyDownHandler(clickOnEnter); /** * Close the window immediately upon submission. */ loginButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { windowPanel.hide(); } }); panel.add(grid); windowPanel.getHeader().add(Caption.IMAGES.window().createImage()); windowPanel.addCloseHandler(new CloseHandler<PopupPanel>() { public void onClose(CloseEvent<PopupPanel> event) { windowPanel = null; } }); }
diff --git a/src/com/herocraftonline/dev/heroes/skill/skills/SkillWolf.java b/src/com/herocraftonline/dev/heroes/skill/skills/SkillWolf.java index ac6065c7..17857b5e 100644 --- a/src/com/herocraftonline/dev/heroes/skill/skills/SkillWolf.java +++ b/src/com/herocraftonline/dev/heroes/skill/skills/SkillWolf.java @@ -1,44 +1,46 @@ package com.herocraftonline.dev.heroes.skill.skills; import java.util.HashMap; import org.bukkit.entity.CreatureType; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.entity.Wolf; import com.herocraftonline.dev.heroes.Heroes; import com.herocraftonline.dev.heroes.persistence.Hero; import com.herocraftonline.dev.heroes.skill.ActiveSkill; import com.herocraftonline.dev.heroes.util.Messaging; public class SkillWolf extends ActiveSkill { public HashMap<Player, Integer> wolves = new HashMap<Player, Integer>(); public SkillWolf(Heroes plugin) { super(plugin); name = "Wolf"; description = "Summons and tames a wolf to your side"; usage = "/skill wolf"; minArgs = 0; maxArgs = 0; identifiers.add("skill wolf"); } @Override public boolean use(Hero hero, String[] args) { Player player = hero.getPlayer(); if (!wolves.containsKey(player) || wolves.get(player) <= 3) { LivingEntity le = player.getWorld().spawnCreature(hero.getPlayer().getLocation(), CreatureType.WOLF); Wolf wolf = (Wolf) le; wolf.setOwner(player); wolf.setTamed(true); - wolves.put(player, wolves.get(player) + 1); + int wolfFixIntegerYesImReallyDoingThisILikeLongNamesNeverGonnaGetAErrorAboutCollidingNamesAnymoreFuckJavaConventions = wolves.get(player) + 1; + wolves.remove(player); + wolves.put(player, wolfFixIntegerYesImReallyDoingThisILikeLongNamesNeverGonnaGetAErrorAboutCollidingNamesAnymoreFuckJavaConventions); return true; } else { Messaging.send(player, "Sorry, you have too many wolves already", (String[]) null); return false; } } }
true
true
public boolean use(Hero hero, String[] args) { Player player = hero.getPlayer(); if (!wolves.containsKey(player) || wolves.get(player) <= 3) { LivingEntity le = player.getWorld().spawnCreature(hero.getPlayer().getLocation(), CreatureType.WOLF); Wolf wolf = (Wolf) le; wolf.setOwner(player); wolf.setTamed(true); wolves.put(player, wolves.get(player) + 1); return true; } else { Messaging.send(player, "Sorry, you have too many wolves already", (String[]) null); return false; } }
public boolean use(Hero hero, String[] args) { Player player = hero.getPlayer(); if (!wolves.containsKey(player) || wolves.get(player) <= 3) { LivingEntity le = player.getWorld().spawnCreature(hero.getPlayer().getLocation(), CreatureType.WOLF); Wolf wolf = (Wolf) le; wolf.setOwner(player); wolf.setTamed(true); int wolfFixIntegerYesImReallyDoingThisILikeLongNamesNeverGonnaGetAErrorAboutCollidingNamesAnymoreFuckJavaConventions = wolves.get(player) + 1; wolves.remove(player); wolves.put(player, wolfFixIntegerYesImReallyDoingThisILikeLongNamesNeverGonnaGetAErrorAboutCollidingNamesAnymoreFuckJavaConventions); return true; } else { Messaging.send(player, "Sorry, you have too many wolves already", (String[]) null); return false; } }
diff --git a/src/main/java/org/jhuapl/edu/sages/etl/strategy/SagesOpenCsvJar.java b/src/main/java/org/jhuapl/edu/sages/etl/strategy/SagesOpenCsvJar.java index b178d72..43f3501 100644 --- a/src/main/java/org/jhuapl/edu/sages/etl/strategy/SagesOpenCsvJar.java +++ b/src/main/java/org/jhuapl/edu/sages/etl/strategy/SagesOpenCsvJar.java @@ -1,395 +1,395 @@ /** * */ package org.jhuapl.edu.sages.etl.strategy; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Savepoint; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Properties; import org.apache.commons.io.FileUtils; import org.apache.log4j.Logger; import org.jhuapl.edu.sages.etl.ConnectionFactory; import org.jhuapl.edu.sages.etl.ETLProperties; import org.jhuapl.edu.sages.etl.PropertiesLoader; import org.jhuapl.edu.sages.etl.SagesEtlException; import org.jhuapl.edu.sages.etl.opencsvpods.DumbTestOpenCsvJar; /** * {@link SagesOpenCsvJar} is the domain class and controls the execution of the overall ETL process. * It contains an {@link ETLStrategyTemplate} object that implements most of the ETL processing logic. * * @author POKUAM1 * @created Nov 1, 2011 */ public abstract class SagesOpenCsvJar { private static org.apache.log4j.Logger log = Logger.getLogger(SagesOpenCsvJar.class); private static org.apache.log4j.Logger outcomeLog = Logger.getLogger("FileProcessingOutcome"); /** The {@link ETLStrategyTemplate} object **/ protected ETLStrategyTemplate etlStrategy; /** The savepoints **/ protected Map<String, Savepoint> savepoints; /** List of files that ETL loads into the production table **/ protected File[] csvFiles; /** The current file that is being processed **/ private File currentFile; /** Current file records that the ETL will load into the production table via SQL statements **/ protected ArrayList<String[]> currentEntries; /** Flag used to determine whether a file should be moved to directory that signifies successful processing **/ private boolean success; /** TODO: not used yet. The current file marked for deletion due to an error in processing **/ protected File fileMarkedForDeletion; /** TODO: not used yet **/ protected int currentRecNum; /** TODO: not used yet. List of files ETL encountered failure while processing **/ private static List<File> failedCsvFiles; /** csv files are loaded from inputdir and moved to outputdir after being processed successfully */ /** ETL looks at the input directory for files to process **/ protected String inputdir_csvfiles; /** ETL moves successfully processed files to the output directory **/ protected String outputdir_csvfiles; /** ETL moves unsucessfully processed files to the failed directory **/ private String faileddir_csvfiles; protected static final String ETL_CLEANSE_TABLE = "ETL_CLEANSE_TABLE"; protected static final String ETL_STAGING_DB = "ETL_STAGING_DB"; protected String src_table_name; protected String dst_table_name; protected String prod_table_name; /** maps the destination columns to their sql-datatype qualifier for generating the schema */ protected Map<String,String> DEST_COLTYPE_MAP; //http://download.oracle.com/javase/6/docs/api/constant-values.html#java.sql.Types.TIME /** maps the destination columns to their java.sql.Types for setting ? parameters on prepared statements */ protected Map<String, Integer> DEST_SQLTYPE_MAP; /** maps the source:destination columns*/ protected Map<String, String> MAPPING_MAP; /** maps the destination:source columns*/ protected Map<String, String> MAPPING_REV_MAP; /** properties holders */ protected Properties props_etlconfig; protected Properties props_mappings; protected Properties props_dateformats; protected Properties props_customsql_cleanse; protected Properties props_customsql_staging; protected Properties props_customsql_final_to_prod; /** target database connection settings*/ protected String dbms; protected int portNumber; protected String serverName; protected String dbName; protected String userName; protected String password; /** maps source column name to its parameter index in the source table, indexing starts at 1 */ protected Map<String,Integer> PARAMINDX_SRC = new HashMap<String,Integer>(); /** maps destination column name to its parameter index in the destination table, indexing starts at 1 */ protected Map<String,Integer> PARAMINDX_DST = new HashMap<String,Integer>(); /** header columns used to define the CLEANSE table schema */ protected String[] header_src = new String[0]; /** errorFlag to control what to do on certain errors */ protected int errorFlag = 0; /** * * @throws SagesEtlException */ public SagesOpenCsvJar() throws SagesEtlException{ super(); PropertiesLoader etlProperties = new ETLProperties(); etlProperties.loadEtlProperties(); initializeProperties((ETLProperties) etlProperties); setFailedCsvFiles(new ArrayList<File>()); savepoints = new LinkedHashMap<String, Savepoint>(); } public void setEtlStrategy (ETLStrategyTemplate strategy){ etlStrategy = strategy; } public void extractHeaderColumns(SagesOpenCsvJar socj) throws FileNotFoundException, IOException{ etlStrategy.extractHeaderColumns(socj); }; String[] determineHeaderColumns(File file) throws FileNotFoundException, IOException{ return etlStrategy.determineHeaderColumns(file); }; public Savepoint buildCleanseTable(Connection c, SagesOpenCsvJar socj, Savepoint save1) throws SQLException,SagesEtlException{ return etlStrategy.buildCleanseTable(c, socj, save1); }; public void truncateCleanseAndStagingTables(DumbTestOpenCsvJar socj_dumb, Connection c, File file, Savepoint baseLine) throws SagesEtlException, SQLException { etlStrategy.truncateCleanseAndStagingTables(socj_dumb, c, file, baseLine); } public Savepoint buildStagingTable(Connection c, SagesOpenCsvJar socj, Savepoint save1) throws SQLException, SagesEtlException{ return etlStrategy.buildStagingTable(c, socj, save1); }; public void generateSourceDestMappings(SagesOpenCsvJar socj){ etlStrategy.generateSourceDestMappings(socj); } public void setAndExecuteInsertIntoCleansingTablePreparedStatement( Connection c, SagesOpenCsvJar socj, ArrayList<String[]> entries_rawdata, Savepoint save2, PreparedStatement ps_INSERT_CLEANSE) throws SQLException { etlStrategy.setAndExecuteInsertIntoCleansingTablePreparedStatement(c, socj, entries_rawdata, save2, ps_INSERT_CLEANSE); } public String buildInsertIntoCleansingTableSql(Connection c, SagesOpenCsvJar socj) throws SQLException { return etlStrategy.buildInsertIntoCleansingTableSql(c, socj); } public void copyFromCleanseToStaging(Connection c, SagesOpenCsvJar socj, Savepoint save2) throws SQLException, SagesEtlException { etlStrategy.copyFromCleanseToStaging(c, socj, save2); } public int errorCleanup(SagesOpenCsvJar socj, Savepoint savepoint, Connection connection, File currentCsv, String failedDirPath, Exception e){ return etlStrategy.errorCleanup(socj, savepoint, connection, currentCsv, failedDirPath, e); } String addFlagColumn(String tableToModify){ return etlStrategy.addFlagColumn(tableToModify); }; public void alterCleanseTableAddFlagColumn(Connection c, Savepoint save1, Savepoint createCleanseSavepoint) throws SQLException, SagesEtlException{ etlStrategy.alterCleanseTableAddFlagColumn(c, save1, createCleanseSavepoint); }; public void alterStagingTableAddFlagColumn(Connection c, Savepoint save1, Savepoint createCleanseSavepoint) throws SQLException, SagesEtlException{ etlStrategy.alterStagingTableAddFlagColumn(c, save1, createCleanseSavepoint); } /** Public/protected helper methods **/ /** * Initializes the {@link SagesOpenCsvJar}' s etl properties * * @param etlProperties - these are configured by updating the set of ETL properties files * @throws SagesEtlException - if property doesn't exist, or issue loading properties file occurs */ protected void initializeProperties(ETLProperties etlProperties) throws SagesEtlException { this.props_etlconfig = etlProperties.getProps_etlconfig(); this.props_mappings = etlProperties.getProps_mappings(); this.props_dateformats = etlProperties.getProps_dateformats(); this.props_customsql_cleanse = etlProperties.getProps_customsql_cleanse(); this.props_customsql_staging = etlProperties.getProps_customsql_staging(); this.props_customsql_final_to_prod = etlProperties.getProps_customsql_final_to_prod(); this.dbms = etlProperties.getDbms(); this.portNumber = etlProperties.getPortNumber(); this.userName = etlProperties.getUserName(); this.password = etlProperties.getPassword(); this.serverName = etlProperties.getServerName(); this.dbName = etlProperties.getDbName(); this.inputdir_csvfiles = props_etlconfig.getProperty("csvinputdir"); this.outputdir_csvfiles = props_etlconfig.getProperty("csvoutputdir"); this.setFaileddir_csvfiles(props_etlconfig.getProperty("csvfaileddir")); } /** * Establishes database connection to the target database * @return Connection * @throws SQLException */ public Connection getConnection() throws SagesEtlException { try { return ConnectionFactory.createConnection(this.dbms, this.serverName, this.dbName, this.userName, this.password, this.portNumber); } catch (SQLException e){ throw abort("Sorry, failed to establish database connection", e); } } /** * Copies file to the designated destination directory, and then deletes it from its * original location. On failure, copied to FAILED directory, On success copied to OUT directory * @param file * @param destinationDir * @throws IOException */ protected static File etlMoveFile(File file, File destinationDir)throws IOException { Date date = new Date(); long dtime = date.getTime(); File newFileLocation = new File(destinationDir, dtime + "_"+ file.getName()); /** Move file to new dir */ FileUtils.copyFile(file, newFileLocation); FileUtils.forceDelete(file); return newFileLocation; } /** * @param socj_dumb * @param c * @throws SQLException */ protected static void runCustomSql(Connection c, Properties customSql, String targetTableName) throws SQLException { //Properties customCleanseSqlprops = socj_dumb.props_customsql_cleanse; Properties customCleanseSqlprops = customSql; int numSql = customCleanseSqlprops.size(); for (int i = 1; i <= numSql; i++) { String sql = customCleanseSqlprops.getProperty(String.valueOf(i)); sql = sql.replace("$table", targetTableName); log.debug("CUSTOM SQL: " + sql); PreparedStatement ps = c.prepareStatement(sql); ps.execute(); } } /** * @param socj TODO * @param c * @param outcome * @param sql * @param canonicalPath * @param fileName * @param processtime * @throws SagesEtlException * @throws SQLException */ public static void logFileOutcome(SagesOpenCsvJar socj, Connection c, File file, String outcome) throws SagesEtlException { String sql = "INSERT INTO etl_status(filename,filepath,outcome,processtime) VALUES(?,?,?,?)"; String canonicalPath = "?"; try { canonicalPath = file.getCanonicalPath(); } catch (IOException e1) { canonicalPath = file.getAbsolutePath(); e1.printStackTrace(); } String fileName = file.getName(); Timestamp processtime = new Timestamp(new Date().getTime()); if (c!= null){ boolean exceptionOcurred = false; Exception eTmp = null; try { PreparedStatement ps_INSERTFILESTATUS = c.prepareStatement(sql); ps_INSERTFILESTATUS.setString(1, fileName); ps_INSERTFILESTATUS.setString(2, canonicalPath); ps_INSERTFILESTATUS.setString(3, outcome); ps_INSERTFILESTATUS.setTimestamp(4, processtime); ps_INSERTFILESTATUS.execute(); } catch (SQLException e) { exceptionOcurred = true; outcomeLog.warn("Unable to write file processing statistics to database. Statistics were still written" + " to the log files. Please Investigate. \n" + e.getMessage()); eTmp = new SQLException(e); } finally { /** TODO MAKE THIS GO INTO A SPECIAL LOG FILE NOT JUST CONSOLE **/ - outcomeLog.info("--------File Proecessing Results--------"); + outcomeLog.info("--------File Processing Results--------"); outcomeLog.info("Filename: " + fileName); outcomeLog.info("Filepath: " + canonicalPath); outcomeLog.info("Processed Time: " + processtime); outcomeLog.info("Outcome: " + outcome); if (exceptionOcurred){ outcomeLog.warn("ALERT. Unable to write these statistics to database. " + "Please Investigate. \n" + eTmp.getMessage()); // NOT A TRUE ERROR, SO DON'T MARK FILES AS FAILED--FILE IS null AND SO IS THE FAILED CSV DIR // socj.errorCleanup(socj, socj.savepoints.get("finalCommit"), c, null, null, eTmp); //TODO OMG THIS IS GROSS FIX ASAP socj.etlStrategy.m_sqlStateHandler.errorCleanup(socj, socj.savepoints.get("finalCommit"), c, null, null, eTmp); } } } } /** * @param c database connection */ public static void closeDbConnection(Connection c) { /** CLOSE CONNECTION TO DATABASE **/ try { if (c != null) { c.close(); log.info("Closed Database Connection. Good-bye."); } } catch (SQLException e) { log.fatal("THIS IS BAD. PROBLEM OCURRED TRYING TO CLOSE DB CONNECTION."); } } /** * returns a SagesEtlException that wraps the original exception * @param msg SAGES ETL message to display * @param e the original exception * @return SagesEtlException */ public static SagesEtlException abort(String msg, Throwable e){ return new SagesEtlException(e.getMessage(), e); } public String getFaileddir_csvfiles() { return faileddir_csvfiles; } public void setFaileddir_csvfiles(String faileddir_csvfiles) { this.faileddir_csvfiles = faileddir_csvfiles; } public File getCurrentFile() { return currentFile; } public void setCurrentFile(File currentFile) { this.currentFile = currentFile; } public static List<File> getFailedCsvFiles() { return failedCsvFiles; } public static void setFailedCsvFiles(List<File> failedCsvFiles) { SagesOpenCsvJar.failedCsvFiles = failedCsvFiles; } public boolean isSuccess() { return success; } public void setSuccess(boolean success) { this.success = success; } }
true
true
public static void logFileOutcome(SagesOpenCsvJar socj, Connection c, File file, String outcome) throws SagesEtlException { String sql = "INSERT INTO etl_status(filename,filepath,outcome,processtime) VALUES(?,?,?,?)"; String canonicalPath = "?"; try { canonicalPath = file.getCanonicalPath(); } catch (IOException e1) { canonicalPath = file.getAbsolutePath(); e1.printStackTrace(); } String fileName = file.getName(); Timestamp processtime = new Timestamp(new Date().getTime()); if (c!= null){ boolean exceptionOcurred = false; Exception eTmp = null; try { PreparedStatement ps_INSERTFILESTATUS = c.prepareStatement(sql); ps_INSERTFILESTATUS.setString(1, fileName); ps_INSERTFILESTATUS.setString(2, canonicalPath); ps_INSERTFILESTATUS.setString(3, outcome); ps_INSERTFILESTATUS.setTimestamp(4, processtime); ps_INSERTFILESTATUS.execute(); } catch (SQLException e) { exceptionOcurred = true; outcomeLog.warn("Unable to write file processing statistics to database. Statistics were still written" + " to the log files. Please Investigate. \n" + e.getMessage()); eTmp = new SQLException(e); } finally { /** TODO MAKE THIS GO INTO A SPECIAL LOG FILE NOT JUST CONSOLE **/ outcomeLog.info("--------File Proecessing Results--------"); outcomeLog.info("Filename: " + fileName); outcomeLog.info("Filepath: " + canonicalPath); outcomeLog.info("Processed Time: " + processtime); outcomeLog.info("Outcome: " + outcome); if (exceptionOcurred){ outcomeLog.warn("ALERT. Unable to write these statistics to database. " + "Please Investigate. \n" + eTmp.getMessage()); // NOT A TRUE ERROR, SO DON'T MARK FILES AS FAILED--FILE IS null AND SO IS THE FAILED CSV DIR // socj.errorCleanup(socj, socj.savepoints.get("finalCommit"), c, null, null, eTmp); //TODO OMG THIS IS GROSS FIX ASAP socj.etlStrategy.m_sqlStateHandler.errorCleanup(socj, socj.savepoints.get("finalCommit"), c, null, null, eTmp); } } } }
public static void logFileOutcome(SagesOpenCsvJar socj, Connection c, File file, String outcome) throws SagesEtlException { String sql = "INSERT INTO etl_status(filename,filepath,outcome,processtime) VALUES(?,?,?,?)"; String canonicalPath = "?"; try { canonicalPath = file.getCanonicalPath(); } catch (IOException e1) { canonicalPath = file.getAbsolutePath(); e1.printStackTrace(); } String fileName = file.getName(); Timestamp processtime = new Timestamp(new Date().getTime()); if (c!= null){ boolean exceptionOcurred = false; Exception eTmp = null; try { PreparedStatement ps_INSERTFILESTATUS = c.prepareStatement(sql); ps_INSERTFILESTATUS.setString(1, fileName); ps_INSERTFILESTATUS.setString(2, canonicalPath); ps_INSERTFILESTATUS.setString(3, outcome); ps_INSERTFILESTATUS.setTimestamp(4, processtime); ps_INSERTFILESTATUS.execute(); } catch (SQLException e) { exceptionOcurred = true; outcomeLog.warn("Unable to write file processing statistics to database. Statistics were still written" + " to the log files. Please Investigate. \n" + e.getMessage()); eTmp = new SQLException(e); } finally { /** TODO MAKE THIS GO INTO A SPECIAL LOG FILE NOT JUST CONSOLE **/ outcomeLog.info("--------File Processing Results--------"); outcomeLog.info("Filename: " + fileName); outcomeLog.info("Filepath: " + canonicalPath); outcomeLog.info("Processed Time: " + processtime); outcomeLog.info("Outcome: " + outcome); if (exceptionOcurred){ outcomeLog.warn("ALERT. Unable to write these statistics to database. " + "Please Investigate. \n" + eTmp.getMessage()); // NOT A TRUE ERROR, SO DON'T MARK FILES AS FAILED--FILE IS null AND SO IS THE FAILED CSV DIR // socj.errorCleanup(socj, socj.savepoints.get("finalCommit"), c, null, null, eTmp); //TODO OMG THIS IS GROSS FIX ASAP socj.etlStrategy.m_sqlStateHandler.errorCleanup(socj, socj.savepoints.get("finalCommit"), c, null, null, eTmp); } } } }
diff --git a/src/main/java/com/almuramc/aqualock/bukkit/input/AquaPanelDelegate.java b/src/main/java/com/almuramc/aqualock/bukkit/input/AquaPanelDelegate.java index d98e0b1..b3d96f3 100644 --- a/src/main/java/com/almuramc/aqualock/bukkit/input/AquaPanelDelegate.java +++ b/src/main/java/com/almuramc/aqualock/bukkit/input/AquaPanelDelegate.java @@ -1,83 +1,83 @@ /* * This file is part of Aqualock. * * Copyright (c) 2012, AlmuraDev <http://www.almuramc.com/> * Aqualock is licensed under the Almura Development License. * * Aqualock 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. * * Aqualock 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. If not, * see <http://www.gnu.org/licenses/> for the GNU General Public License. */ package com.almuramc.aqualock.bukkit.input; import java.util.HashMap; import java.util.UUID; import com.almuramc.aqualock.bukkit.AqualockPlugin; import com.almuramc.aqualock.bukkit.display.AquaPanel; import com.almuramc.aqualock.bukkit.util.BlockUtil; import com.almuramc.aqualock.bukkit.util.LockUtil; import com.almuramc.bolt.lock.Lock; import org.getspout.spoutapi.event.input.KeyBindingEvent; import org.getspout.spoutapi.gui.ScreenType; import org.getspout.spoutapi.keyboard.BindingExecutionDelegate; import org.getspout.spoutapi.player.SpoutPlayer; import org.bukkit.Location; import org.bukkit.block.Block; public class AquaPanelDelegate implements BindingExecutionDelegate { private final AqualockPlugin plugin; private static final HashMap<UUID, AquaPanel> panels = new HashMap<UUID, AquaPanel>(); public AquaPanelDelegate(AqualockPlugin plugin) { this.plugin = plugin; } @Override public void keyPressed(KeyBindingEvent keyBindingEvent) { final SpoutPlayer player = keyBindingEvent.getPlayer(); //Do not let them close another screen with this keybinding from this event - if (!player.getMainScreen().getScreenType().equals(ScreenType.GAME_SCREEN)) { + if (!keyBindingEvent.getScreenType().equals(ScreenType.GAME_SCREEN)) { return; } Block block = BlockUtil.getTarget(player, null, 4); if (block == null) { player.sendMessage(plugin.getPrefix() + "No valid block at the cursor could be found!"); return; } AquaPanel panel; final Location loc = block.getLocation(); final Lock lock = plugin.getRegistry().getLock(loc.getWorld().getUID(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); if (!LockUtil.canPerformAction(player, lock == null ? "LOCK" : "UPDATE")) { return; } //Check for GUI cache, create new cache if necessary, attach new panel if (!panels.containsKey(player.getUniqueId())) { panel = new AquaPanel(plugin); panels.put(player.getUniqueId(), panel); player.getMainScreen().attachPopupScreen(panel); } else { //Has a cached panel, so attach it panel = panels.get(player.getUniqueId()); player.getMainScreen().attachPopupScreen(panels.get(player.getUniqueId())); } panel.setLocation(block.getLocation()); panel.populate(lock); } @Override public void keyReleased(KeyBindingEvent keyBindingEvent) { //Does nothing } }
true
true
public void keyPressed(KeyBindingEvent keyBindingEvent) { final SpoutPlayer player = keyBindingEvent.getPlayer(); //Do not let them close another screen with this keybinding from this event if (!player.getMainScreen().getScreenType().equals(ScreenType.GAME_SCREEN)) { return; } Block block = BlockUtil.getTarget(player, null, 4); if (block == null) { player.sendMessage(plugin.getPrefix() + "No valid block at the cursor could be found!"); return; } AquaPanel panel; final Location loc = block.getLocation(); final Lock lock = plugin.getRegistry().getLock(loc.getWorld().getUID(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); if (!LockUtil.canPerformAction(player, lock == null ? "LOCK" : "UPDATE")) { return; } //Check for GUI cache, create new cache if necessary, attach new panel if (!panels.containsKey(player.getUniqueId())) { panel = new AquaPanel(plugin); panels.put(player.getUniqueId(), panel); player.getMainScreen().attachPopupScreen(panel); } else { //Has a cached panel, so attach it panel = panels.get(player.getUniqueId()); player.getMainScreen().attachPopupScreen(panels.get(player.getUniqueId())); } panel.setLocation(block.getLocation()); panel.populate(lock); }
public void keyPressed(KeyBindingEvent keyBindingEvent) { final SpoutPlayer player = keyBindingEvent.getPlayer(); //Do not let them close another screen with this keybinding from this event if (!keyBindingEvent.getScreenType().equals(ScreenType.GAME_SCREEN)) { return; } Block block = BlockUtil.getTarget(player, null, 4); if (block == null) { player.sendMessage(plugin.getPrefix() + "No valid block at the cursor could be found!"); return; } AquaPanel panel; final Location loc = block.getLocation(); final Lock lock = plugin.getRegistry().getLock(loc.getWorld().getUID(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); if (!LockUtil.canPerformAction(player, lock == null ? "LOCK" : "UPDATE")) { return; } //Check for GUI cache, create new cache if necessary, attach new panel if (!panels.containsKey(player.getUniqueId())) { panel = new AquaPanel(plugin); panels.put(player.getUniqueId(), panel); player.getMainScreen().attachPopupScreen(panel); } else { //Has a cached panel, so attach it panel = panels.get(player.getUniqueId()); player.getMainScreen().attachPopupScreen(panels.get(player.getUniqueId())); } panel.setLocation(block.getLocation()); panel.populate(lock); }
diff --git a/Demigods-Greek/src/main/java/com/censoredsoftware/demigods/greek/ability/passive/RainbowWalking.java b/Demigods-Greek/src/main/java/com/censoredsoftware/demigods/greek/ability/passive/RainbowWalking.java index b87be1f5..cb2d41fe 100644 --- a/Demigods-Greek/src/main/java/com/censoredsoftware/demigods/greek/ability/passive/RainbowWalking.java +++ b/Demigods-Greek/src/main/java/com/censoredsoftware/demigods/greek/ability/passive/RainbowWalking.java @@ -1,43 +1,43 @@ package com.censoredsoftware.demigods.greek.ability.passive; import com.censoredsoftware.demigods.engine.data.DCharacter; import com.censoredsoftware.demigods.engine.util.Zones; import com.censoredsoftware.demigods.greek.ability.GreekAbility; import com.censoredsoftware.demigods.greek.ability.ultimate.Discoball; import com.google.common.collect.Lists; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import java.util.List; public class RainbowWalking extends GreekAbility.Passive { private final static String name = "Rainbow Walking"; private final static int repeat = 5; private final static List<String> details = Lists.newArrayList("Spread the disco while sneaking."); public RainbowWalking(final String deity) { super(name, deity, repeat, details, null, new Runnable() { @Override public void run() { - for(DCharacter online : DCharacter.Util.getOnlineCharactersWithDeity("DrD1sco")) + for(DCharacter online : DCharacter.Util.getOnlineCharactersWithDeity(deity)) { Player player = online.getOfflinePlayer().getPlayer(); if(Zones.inNoDemigodsZone(player.getLocation()) || !player.isSneaking() || player.isFlying() || Zones.inNoPvpZone(player.getLocation()) || Zones.inNoBuildZone(player, player.getLocation())) continue; doEffect(player); } } private void doEffect(Player player) { for(Entity entity : player.getNearbyEntities(30, 30, 30)) if(entity instanceof Player) Discoball.rainbow(player, (Player) entity); Discoball.rainbow(player, player); Discoball.playRandomNote(player.getLocation(), 0.5F); } }); } }
true
true
public RainbowWalking(final String deity) { super(name, deity, repeat, details, null, new Runnable() { @Override public void run() { for(DCharacter online : DCharacter.Util.getOnlineCharactersWithDeity("DrD1sco")) { Player player = online.getOfflinePlayer().getPlayer(); if(Zones.inNoDemigodsZone(player.getLocation()) || !player.isSneaking() || player.isFlying() || Zones.inNoPvpZone(player.getLocation()) || Zones.inNoBuildZone(player, player.getLocation())) continue; doEffect(player); } } private void doEffect(Player player) { for(Entity entity : player.getNearbyEntities(30, 30, 30)) if(entity instanceof Player) Discoball.rainbow(player, (Player) entity); Discoball.rainbow(player, player); Discoball.playRandomNote(player.getLocation(), 0.5F); } }); }
public RainbowWalking(final String deity) { super(name, deity, repeat, details, null, new Runnable() { @Override public void run() { for(DCharacter online : DCharacter.Util.getOnlineCharactersWithDeity(deity)) { Player player = online.getOfflinePlayer().getPlayer(); if(Zones.inNoDemigodsZone(player.getLocation()) || !player.isSneaking() || player.isFlying() || Zones.inNoPvpZone(player.getLocation()) || Zones.inNoBuildZone(player, player.getLocation())) continue; doEffect(player); } } private void doEffect(Player player) { for(Entity entity : player.getNearbyEntities(30, 30, 30)) if(entity instanceof Player) Discoball.rainbow(player, (Player) entity); Discoball.rainbow(player, player); Discoball.playRandomNote(player.getLocation(), 0.5F); } }); }
diff --git a/core/test/net/sf/openrocket/preset/xml/BaseComponentDTOTest.java b/core/test/net/sf/openrocket/preset/xml/BaseComponentDTOTest.java index 0096810d..bbc609d9 100644 --- a/core/test/net/sf/openrocket/preset/xml/BaseComponentDTOTest.java +++ b/core/test/net/sf/openrocket/preset/xml/BaseComponentDTOTest.java @@ -1,72 +1,72 @@ package net.sf.openrocket.preset.xml; import net.sf.openrocket.motor.Manufacturer; import net.sf.openrocket.preset.ComponentPreset; import net.sf.openrocket.preset.ComponentPresetFactory; import net.sf.openrocket.preset.TypedPropertyMap; import org.junit.Assert; import org.junit.Test; import javax.imageio.ImageIO; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import java.awt.image.BufferedImage; import java.awt.image.DataBufferByte; import java.io.StringReader; import java.io.StringWriter; /** */ public class BaseComponentDTOTest { @Test public void testImage() throws Exception { TypedPropertyMap presetspec = new TypedPropertyMap(); presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.BODY_TUBE); presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); presetspec.put(ComponentPreset.PARTNO, "partno"); presetspec.put(ComponentPreset.LENGTH, 2.0); presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); presetspec.put(ComponentPreset.INNER_DIAMETER, 1.0); presetspec.put(ComponentPreset.MASS, 100.0); ComponentPreset preset = ComponentPresetFactory.create(presetspec); //Convert the presets to a BodyTubeDTO BodyTubeDTO dto = new BodyTubeDTO(preset); //Add an image to the DTO. - BufferedImage image = ImageIO.read(this.getClass().getResourceAsStream("or_launcher.png")); + BufferedImage image = ImageIO.read(this.getClass().getResourceAsStream("/pix/splashscreen.png")); dto.setImage(image); JAXBContext binder = JAXBContext.newInstance(OpenRocketComponentDTO.class); Marshaller marshaller = binder.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); StringWriter sw = new StringWriter(); //Serialize the dto to XML marshaller.marshal(dto, sw); String xml = sw.toString(); //Read the XML back to create the dto again Unmarshaller unmarshaller = binder.createUnmarshaller(); BodyTubeDTO redone = (BodyTubeDTO) unmarshaller.unmarshal(new StringReader(xml)); //Compare the image. Assert.assertArrayEquals(((DataBufferByte) image.getData().getDataBuffer()).getData(), ((DataBufferByte) redone.getImage().getData().getDataBuffer()).getData()); //Assert the rest of the attributes. Assert.assertEquals(dto.getInsideDiameter(), redone.getInsideDiameter(), 0.00001); Assert.assertEquals(dto.getLength(), redone.getLength(), 0.00001); Assert.assertEquals(dto.getOutsideDiameter(), redone.getOutsideDiameter(), 0.00001); Assert.assertEquals(dto.getDescription(), redone.getDescription()); Assert.assertEquals(dto.getManufacturer(), redone.getManufacturer()); Assert.assertEquals(dto.getMass(), redone.getMass(), 0.00001); Assert.assertEquals(dto.getPartNo(), redone.getPartNo()); //Uncomment if you want to write the image to a file to view it. // ImageIO.write(redone.getImage(), "png", new FileOutputStream("redone.png")); } }
true
true
public void testImage() throws Exception { TypedPropertyMap presetspec = new TypedPropertyMap(); presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.BODY_TUBE); presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); presetspec.put(ComponentPreset.PARTNO, "partno"); presetspec.put(ComponentPreset.LENGTH, 2.0); presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); presetspec.put(ComponentPreset.INNER_DIAMETER, 1.0); presetspec.put(ComponentPreset.MASS, 100.0); ComponentPreset preset = ComponentPresetFactory.create(presetspec); //Convert the presets to a BodyTubeDTO BodyTubeDTO dto = new BodyTubeDTO(preset); //Add an image to the DTO. BufferedImage image = ImageIO.read(this.getClass().getResourceAsStream("or_launcher.png")); dto.setImage(image); JAXBContext binder = JAXBContext.newInstance(OpenRocketComponentDTO.class); Marshaller marshaller = binder.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); StringWriter sw = new StringWriter(); //Serialize the dto to XML marshaller.marshal(dto, sw); String xml = sw.toString(); //Read the XML back to create the dto again Unmarshaller unmarshaller = binder.createUnmarshaller(); BodyTubeDTO redone = (BodyTubeDTO) unmarshaller.unmarshal(new StringReader(xml)); //Compare the image. Assert.assertArrayEquals(((DataBufferByte) image.getData().getDataBuffer()).getData(), ((DataBufferByte) redone.getImage().getData().getDataBuffer()).getData()); //Assert the rest of the attributes. Assert.assertEquals(dto.getInsideDiameter(), redone.getInsideDiameter(), 0.00001); Assert.assertEquals(dto.getLength(), redone.getLength(), 0.00001); Assert.assertEquals(dto.getOutsideDiameter(), redone.getOutsideDiameter(), 0.00001); Assert.assertEquals(dto.getDescription(), redone.getDescription()); Assert.assertEquals(dto.getManufacturer(), redone.getManufacturer()); Assert.assertEquals(dto.getMass(), redone.getMass(), 0.00001); Assert.assertEquals(dto.getPartNo(), redone.getPartNo()); //Uncomment if you want to write the image to a file to view it. // ImageIO.write(redone.getImage(), "png", new FileOutputStream("redone.png")); }
public void testImage() throws Exception { TypedPropertyMap presetspec = new TypedPropertyMap(); presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.BODY_TUBE); presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); presetspec.put(ComponentPreset.PARTNO, "partno"); presetspec.put(ComponentPreset.LENGTH, 2.0); presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); presetspec.put(ComponentPreset.INNER_DIAMETER, 1.0); presetspec.put(ComponentPreset.MASS, 100.0); ComponentPreset preset = ComponentPresetFactory.create(presetspec); //Convert the presets to a BodyTubeDTO BodyTubeDTO dto = new BodyTubeDTO(preset); //Add an image to the DTO. BufferedImage image = ImageIO.read(this.getClass().getResourceAsStream("/pix/splashscreen.png")); dto.setImage(image); JAXBContext binder = JAXBContext.newInstance(OpenRocketComponentDTO.class); Marshaller marshaller = binder.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); StringWriter sw = new StringWriter(); //Serialize the dto to XML marshaller.marshal(dto, sw); String xml = sw.toString(); //Read the XML back to create the dto again Unmarshaller unmarshaller = binder.createUnmarshaller(); BodyTubeDTO redone = (BodyTubeDTO) unmarshaller.unmarshal(new StringReader(xml)); //Compare the image. Assert.assertArrayEquals(((DataBufferByte) image.getData().getDataBuffer()).getData(), ((DataBufferByte) redone.getImage().getData().getDataBuffer()).getData()); //Assert the rest of the attributes. Assert.assertEquals(dto.getInsideDiameter(), redone.getInsideDiameter(), 0.00001); Assert.assertEquals(dto.getLength(), redone.getLength(), 0.00001); Assert.assertEquals(dto.getOutsideDiameter(), redone.getOutsideDiameter(), 0.00001); Assert.assertEquals(dto.getDescription(), redone.getDescription()); Assert.assertEquals(dto.getManufacturer(), redone.getManufacturer()); Assert.assertEquals(dto.getMass(), redone.getMass(), 0.00001); Assert.assertEquals(dto.getPartNo(), redone.getPartNo()); //Uncomment if you want to write the image to a file to view it. // ImageIO.write(redone.getImage(), "png", new FileOutputStream("redone.png")); }
diff --git a/src/au/com/addstar/truehardcore/CommandTH.java b/src/au/com/addstar/truehardcore/CommandTH.java index 5edacdf..98b2dd6 100644 --- a/src/au/com/addstar/truehardcore/CommandTH.java +++ b/src/au/com/addstar/truehardcore/CommandTH.java @@ -1,127 +1,127 @@ package au.com.addstar.truehardcore; /* * TrueHardcore * Copyright (C) 2013 add5tar <copyright at addstar dot com dot au> * * 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/> */ import org.bukkit.ChatColor; import org.bukkit.World; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import au.com.addstar.truehardcore.HardcorePlayers.HardcorePlayer; public class CommandTH implements CommandExecutor { private TrueHardcore plugin; public CommandTH(TrueHardcore instance) { plugin = instance; } /* * Handle the /truehardcore command */ public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { String action = ""; if (args.length > 0) { action = args[0].toUpperCase(); } if (action.equals("PLAY")) { if (Util.RequirePermission((Player) sender, "truehardcore.use")) { if (args.length > 1) { World world = plugin.getServer().getWorld(args[1]); if (world == null) { sender.sendMessage(ChatColor.RED + "Error: Unknown world!"); return true; } if (plugin.IsHardcoreWorld(world)) { plugin.PlayGame(world.getName(), (Player) sender); } else { sender.sendMessage(ChatColor.RED + "Error: That is not a hardcore world!"); } } else { sender.sendMessage(ChatColor.YELLOW + "Usage: /th play <world>"); } } } else if (action.equals("LEAVE")) { plugin.LeaveGame((Player) sender); } else if (action.equals("INFO")) { HardcorePlayer hcp = null; if (args.length == 1) { if (sender instanceof Player) { Player player = (Player) sender; hcp = plugin.HCPlayers.Get(player); hcp.updatePlayer(player); } else { sender.sendMessage(ChatColor.RED + "Usage: /th info <player> [world]"); } } else if (args.length == 2) { - Player player = (Player) plugin.getServer().getPlayer(args[2]); + Player player = (Player) plugin.getServer().getPlayer(args[1]); if (player != null) { hcp = plugin.HCPlayers.Get(player); if (plugin.IsHardcoreWorld(player.getWorld())) { hcp.updatePlayer(player); } } else { sender.sendMessage(ChatColor.RED + "Unknown player"); } } else if (args.length == 3) { hcp = plugin.HCPlayers.Get(args[2], args[1]); Player player = (Player) plugin.getServer().getPlayer(args[2]); if (player != null) { if (plugin.IsHardcoreWorld(player.getWorld())) { if (args[1] == player.getWorld().getName()) { hcp.updatePlayer(player); } } } } if (hcp != null) { sender.sendMessage(ChatColor.GREEN + "Hardcore player information:"); sender.sendMessage(ChatColor.YELLOW + "Player: " + ChatColor.AQUA + hcp.getPlayerName()); sender.sendMessage(ChatColor.YELLOW + "World: " + ChatColor.AQUA + hcp.getWorld()); sender.sendMessage(ChatColor.YELLOW + "State: " + ChatColor.AQUA + hcp.getState()); //sender.sendMessage(ChatColor.YELLOW + "Current XP: " + ChatColor.AQUA + hcp.getExp()); sender.sendMessage(ChatColor.YELLOW + "Current Level: " + ChatColor.AQUA + hcp.getLevel()); sender.sendMessage(ChatColor.YELLOW + "Total Score: " + ChatColor.AQUA + hcp.getScore()); sender.sendMessage(ChatColor.YELLOW + "Total Deaths: " + ChatColor.AQUA + hcp.getDeaths()); sender.sendMessage(ChatColor.YELLOW + "Top Score: " + ChatColor.AQUA + hcp.getTopScore()); } } else if (action.equals("LIST")) { for (String key : plugin.HCPlayers.AllRecords().keySet()) { HardcorePlayer hcp = plugin.HCPlayers.Get(key); sender.sendMessage(Util.padRight(key, 30) + " " + hcp.getState()); } } else { sender.sendMessage(ChatColor.LIGHT_PURPLE + "TrueHardcore Commands:"); sender.sendMessage(ChatColor.AQUA + "/th play " + ChatColor.YELLOW + ": Start or resume your hardcore game"); sender.sendMessage(ChatColor.AQUA + "/th leave " + ChatColor.YELLOW + ": Leave the hardcore game (progress is saved)"); } return true; } }
true
true
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { String action = ""; if (args.length > 0) { action = args[0].toUpperCase(); } if (action.equals("PLAY")) { if (Util.RequirePermission((Player) sender, "truehardcore.use")) { if (args.length > 1) { World world = plugin.getServer().getWorld(args[1]); if (world == null) { sender.sendMessage(ChatColor.RED + "Error: Unknown world!"); return true; } if (plugin.IsHardcoreWorld(world)) { plugin.PlayGame(world.getName(), (Player) sender); } else { sender.sendMessage(ChatColor.RED + "Error: That is not a hardcore world!"); } } else { sender.sendMessage(ChatColor.YELLOW + "Usage: /th play <world>"); } } } else if (action.equals("LEAVE")) { plugin.LeaveGame((Player) sender); } else if (action.equals("INFO")) { HardcorePlayer hcp = null; if (args.length == 1) { if (sender instanceof Player) { Player player = (Player) sender; hcp = plugin.HCPlayers.Get(player); hcp.updatePlayer(player); } else { sender.sendMessage(ChatColor.RED + "Usage: /th info <player> [world]"); } } else if (args.length == 2) { Player player = (Player) plugin.getServer().getPlayer(args[2]); if (player != null) { hcp = plugin.HCPlayers.Get(player); if (plugin.IsHardcoreWorld(player.getWorld())) { hcp.updatePlayer(player); } } else { sender.sendMessage(ChatColor.RED + "Unknown player"); } } else if (args.length == 3) { hcp = plugin.HCPlayers.Get(args[2], args[1]); Player player = (Player) plugin.getServer().getPlayer(args[2]); if (player != null) { if (plugin.IsHardcoreWorld(player.getWorld())) { if (args[1] == player.getWorld().getName()) { hcp.updatePlayer(player); } } } } if (hcp != null) { sender.sendMessage(ChatColor.GREEN + "Hardcore player information:"); sender.sendMessage(ChatColor.YELLOW + "Player: " + ChatColor.AQUA + hcp.getPlayerName()); sender.sendMessage(ChatColor.YELLOW + "World: " + ChatColor.AQUA + hcp.getWorld()); sender.sendMessage(ChatColor.YELLOW + "State: " + ChatColor.AQUA + hcp.getState()); //sender.sendMessage(ChatColor.YELLOW + "Current XP: " + ChatColor.AQUA + hcp.getExp()); sender.sendMessage(ChatColor.YELLOW + "Current Level: " + ChatColor.AQUA + hcp.getLevel()); sender.sendMessage(ChatColor.YELLOW + "Total Score: " + ChatColor.AQUA + hcp.getScore()); sender.sendMessage(ChatColor.YELLOW + "Total Deaths: " + ChatColor.AQUA + hcp.getDeaths()); sender.sendMessage(ChatColor.YELLOW + "Top Score: " + ChatColor.AQUA + hcp.getTopScore()); } } else if (action.equals("LIST")) { for (String key : plugin.HCPlayers.AllRecords().keySet()) { HardcorePlayer hcp = plugin.HCPlayers.Get(key); sender.sendMessage(Util.padRight(key, 30) + " " + hcp.getState()); } } else { sender.sendMessage(ChatColor.LIGHT_PURPLE + "TrueHardcore Commands:"); sender.sendMessage(ChatColor.AQUA + "/th play " + ChatColor.YELLOW + ": Start or resume your hardcore game"); sender.sendMessage(ChatColor.AQUA + "/th leave " + ChatColor.YELLOW + ": Leave the hardcore game (progress is saved)"); } return true; }
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { String action = ""; if (args.length > 0) { action = args[0].toUpperCase(); } if (action.equals("PLAY")) { if (Util.RequirePermission((Player) sender, "truehardcore.use")) { if (args.length > 1) { World world = plugin.getServer().getWorld(args[1]); if (world == null) { sender.sendMessage(ChatColor.RED + "Error: Unknown world!"); return true; } if (plugin.IsHardcoreWorld(world)) { plugin.PlayGame(world.getName(), (Player) sender); } else { sender.sendMessage(ChatColor.RED + "Error: That is not a hardcore world!"); } } else { sender.sendMessage(ChatColor.YELLOW + "Usage: /th play <world>"); } } } else if (action.equals("LEAVE")) { plugin.LeaveGame((Player) sender); } else if (action.equals("INFO")) { HardcorePlayer hcp = null; if (args.length == 1) { if (sender instanceof Player) { Player player = (Player) sender; hcp = plugin.HCPlayers.Get(player); hcp.updatePlayer(player); } else { sender.sendMessage(ChatColor.RED + "Usage: /th info <player> [world]"); } } else if (args.length == 2) { Player player = (Player) plugin.getServer().getPlayer(args[1]); if (player != null) { hcp = plugin.HCPlayers.Get(player); if (plugin.IsHardcoreWorld(player.getWorld())) { hcp.updatePlayer(player); } } else { sender.sendMessage(ChatColor.RED + "Unknown player"); } } else if (args.length == 3) { hcp = plugin.HCPlayers.Get(args[2], args[1]); Player player = (Player) plugin.getServer().getPlayer(args[2]); if (player != null) { if (plugin.IsHardcoreWorld(player.getWorld())) { if (args[1] == player.getWorld().getName()) { hcp.updatePlayer(player); } } } } if (hcp != null) { sender.sendMessage(ChatColor.GREEN + "Hardcore player information:"); sender.sendMessage(ChatColor.YELLOW + "Player: " + ChatColor.AQUA + hcp.getPlayerName()); sender.sendMessage(ChatColor.YELLOW + "World: " + ChatColor.AQUA + hcp.getWorld()); sender.sendMessage(ChatColor.YELLOW + "State: " + ChatColor.AQUA + hcp.getState()); //sender.sendMessage(ChatColor.YELLOW + "Current XP: " + ChatColor.AQUA + hcp.getExp()); sender.sendMessage(ChatColor.YELLOW + "Current Level: " + ChatColor.AQUA + hcp.getLevel()); sender.sendMessage(ChatColor.YELLOW + "Total Score: " + ChatColor.AQUA + hcp.getScore()); sender.sendMessage(ChatColor.YELLOW + "Total Deaths: " + ChatColor.AQUA + hcp.getDeaths()); sender.sendMessage(ChatColor.YELLOW + "Top Score: " + ChatColor.AQUA + hcp.getTopScore()); } } else if (action.equals("LIST")) { for (String key : plugin.HCPlayers.AllRecords().keySet()) { HardcorePlayer hcp = plugin.HCPlayers.Get(key); sender.sendMessage(Util.padRight(key, 30) + " " + hcp.getState()); } } else { sender.sendMessage(ChatColor.LIGHT_PURPLE + "TrueHardcore Commands:"); sender.sendMessage(ChatColor.AQUA + "/th play " + ChatColor.YELLOW + ": Start or resume your hardcore game"); sender.sendMessage(ChatColor.AQUA + "/th leave " + ChatColor.YELLOW + ": Leave the hardcore game (progress is saved)"); } return true; }
diff --git a/src/plugins/Freetalk/Message.java b/src/plugins/Freetalk/Message.java index db48f607..b508c920 100644 --- a/src/plugins/Freetalk/Message.java +++ b/src/plugins/Freetalk/Message.java @@ -1,1207 +1,1206 @@ /* This code is part of Freenet. It is distributed under the GNU General * Public License, version 2 (or at your option any later version). See * http://www.gnu.org/ for further details of the GPL. */ package plugins.Freetalk; import java.io.UnsupportedEncodingException; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Set; import java.util.StringTokenizer; import java.util.UUID; import plugins.Freetalk.Identity.IdentityID; import plugins.Freetalk.Persistent.IndexedField; import plugins.Freetalk.exceptions.InvalidParameterException; import plugins.Freetalk.exceptions.NoSuchBoardException; import plugins.Freetalk.exceptions.NoSuchMessageException; import freenet.keys.FreenetURI; import freenet.support.Logger; import freenet.support.StringValidityChecker; import freenet.support.codeshortification.IfNotEquals; /** * A Freetalk message. This class is supposed to be used by the UI directly for reading messages. The UI can obtain message objects by querying * them from a <code>MessageManager</code>. A message has the usual attributes (author, boards to which it is posted, etc.) one would assume. * There are two unique ways to reference a message: It's URI and it's message ID. The URI is to be given to the user if he wants to tell other * people about the message, the message ID is to be used for querying the database for a message in a fast way. * * Activation policy: Class Message does automatic activation on its own. * This means that objects of class Message can be activated to a depth of only 1 when querying them from the database. * All methods automatically activate the object to any needed higher depth. * * @author xor ([email protected]) * @author saces */ // @IndexedClass // I can't think of any query which would need to get all Message objects. @IndexedField(names = {"mCreationDate"}) public abstract class Message extends Persistent { /* Public constants */ // TODO: Get rid of the String.length() limit and only use the byte[].length limit. public final static int MAX_MESSAGE_TITLE_TEXT_LENGTH = 256; // String.length() public final static int MAX_MESSAGE_TITLE_BYTE_LENGTH = 256; public final static int MAX_MESSAGE_TEXT_LENGTH = 64*1024; public final static int MAX_MESSAGE_TEXT_BYTE_LENGTH = 64*1024; // byte[].length public final static int MAX_BOARDS_PER_MESSAGE = 16; public final static int MAX_ATTACHMENTS_PER_MESSAGE = 256; /* Attributes, stored in the database */ /** * The URI of this message. */ protected MessageURI mURI; /* Not final because for OwnMessages it is set after the MessageList was inserted */ /** * The physical URI of the message. Null until the message was inserted and the URI is known. */ protected FreenetURI mFreenetURI; /* Not final because for OwnMessages it is set after the Message was inserted */ /** * The ID of the message. Format: Hex encoded author routing key + "@" + hex encoded random UUID. */ @IndexedField /* IndexedField because it is our primary key */ protected final String mID; protected MessageList mMessageList; /* Not final because OwnMessages are assigned to message lists after a certain delay */ /** * The URI of the thread this message belongs to. * Notice that the message referenced by this URI might NOT be a thread itself - you are allowed to reply to a message saying that the message is a thread * even though it is a reply to a different thread. Doing this is called forking a thread. */ protected final MessageURI mThreadURI; /** * The parent thread ID which was calculated from {@link mThreadURI} */ @IndexedField /* IndexedField for being able to query all messages of a thread */ protected final String mThreadID; /** * The URI of the message to which this message is a reply. Null if it is a thread. */ protected final MessageURI mParentURI; /** * The parent message ID which was calculated from {@link mParentURI} */ @IndexedField /* IndexedField for being able to get all replies to a message */ protected final String mParentID; /** * The boards to which this message was posted, in alphabetical order. */ protected final Board[] mBoards; protected final Board mReplyToBoard; protected final Identity mAuthor; protected final String mTitle; /** * The date when the message was written in <strong>UTC time</strong>. */ protected final Date mDate; protected final String mText; /** * The attachments of this message, in the order in which they were received in the original message. */ protected final Attachment[] mAttachments; public static class Attachment extends Persistent { private Message mMessage; private final FreenetURI mURI; @IndexedField private final String mFilename; private final long mSize; /* Size in bytes */ // TODO: Store mime type and maybe some hashes. // TODO: Store filename for search indexing // TODO: Require size > 0 and obtain the size before posting a message public Attachment(FreenetURI myURI, long mySize) { if(myURI == null) throw new IllegalArgumentException("URI is null"); if(mySize < 0) throw new IllegalArgumentException("Size is negative"); mMessage = null; // Is not available when the UI constructs attachments mURI = myURI; mFilename = mURI.getPreferredFilename(); mSize = mySize; } public void databaseIntegrityTest() throws Exception { checkedActivate(3); if(mMessage == null) throw new NullPointerException("mMessage==null"); if(mURI == null) throw new NullPointerException("mURI==null"); if(mSize < 0) throw new IllegalStateException("mSize is negative: " + mSize); if(mFilename == null) throw new NullPointerException("mFilename==null"); if(!mFilename.equals(mURI.getPreferredFilename())) throw new IllegalStateException("mFilename does not match expected filename: mFilename==" + mFilename + "; expected==" + mURI.getPreferredFilename()); // TODO: FFS, is there really no array search library function which is not binary search?? for(Attachment a : mMessage.getAttachments()) { if(a == this) return; } throw new IllegalStateException("mMessage does not have this attachment: " + mMessage); } protected void setMessage(Message message) { mMessage = message; } public Message getMessage() { checkedActivate(2); mMessage.initializeTransient(mFreetalk); return mMessage; } public FreenetURI getURI() { checkedActivate(3); return mURI; } public String getFilename() { // checkedActivate(1); not needed, String is a db4o primitive return mFilename; } public long getSize() { // checkedActivate(1); not needed, long is a db4o primitive return mSize; } @Override protected void storeWithoutCommit() { try { checkedActivate(3); // TODO: Figure out a suitable depth. // You have to take care to keep the list of stored objects synchronized with those being deleted in removeFrom() ! checkedStore(mURI); checkedStore(); } catch(RuntimeException e) { checkedRollbackAndThrow(e); } } @Override protected void deleteWithoutCommit() { try { checkedActivate(3); // TODO: Figure out a suitable depth. checkedDelete(); mURI.removeFrom(mDB); } catch(RuntimeException e) { checkedRollbackAndThrow(e); } } } /** * The thread to which this message is a reply. */ private Message mThread = null; /** * The message to which this message is a reply. */ private Message mParent = null; /** * Whether this message was linked into all it's boards. For an explanation of this flag please read the documentation of {@link wasLinkedIn}. */ @IndexedField /* IndexedField because the message manager needs to query for all messages which have not been linked in */ private boolean mWasLinkedIn = false; /** * A class for representing and especially verifying message IDs. * We do not use it as a type for storing it because that would make the database queries significantly slower. */ public static final class MessageID { /** * UUID length + "@" length + identity ID length */ public final static int MAX_MESSAGE_ID_LENGTH = 36 + 1 + Identity.IdentityID.MAX_IDENTITY_ID_LENGTH; private final String mID; private final IdentityID mAuthorID; private final UUID mUUID; private MessageID(String id) { if(id.length() > MAX_MESSAGE_ID_LENGTH) throw new IllegalArgumentException("ID is too long, length: " + id.length()); mID = id; final StringTokenizer tokenizer = new StringTokenizer(id, "@"); // TODO: Further verification try { mUUID = UUID.fromString(tokenizer.nextToken()); } catch(IllegalArgumentException e) { throw new IllegalArgumentException("Invalid UUID in message ID:" + id); } mAuthorID = IdentityID.construct(tokenizer.nextToken()); if(tokenizer.hasMoreTokens()) throw new IllegalArgumentException("Invalid MessageID: " + id); } private MessageID(UUID uuid, FreenetURI authorRequestURI) { if(uuid == null) throw new NullPointerException("UUID is null"); if(authorRequestURI == null) throw new NullPointerException("URI is null"); if(!authorRequestURI.isUSK() && !authorRequestURI.isSSK()) throw new IllegalArgumentException("URI is no USK/SSK"); mUUID = uuid; mAuthorID = IdentityID.constructFromURI(authorRequestURI); mID = mUUID + "@" + mAuthorID; } public static final MessageID construct(String id) { return new MessageID(id); // TODO: Optimization: Write a nonvalidating constructor & change callers to use it if possible. } public static final MessageID construct(Message fromMessage) { return new MessageID(fromMessage.getID()); // TODO: Optimization: Write and use a non-validating constructor. } public static final MessageID construct(UUID uuid, FreenetURI authorRequestURI) { return new MessageID(uuid, authorRequestURI); } public static final MessageID constructRandomID(Identity author) { return new MessageID(UUID.randomUUID() + "@" + author.getID()); } public final void throwIfAuthorDoesNotMatch(Identity author) { if(!mAuthorID.equals(author.getID())) throw new IllegalArgumentException("Message ID contains the wrong author ID (should be " + author.getID() + "): " + mID); } public final void throwIfAuthorDoesNotMatch(IdentityID authorID) { if(!mAuthorID.equals(authorID)) throw new IllegalArgumentException("Message ID contains the wrong author ID (should be " + authorID + "): " + mID); } public final String toString() { return mID; } public final UUID getUUID() { return mUUID; } public final IdentityID getAuthorID() { return mAuthorID; } public final boolean equals(final Object o) { if(o instanceof MessageID) return mID.equals(((MessageID)o).mID); if(o instanceof String) return mID.equals(o); return false; } } protected Message(MessageURI newURI, FreenetURI newFreenetURI, MessageID newID, MessageList newMessageList, MessageURI newThreadURI, MessageURI newParentURI, Set<Board> newBoards, Board newReplyToBoard, Identity newAuthor, String newTitle, Date newDate, String newText, List<Attachment> newAttachments) throws InvalidParameterException { if(newURI != null) // May be null first for own messages newURI.throwIfAuthorDoesNotMatch(newAuthor); // newFreenetURI cannot be validated, it is allowed to be CHK if(newFreenetURI != null) { if(!newFreenetURI.isCHK()) throw new IllegalArgumentException("Invalid FreenetURI, not CHK:" + newFreenetURI); } newID.throwIfAuthorDoesNotMatch(newAuthor); if(newMessageList != null && newMessageList.getAuthor() != newAuthor) throw new InvalidParameterException("The author of the given message list is not the author of this message: " + newURI); try { if(newFreenetURI != null) newMessageList.getReference(newFreenetURI); } catch(NoSuchMessageException e) { throw new InvalidParameterException("The given message list does not contain this message: " + newURI); } if (newBoards.isEmpty()) throw new InvalidParameterException("No boards in message " + newURI); if (newBoards.size() > MAX_BOARDS_PER_MESSAGE) throw new InvalidParameterException("Too many boards in message " + newURI); if (newReplyToBoard != null && !newBoards.contains(newReplyToBoard)) { Logger.error(this, "Message created with replyToBoard not being in newBoards: " + newURI); newBoards.add(newReplyToBoard); } mURI = newURI != null ? newURI.clone() : null; mFreenetURI = newFreenetURI != null ? newFreenetURI.clone() : null; mMessageList = newMessageList; mAuthor = newAuthor; mID = newID.toString(); // There are 4 possible combinations: // Thread URI specified, parent URI specified: We are replying to the given message in the given thread. // Thread URI specified, parent URI not specified: We are replying to the given thread directly, parent URI will be set to thread URI. // Thread URI not specified, parent URI not specified: We are creating a new thread. // Thread URI not specified, parent URI specified: Invalid, we throw an exception. // // The last case is invalid because the thread URI of a message is the primary information which decides in which thread it is displayed // and you can link replies into multiple threads by replying to them with different thread URIs... so if there is only a parent URI and // no thread URI we cannot decide to which thread the message belongs because the parent might belong to multiple thread. if(newParentURI != null && newThreadURI == null) Logger.error(this, "Message with parent URI but without thread URI created: " + newURI); mParentURI = newParentURI != null ? newParentURI.clone() : (newThreadURI != null ? newThreadURI.clone() : null); mParentID = mParentURI != null ? mParentURI.getMessageID() : null; /* If the given thread URI is null, the message will be a thread */ mThreadURI = newThreadURI != null ? newThreadURI.clone() : null; mThreadID = newThreadURI != null ? newThreadURI.getMessageID() : null; if(mID.equals(mParentID)) throw new InvalidParameterException("A message cannot be parent of itself."); if(mID.equals(mThreadID)) throw new InvalidParameterException("A message cannot have itself as thread."); mBoards = newBoards.toArray(new Board[newBoards.size()]); Arrays.sort(mBoards); // We use binary search in some places mReplyToBoard = newReplyToBoard; mTitle = makeTitleValid(newTitle); if(newDate.after(getFetchDate())) { Logger.warning(this, "Received bogus message date: Now = " + getFetchDate() + "; message date = " + newDate + "; message=" + mURI); mDate = getFetchDate(); } else { mDate = newDate; // TODO: Check out whether Date provides a function for getting the timezone and throw an Exception if not UTC. } mText = makeTextValid(newText); if (!isTitleValid(mTitle)) // TODO: Usability: Change the function to "throwIfTitleIsInvalid" so it can give a reason. throw new InvalidParameterException("Invalid message title in message " + newURI); if (!isTextValid(mText)) // TODO: Usability: Change the function to "throwIfTextIsInvalid" so it can give a reason. throw new InvalidParameterException("Invalid message text in message " + newURI); if(newAttachments != null) { if(newAttachments.size() > MAX_ATTACHMENTS_PER_MESSAGE) throw new InvalidParameterException("Too many attachments in message: " + newAttachments.size()); mAttachments = newAttachments.toArray(new Attachment[newAttachments.size()]); for(Attachment a : mAttachments) a.setMessage(this); } else { mAttachments = null; } } @Override public void databaseIntegrityTest() throws Exception { checkedActivate(3); if(mID == null) throw new NullPointerException("mID==null"); if(mAuthor == null) throw new NullPointerException("mAuthor==null"); MessageID.construct(mID).throwIfAuthorDoesNotMatch(mAuthor); if(!(this instanceof OwnMessage)) { if(mURI == null) throw new NullPointerException("mURI==null"); if(mFreenetURI == null) throw new NullPointerException("mFreenetURI==null"); if(mMessageList == null) throw new IllegalStateException("mMessageList==null"); } if(mURI != null) { final MessageURI messageURI = getURI(); // Call intializeTransient // The following check would be wrong (explanation below): // if(!messageURI.getFreenetURI().equals(mFreenetURI)) // throw new IllegalStateException("mURI and mFreenetURI mismatch: mURI==" + mURI + "; mFreenetURI==" + mFreenetURI); // It would be wrong because message URI contains the URI of the message list, not the URI of the message itself. messageURI.throwIfAuthorDoesNotMatch(mAuthor); if(!messageURI.getMessageID().equals(mID)) throw new IllegalStateException("mID == " + mID + " not matched for mURI == " + mURI); } if(mMessageList != null) { // If we are an OwnMessage and mMessageList is non-null then the URIs should also be non-null if(mURI == null) throw new NullPointerException("mURI == null"); if(mFreenetURI == null) throw new NullPointerException("mFreenetURI == null"); final MessageList messageList = getMessageList(); // Call initializeTransient if(!messageList.getURI().equals(getURI().getFreenetURI())) throw new IllegalStateException("getURI().getFreenetURI() == " + getURI().getFreenetURI() + " but mMessageList.getURI() == " + messageList.getURI()); if(messageList.getAuthor() != mAuthor) throw new IllegalStateException("mMessageList author does not match mAuthor: " + mMessageList); try { final MessageList.MessageReference ref = getMessageList().getReference(mFreenetURI); IfNotEquals.thenThrow(mID, ref.getMessageID(), "mID"); } catch(NoSuchMessageException e) { throw new IllegalStateException("mMessageList does not contain this message: " + mMessageList); } } if(mParentURI == null ^ mThreadURI == null) throw new IllegalStateException("mParentURI==" + mParentURI + " but mThreadURI==" + mThreadURI); if(mParentURI != null) { // Thread URI != null aswell final String parentID = getParentURI().getMessageID(); if(parentID.equals(mID)) throw new IllegalStateException("mParentURI points to the message itself"); if(!parentID.equals(mParentID)) throw new IllegalStateException("mParentURI==" + mParentURI + " but mParentID=="+parentID); final String threadID = getThreadURI().getMessageID(); if(threadID.equals(mID)) throw new IllegalStateException("mThreadURI points to the message itself"); if(!threadID.equals(mThreadID)) throw new IllegalStateException("mThreadURI==" + mThreadURI + " but mThreadID=="+threadID); } else { // Parent URI is null => Thread URI is null => No parent message / thread should be set. if(mParent != null) throw new IllegalStateException("mParent == " + mParent); if(mThread != null) throw new IllegalStateException("mThread == " + mThread); } { if(mBoards == null) throw new NullPointerException("mBoards==null"); if(mBoards.length < 1) throw new IllegalStateException("mBoards is empty"); if(mBoards.length > MAX_BOARDS_PER_MESSAGE) throw new IllegalStateException("mBoards contains too many boards: " + mBoards.length); - if(mReplyToBoard == null) - throw new NullPointerException("mReplToBoard==null"); + // mReplyToBoard may be null if replies are desired to all boards - boolean replyToBoardWasFound = false; + boolean replyToBoardWasFound = mReplyToBoard == null ? true : false; for(Board board : mBoards) { if(board == null) throw new NullPointerException("mBoards contains null entry"); if(board == mReplyToBoard) replyToBoardWasFound = true; if(board instanceof SubscribedBoard) throw new IllegalStateException("mBoard contains a SubscribedBoard: " + board); } if(!replyToBoardWasFound) throw new IllegalStateException("mBoards does not contain mReplyToBoard"); } if(!isTitleValid(mTitle)) // Checks for null aswell throw new IllegalStateException("Title is not valid: " + mTitle); if(!isTextValid(mText)) // Checks for null aswell throw new IllegalStateException("Text is not valid"); if(mDate == null) throw new NullPointerException("mDate==null"); if(mDate.after(getFetchDate())) throw new IllegalStateException("mDate==" + mDate + " after mFetchDate==" + getFetchDate()); if(mAttachments != null && mAttachments.length > MAX_ATTACHMENTS_PER_MESSAGE) throw new IllegalStateException("mAttachments contains too many attachments: " + mAttachments.length); // Attachments inherit class Persistent and therefore have their own integrity test if(mThread != null && !mThreadID.equals(mThread.getID())) throw new IllegalStateException("mThread does not match thread ID: " + mThread); if(mParent != null && !mParentID.endsWith(mParent.getID())) throw new IllegalStateException("mParent does not match parent ID: " + mParent); if(mWasLinkedIn) { for(Board board : mBoards) { try { board.initializeTransient(mFreetalk); board.getMessageLink(this); } catch(NoSuchMessageException e) { throw new IllegalStateException("mWasLinkedIn==true but not found in board " + board); } } } } /** * Get the URI of the message. */ public MessageURI getURI() { /* Not synchronized because only OwnMessage might change the URI */ checkedActivate(3); // It's likely that the URI will be used so we fully activate it. assert(mURI != null); mURI.initializeTransient(mFreetalk); return mURI; } /** * Gets the FreenetURI where this message is actually stored, i.e. the CHK URI of the message. */ protected FreenetURI getFreenetURI() { checkedActivate(2); assert(mFreenetURI != null); return mFreenetURI; } public final String getID() { return mID; // Is final. } public final synchronized MessageList getMessageList() { checkedActivate(2); assert(mMessageList != null); mMessageList.initializeTransient(mFreetalk); return mMessageList; } protected final synchronized void clearMessageList() { checkedActivate(2); mMessageList = null; storeWithoutCommit(); } /** * Get the MessageURI of the thread this message belongs to. * @throws NoSuchMessageException */ public final synchronized MessageURI getThreadURI() throws NoSuchMessageException { checkedActivate(2); if(mThreadURI == null) throw new NoSuchMessageException(); return mThreadURI; } /** * Get the ID of the thread this message belongs to. Should not be used by the user interface for querying the database as the parent * thread might not have been downloaded yet. Use getThread() instead. * * Notice that the message referenced by this ID might NOT be a thread itself - you are allowed to reply to a message saying that the message is a thread * even though it is a reply to a different thread. Doing this is called forking a thread. * * @return The ID of the message's parent thread. * @throws NoSuchMessageException If the message is a thread itself. */ public final synchronized String getThreadID() throws NoSuchMessageException { // checkedActivate(1); if(mThreadID == null) throw new NoSuchMessageException(); return mThreadID; } /** * Gets the thread ID and throws a RuntimeException if it does not exist. * * getThreadID() would throw a NoSuchMessageException which is not a RuntimeException - if you have checked that isThread()==false already * you want a RuntimeException because getThreadID should not throw. * * @return */ public final String getThreadIDSafe() { try { return getThreadID(); } catch(NoSuchMessageException e) { throw new RuntimeException(e); } } /** * Get the MessageURI to which this message is a reply. Null if the message is a thread. */ public final MessageURI getParentURI() throws NoSuchMessageException { checkedActivate(3); // It's likely that the URI will be used so we fully activate it. if(mParentURI == null) throw new NoSuchMessageException(); mParentURI.initializeTransient(mFreetalk); return mParentURI; } public final String getParentID() throws NoSuchMessageException { // checkedActivate(1); if(mParentID == null) throw new NoSuchMessageException(); return mParentID; } /** * Gets the parent ID and throws a RuntimeException if it does not exist. * * getParentID() would throw a NoSuchMessageException which is not a RuntimeException - if you have checked that isThread()==false already * you want a RuntimeException because getParentID should not throw. * * @return */ public final String getParentIDSafe() { try { return getParentID(); } catch(NoSuchMessageException e) { throw new RuntimeException(e); } } /** * Returns true if the message is a thread. A message is considered as a thread if and only if it does not specify the URI of a parent thread - even if it does * specify the URI of a parent message it is still a thread if there is no parent thread URI! */ public final boolean isThread() { checkedActivate(2); return mThreadURI == null; } /** * Get the boards to which this message was posted. The boards are returned in alphabetical order. * The transient fields of the returned boards are initialized already. */ public final Board[] getBoards() { checkedActivate(2); assert(mBoards != null); for(Board b : mBoards) b.initializeTransient(mFreetalk); return mBoards; } public final Board getReplyToBoard() throws NoSuchBoardException { checkedActivate(2); if(mReplyToBoard == null) throw new NoSuchBoardException(); mReplyToBoard.initializeTransient(mFreetalk); return mReplyToBoard; } /** * Get the author of the message. */ public final Identity getAuthor() { checkedActivate(2); assert(mAuthor != null); if(mAuthor instanceof Persistent) { Persistent author = (Persistent)mAuthor; author.initializeTransient(mFreetalk); } return mAuthor; } /** * Get the title of the message. */ public final String getTitle() { // checkedActivate(1); assert(mTitle != null); return mTitle; } /** * Get the date when the message was written in <strong>UTC time</strong>. */ public final Date getDate() { // checkedActivate(1); assert(mDate != null); return mDate; } /** * Get the date when the message was fetched by Freetalk. */ public final Date getFetchDate() { // checkedActivate(1); assert(mCreationDate != null); return mCreationDate; } /** * Get the text of the message. */ public final String getText() { // checkedActivate(1); assert(mText != null); return mText; } /** * Get the attachments of the message, in the order in which they were received. */ public final Attachment[] getAttachments() { checkedActivate(3); for(Attachment a : mAttachments) a.initializeTransient(mFreetalk); return mAttachments; } /** * Get the thread to which this message belongs. The transient fields of the returned message will be initialized already. * * Notice that the returned message might not be a thread itself - you are allowed to reply to a message saying that the message is a thread * even though it is a reply to a different thread. Doing this is called forking a thread. * * @throws NoSuchMessageException If the parent thread of this message was not downloaded yet. */ public final synchronized Message getThread() throws NoSuchMessageException { /* TODO: Find all usages of this function and check whether we might want to use a higher depth here */ checkedActivate(2); if(mThread == null) throw new NoSuchMessageException(); mThread.initializeTransient(mFreetalk); return mThread; } public final synchronized void setThread(Message newParentThread) { assert(mThread == null || mThread == newParentThread); if(mThread != null) Logger.warning(this, "Thread already exists for " + this + ": existing==" + mThread + "; new==" + newParentThread); if(!newParentThread.getID().equals(mThreadID)) // mThreadID needs no activation throw new IllegalArgumentException("Trying to set a message as thread which has the wrong ID: " + newParentThread.getID()); if(newParentThread instanceof OwnMessage) throw new IllegalArgumentException("Trying to set an OwnMessage as parent thread: " + newParentThread); mThread = newParentThread; storeWithoutCommit(); } protected final synchronized void clearThread() { mThread = null; storeWithoutCommit(); } /** * Get the message to which this message is a reply. The transient fields of the returned message will be initialized already. */ public synchronized Message getParent() throws NoSuchMessageException { /* TODO: Find all usages of this function and check whether we might want to use a higher depth here */ checkedActivate(2); if(mParent == null) throw new NoSuchMessageException(); mParent.initializeTransient(mFreetalk); return mParent; } public final synchronized void setParent(Message newParent) { assert(mParent == null || newParent == mParent); if(mParent != null) Logger.warning(this, "Parent already exists for " + this + ": existing==" + mParent + "; new==" + newParent); if(!newParent.getID().equals(mParentID)) // mParentID needs no activation throw new IllegalArgumentException("Trying to set a message as parent which has the wrong ID: " + newParent.getID()); if(newParent instanceof OwnMessage) throw new IllegalArgumentException("Trying to set an OwnMessage as parent: " + newParent); mParent = newParent; storeWithoutCommit(); } protected final synchronized void clearParent() { mParent = null; storeWithoutCommit(); } /** * @return Returns a flag which indicates whether this message was linked into all boards where it should be visible (by calling addMessage() on those boards). * A message will only be visible in boards where it was linked in - the sole storage of a object of type Message does not make it visible. * */ protected final synchronized boolean wasLinkedIn() { // checkedActivate(1); return mWasLinkedIn; } /** * Sets the wasLinkedIn flag of this message. * For an explanation of this flag please read the documentation of {@link wasLinkedIn}. */ protected final synchronized void setLinkedIn(boolean wasLinkedIn) { mWasLinkedIn = wasLinkedIn; } /** * Checks whether the title of the message is valid. Validity conditions: * - Not empty * - No line breaks, tabs, or any other control characters. * - No invalid characters. * - valid UTF-8 encoding * - No invalid UTF formatting (unpaired direction or annotation characters). * - Not too long */ public static final boolean isTitleValid(String title) { if(title == null) return false; if(title.length() == 0) return false; if(title.length() > MAX_MESSAGE_TITLE_TEXT_LENGTH) return false; try { if (title.getBytes("UTF-8").length > MAX_MESSAGE_TITLE_BYTE_LENGTH) { return false; } } catch(UnsupportedEncodingException e) { return false; } return (StringValidityChecker.containsNoInvalidCharacters(title) && StringValidityChecker.containsNoLinebreaks(title) && StringValidityChecker.containsNoControlCharacters(title) && StringValidityChecker.containsNoInvalidFormatting(title)); } /** * Checks whether the text of the message is valid. Validity conditions: * - Not null * - Not more than MAX_MESSAGE_TEXT_LENGTH characters or MAX_MESSAGE_TEXT_BYTE_LENGTH bytes. * - Valid UTF-8 encoding. * - Contains no invalid UTF formatting (unpaired direction or annotation characters). * - Control characters are allowed: We want to allow other plugins to use Freetalk as their core, therefore we should not be too restrictive about * message content. Freetalk user interfaces have to take care on their own to be secure against weird control characters. */ public static final boolean isTextValid(String text) { if (text == null) { return false; } if (text.length() > MAX_MESSAGE_TEXT_LENGTH) { return false; } try { if (text.getBytes("UTF-8").length > MAX_MESSAGE_TEXT_BYTE_LENGTH) { return false; } } catch(UnsupportedEncodingException e) { return false; } return (StringValidityChecker.containsNoInvalidCharacters(text) && StringValidityChecker.containsNoInvalidFormatting(text)); } /** * Makes the passed title valid in means of <code>isTitleValid()</code> * @see isTitleValid */ public static final String makeTitleValid(String title) { // TODO: the newline handling here is based on the RFC 822 // format (newline + linear white space = single space). If // necessary, we could move that part of the cleaning-up to // ui.NNTP.ArticleParser, but the same algorithm should work // fine in the general case. // TODO: Why are we only replacing multiple whitespace with a single one if a newline is prefixed? StringBuilder result = new StringBuilder(); boolean replacingNewline = false; int dirCount = 0; boolean inAnnotatedText = false; boolean inAnnotation = false; for (int i = 0; i < title.length(); ) { int c = title.codePointAt(i); i += Character.charCount(c); if (c == '\r' || c == '\n') { if (!replacingNewline) { replacingNewline = true; result.append(' '); } } else if (c == '\t' || c == ' ') { if (!replacingNewline) result.append(' '); } else if (c == 0x202A // LEFT-TO-RIGHT EMBEDDING || c == 0x202B // RIGHT-TO-LEFT EMBEDDING || c == 0x202D // LEFT-TO-RIGHT OVERRIDE || c == 0x202E) { // RIGHT-TO-LEFT OVERRIDE dirCount++; result.appendCodePoint(c); } else if (c == 0x202C) { // POP DIRECTIONAL FORMATTING if (dirCount > 0) { dirCount--; result.appendCodePoint(c); } } else if (c == 0xFFF9) { // INTERLINEAR ANNOTATION ANCHOR if (!inAnnotatedText && !inAnnotation) { result.appendCodePoint(c); inAnnotatedText = true; } } else if (c == 0xFFFA) { // INTERLINEAR ANNOTATION SEPARATOR if (inAnnotatedText) { result.appendCodePoint(c); inAnnotatedText = false; inAnnotation = true; } } else if (c == 0xFFFB) { // INTERLINEAR ANNOTATION TERMINATOR if (inAnnotation) { result.appendCodePoint(c); inAnnotation = false; } } else if ((c & 0xFFFE) == 0xFFFE) { // invalid character, ignore } else { replacingNewline = false; switch (Character.getType(c)) { case Character.CONTROL: case Character.SURROGATE: case Character.LINE_SEPARATOR: case Character.PARAGRAPH_SEPARATOR: break; default: result.appendCodePoint(c); } } } if (inAnnotatedText) { result.appendCodePoint(0xFFFA); result.appendCodePoint(0xFFFB); } else if (inAnnotation) { result.appendCodePoint(0xFFFB); } while (dirCount > 0) { result.appendCodePoint(0x202C); dirCount--; } return result.toString(); } /** * Makes the passed text valid in means of <code>isTextValid()</code> * @see isTextValid */ public static final String makeTextValid(String text) { return text.replace("\r\n", "\n"); } public final synchronized void storeAndCommit() { synchronized(mDB.lock()) { try { storeWithoutCommit(); checkedCommit(this); } catch(RuntimeException e) { checkedRollbackAndThrow(e); } } } public void storeWithoutCommit() { try { checkedActivate(3); // 3 is the maximum depth of all getter functions. You have to adjust this when adding new members. for(Board board : mBoards) throwIfNotStored(board); throwIfNotStored(mAuthor); // The MessageLists of OwnMessages are created within the same transaction as the storeAndCommit so we cannot do throwIfNotStored for them. if(mMessageList != null && !(this instanceof OwnMessage)) throwIfNotStored(mMessageList); // You have to take care to keep the list of stored objects synchronized with those being deleted in deleteWithoutCommit() ! if(mURI != null) { mURI.initializeTransient(mFreetalk); mURI.storeWithoutCommit(); } if(mFreenetURI != null) { // It's a FreenetURI so it does not extend Persistent. checkedStore(mFreenetURI); } if(mThreadURI != null) { mThreadURI.initializeTransient(mFreetalk); mThreadURI.storeWithoutCommit(); } if(mParentURI != null) { mParentURI.initializeTransient(mFreetalk); mParentURI.storeWithoutCommit(); } // db.store(mBoards); /* Not stored because it is a primitive for db4o */ // db.store(mDate); /* Not stored because it is a primitive for db4o */ if(mAttachments != null) { for(Attachment a : mAttachments) { a.initializeTransient(mFreetalk); a.storeWithoutCommit(); } } // db.store(mAttachments); /* Not stored because it is a primitive for db4o */ checkedStore(); } catch(RuntimeException e) { checkedRollbackAndThrow(e); } } protected void deleteWithoutCommit() { try { checkedActivate(3); // TODO: Figure out a suitable depth. checkedDelete(this); if(mParentURI != null) { mParentURI.initializeTransient(mFreetalk); mParentURI.deleteWithoutCommit(); } if(mThreadURI != null) { mThreadURI.initializeTransient(mFreetalk); mThreadURI.deleteWithoutCommit(); } if(mFreenetURI != null) { // It's a FreenetURI so there is no transient initialization mFreenetURI.removeFrom(mDB); } if(mURI != null) { mURI.initializeTransient(mFreetalk); mURI.deleteWithoutCommit(); } if(mAttachments != null) { for(Attachment a : mAttachments) { a.initializeTransient(mFreetalk); a.deleteWithoutCommit(); } } } catch(RuntimeException e) { checkedRollbackAndThrow(e); } } @Override public boolean equals(Object obj) { if(obj instanceof Message) { Message otherMessage = (Message)obj; return mID.equals(otherMessage.getID()); // mID needs no activation } else return false; } public String toString() { if(mDB != null) return getURI().toString(); // We do not throw a NPE because toString() is usually used in logging, we want the logging to be robust Logger.error(this, "toString() called before initializeTransient()!"); return super.toString() + " (intializeTransient() not called!, message URI may be null, here it is: " + mURI + ")"; } }
false
true
public void databaseIntegrityTest() throws Exception { checkedActivate(3); if(mID == null) throw new NullPointerException("mID==null"); if(mAuthor == null) throw new NullPointerException("mAuthor==null"); MessageID.construct(mID).throwIfAuthorDoesNotMatch(mAuthor); if(!(this instanceof OwnMessage)) { if(mURI == null) throw new NullPointerException("mURI==null"); if(mFreenetURI == null) throw new NullPointerException("mFreenetURI==null"); if(mMessageList == null) throw new IllegalStateException("mMessageList==null"); } if(mURI != null) { final MessageURI messageURI = getURI(); // Call intializeTransient // The following check would be wrong (explanation below): // if(!messageURI.getFreenetURI().equals(mFreenetURI)) // throw new IllegalStateException("mURI and mFreenetURI mismatch: mURI==" + mURI + "; mFreenetURI==" + mFreenetURI); // It would be wrong because message URI contains the URI of the message list, not the URI of the message itself. messageURI.throwIfAuthorDoesNotMatch(mAuthor); if(!messageURI.getMessageID().equals(mID)) throw new IllegalStateException("mID == " + mID + " not matched for mURI == " + mURI); } if(mMessageList != null) { // If we are an OwnMessage and mMessageList is non-null then the URIs should also be non-null if(mURI == null) throw new NullPointerException("mURI == null"); if(mFreenetURI == null) throw new NullPointerException("mFreenetURI == null"); final MessageList messageList = getMessageList(); // Call initializeTransient if(!messageList.getURI().equals(getURI().getFreenetURI())) throw new IllegalStateException("getURI().getFreenetURI() == " + getURI().getFreenetURI() + " but mMessageList.getURI() == " + messageList.getURI()); if(messageList.getAuthor() != mAuthor) throw new IllegalStateException("mMessageList author does not match mAuthor: " + mMessageList); try { final MessageList.MessageReference ref = getMessageList().getReference(mFreenetURI); IfNotEquals.thenThrow(mID, ref.getMessageID(), "mID"); } catch(NoSuchMessageException e) { throw new IllegalStateException("mMessageList does not contain this message: " + mMessageList); } } if(mParentURI == null ^ mThreadURI == null) throw new IllegalStateException("mParentURI==" + mParentURI + " but mThreadURI==" + mThreadURI); if(mParentURI != null) { // Thread URI != null aswell final String parentID = getParentURI().getMessageID(); if(parentID.equals(mID)) throw new IllegalStateException("mParentURI points to the message itself"); if(!parentID.equals(mParentID)) throw new IllegalStateException("mParentURI==" + mParentURI + " but mParentID=="+parentID); final String threadID = getThreadURI().getMessageID(); if(threadID.equals(mID)) throw new IllegalStateException("mThreadURI points to the message itself"); if(!threadID.equals(mThreadID)) throw new IllegalStateException("mThreadURI==" + mThreadURI + " but mThreadID=="+threadID); } else { // Parent URI is null => Thread URI is null => No parent message / thread should be set. if(mParent != null) throw new IllegalStateException("mParent == " + mParent); if(mThread != null) throw new IllegalStateException("mThread == " + mThread); } { if(mBoards == null) throw new NullPointerException("mBoards==null"); if(mBoards.length < 1) throw new IllegalStateException("mBoards is empty"); if(mBoards.length > MAX_BOARDS_PER_MESSAGE) throw new IllegalStateException("mBoards contains too many boards: " + mBoards.length); if(mReplyToBoard == null) throw new NullPointerException("mReplToBoard==null"); boolean replyToBoardWasFound = false; for(Board board : mBoards) { if(board == null) throw new NullPointerException("mBoards contains null entry"); if(board == mReplyToBoard) replyToBoardWasFound = true; if(board instanceof SubscribedBoard) throw new IllegalStateException("mBoard contains a SubscribedBoard: " + board); } if(!replyToBoardWasFound) throw new IllegalStateException("mBoards does not contain mReplyToBoard"); } if(!isTitleValid(mTitle)) // Checks for null aswell throw new IllegalStateException("Title is not valid: " + mTitle); if(!isTextValid(mText)) // Checks for null aswell throw new IllegalStateException("Text is not valid"); if(mDate == null) throw new NullPointerException("mDate==null"); if(mDate.after(getFetchDate())) throw new IllegalStateException("mDate==" + mDate + " after mFetchDate==" + getFetchDate()); if(mAttachments != null && mAttachments.length > MAX_ATTACHMENTS_PER_MESSAGE) throw new IllegalStateException("mAttachments contains too many attachments: " + mAttachments.length); // Attachments inherit class Persistent and therefore have their own integrity test if(mThread != null && !mThreadID.equals(mThread.getID())) throw new IllegalStateException("mThread does not match thread ID: " + mThread); if(mParent != null && !mParentID.endsWith(mParent.getID())) throw new IllegalStateException("mParent does not match parent ID: " + mParent); if(mWasLinkedIn) { for(Board board : mBoards) { try { board.initializeTransient(mFreetalk); board.getMessageLink(this); } catch(NoSuchMessageException e) { throw new IllegalStateException("mWasLinkedIn==true but not found in board " + board); } } } }
public void databaseIntegrityTest() throws Exception { checkedActivate(3); if(mID == null) throw new NullPointerException("mID==null"); if(mAuthor == null) throw new NullPointerException("mAuthor==null"); MessageID.construct(mID).throwIfAuthorDoesNotMatch(mAuthor); if(!(this instanceof OwnMessage)) { if(mURI == null) throw new NullPointerException("mURI==null"); if(mFreenetURI == null) throw new NullPointerException("mFreenetURI==null"); if(mMessageList == null) throw new IllegalStateException("mMessageList==null"); } if(mURI != null) { final MessageURI messageURI = getURI(); // Call intializeTransient // The following check would be wrong (explanation below): // if(!messageURI.getFreenetURI().equals(mFreenetURI)) // throw new IllegalStateException("mURI and mFreenetURI mismatch: mURI==" + mURI + "; mFreenetURI==" + mFreenetURI); // It would be wrong because message URI contains the URI of the message list, not the URI of the message itself. messageURI.throwIfAuthorDoesNotMatch(mAuthor); if(!messageURI.getMessageID().equals(mID)) throw new IllegalStateException("mID == " + mID + " not matched for mURI == " + mURI); } if(mMessageList != null) { // If we are an OwnMessage and mMessageList is non-null then the URIs should also be non-null if(mURI == null) throw new NullPointerException("mURI == null"); if(mFreenetURI == null) throw new NullPointerException("mFreenetURI == null"); final MessageList messageList = getMessageList(); // Call initializeTransient if(!messageList.getURI().equals(getURI().getFreenetURI())) throw new IllegalStateException("getURI().getFreenetURI() == " + getURI().getFreenetURI() + " but mMessageList.getURI() == " + messageList.getURI()); if(messageList.getAuthor() != mAuthor) throw new IllegalStateException("mMessageList author does not match mAuthor: " + mMessageList); try { final MessageList.MessageReference ref = getMessageList().getReference(mFreenetURI); IfNotEquals.thenThrow(mID, ref.getMessageID(), "mID"); } catch(NoSuchMessageException e) { throw new IllegalStateException("mMessageList does not contain this message: " + mMessageList); } } if(mParentURI == null ^ mThreadURI == null) throw new IllegalStateException("mParentURI==" + mParentURI + " but mThreadURI==" + mThreadURI); if(mParentURI != null) { // Thread URI != null aswell final String parentID = getParentURI().getMessageID(); if(parentID.equals(mID)) throw new IllegalStateException("mParentURI points to the message itself"); if(!parentID.equals(mParentID)) throw new IllegalStateException("mParentURI==" + mParentURI + " but mParentID=="+parentID); final String threadID = getThreadURI().getMessageID(); if(threadID.equals(mID)) throw new IllegalStateException("mThreadURI points to the message itself"); if(!threadID.equals(mThreadID)) throw new IllegalStateException("mThreadURI==" + mThreadURI + " but mThreadID=="+threadID); } else { // Parent URI is null => Thread URI is null => No parent message / thread should be set. if(mParent != null) throw new IllegalStateException("mParent == " + mParent); if(mThread != null) throw new IllegalStateException("mThread == " + mThread); } { if(mBoards == null) throw new NullPointerException("mBoards==null"); if(mBoards.length < 1) throw new IllegalStateException("mBoards is empty"); if(mBoards.length > MAX_BOARDS_PER_MESSAGE) throw new IllegalStateException("mBoards contains too many boards: " + mBoards.length); // mReplyToBoard may be null if replies are desired to all boards boolean replyToBoardWasFound = mReplyToBoard == null ? true : false; for(Board board : mBoards) { if(board == null) throw new NullPointerException("mBoards contains null entry"); if(board == mReplyToBoard) replyToBoardWasFound = true; if(board instanceof SubscribedBoard) throw new IllegalStateException("mBoard contains a SubscribedBoard: " + board); } if(!replyToBoardWasFound) throw new IllegalStateException("mBoards does not contain mReplyToBoard"); } if(!isTitleValid(mTitle)) // Checks for null aswell throw new IllegalStateException("Title is not valid: " + mTitle); if(!isTextValid(mText)) // Checks for null aswell throw new IllegalStateException("Text is not valid"); if(mDate == null) throw new NullPointerException("mDate==null"); if(mDate.after(getFetchDate())) throw new IllegalStateException("mDate==" + mDate + " after mFetchDate==" + getFetchDate()); if(mAttachments != null && mAttachments.length > MAX_ATTACHMENTS_PER_MESSAGE) throw new IllegalStateException("mAttachments contains too many attachments: " + mAttachments.length); // Attachments inherit class Persistent and therefore have their own integrity test if(mThread != null && !mThreadID.equals(mThread.getID())) throw new IllegalStateException("mThread does not match thread ID: " + mThread); if(mParent != null && !mParentID.endsWith(mParent.getID())) throw new IllegalStateException("mParent does not match parent ID: " + mParent); if(mWasLinkedIn) { for(Board board : mBoards) { try { board.initializeTransient(mFreetalk); board.getMessageLink(this); } catch(NoSuchMessageException e) { throw new IllegalStateException("mWasLinkedIn==true but not found in board " + board); } } } }
diff --git a/lib/mx-native-loader-1.2/src/main/java/com/wapmx/nativeutils/jniloader/DefaultJniExtractor.java b/lib/mx-native-loader-1.2/src/main/java/com/wapmx/nativeutils/jniloader/DefaultJniExtractor.java index 031b115b..80655e7b 100644 --- a/lib/mx-native-loader-1.2/src/main/java/com/wapmx/nativeutils/jniloader/DefaultJniExtractor.java +++ b/lib/mx-native-loader-1.2/src/main/java/com/wapmx/nativeutils/jniloader/DefaultJniExtractor.java @@ -1,150 +1,150 @@ // $Id: DefaultJniExtractor.java 135270 2008-01-16 16:00:27Z richardv $ package com.wapmx.nativeutils.jniloader; /* * Copyright 2006 MX Telecom Ltd. */ import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Map; import java.util.HashMap; /** * @author Richard van der Hoff <[email protected]> */ public class DefaultJniExtractor implements JniExtractor { private static boolean debug = false; /** * this is where JNI libraries are extracted to. */ private File jniDir = null; private static Map _cache; static { // initialise the debug switch String s = System.getProperty("java.library.debug"); if(s != null && (s.toLowerCase().startsWith("y") || s.startsWith("1"))) debug = true; _cache = new HashMap(); if(debug) System.err.println("cache " + _cache); } /** * Gets the working directory to use for jni extraction. * <p> * Attempts to create it if it doesn't exist. * * @return jni working dir * @throws IOException if there's a problem creating the dir */ public File getJniDir() throws IOException { String[] libPaths = { "Sikuli-IDE.app/Contents/Frameworks", "libs", "/Applications/Sikuli-IDE.app/Contents/Frameworks", - System.getenv("SIKULI_HOME") + File.separator + "libs" + System.getenv("SIKULI_HOME") + "libs" }; if(jniDir == null) { for(int i=0;i<libPaths.length;i++){ String path = libPaths[i]; jniDir = new File(path); if( jniDir.exists() ){ System.setProperty("java.library.tmpdir", path); return jniDir; } } String tmpdir = System.getProperty("java.io.tmpdir") + "/tmplib"; jniDir = new File( System.getProperty("java.library.tmpdir",tmpdir)); if(debug) System.err.println("Initialised JNI library working directory to '"+jniDir+"'"); } if ( !jniDir.exists() ) { if( !jniDir.mkdirs()) throw new IOException("Unable to create JNI library working directory "+jniDir); } return jniDir; } /** * extract a JNI library from the classpath * * @param libname - System.loadLibrary() - compatible library name * @return the extracted file * @throws IOException */ public File extractJni(String libname) throws IOException { String mappedlib = System.mapLibraryName(libname); /* on darwin, the default mapping is to .jnilib; but * we use .dylibs so that library interdependencies are handled correctly. * if we don't find a .jnilib, try .dylib instead. */ if(mappedlib.endsWith(".jnilib")) { if(this.getClass().getClassLoader().getResource("META-INF/lib/"+mappedlib) == null) mappedlib = mappedlib.substring(0, mappedlib.length()-7)+".dylib"; } if(_cache.containsKey(mappedlib)){ if(debug) System.err.println("in cache " + mappedlib); return (File)_cache.get(mappedlib); } else{ if(debug) System.err.println("not in cache " + mappedlib); File ret = extractResource("META-INF/lib/"+mappedlib,mappedlib); _cache.put(mappedlib, ret); return ret; } } /** * extract a resource to the tmp dir (this entry point is used for unit testing) * * @param resourcename the name of the resource on the classpath * @param outputname the filename to copy to (within the tmp dir) * @return the extracted file * @throws IOException */ File extractResource(String resourcename,String outputname) throws IOException { InputStream in = this.getClass().getClassLoader().getResourceAsStream(resourcename); if(in == null) throw new IOException("Unable to find library "+resourcename+" on classpath"); File outfile = new File(getJniDir(),outputname); if(debug) System.err.println("Extracting '"+resourcename+"' to '"+outfile.getAbsolutePath()+"'"); //FIXME: check the file utime and determine if it needs overwritten if( !outfile.exists() || outfile.getParent().endsWith("tmplib") ){ OutputStream out = new FileOutputStream(outfile); copy(in,out); out.close(); } in.close(); return outfile; } /** * copy an InputStream to an OutputStream. * * @param in InputStream to copy from * @param out OutputStream to copy to * @throws IOException if there's an error */ static void copy(InputStream in, OutputStream out) throws IOException { byte[] tmp = new byte[8192]; int len = 0; while (true) { len = in.read(tmp); if (len <= 0) { break; } out.write(tmp, 0, len); } } }
true
true
public File getJniDir() throws IOException { String[] libPaths = { "Sikuli-IDE.app/Contents/Frameworks", "libs", "/Applications/Sikuli-IDE.app/Contents/Frameworks", System.getenv("SIKULI_HOME") + File.separator + "libs" }; if(jniDir == null) { for(int i=0;i<libPaths.length;i++){ String path = libPaths[i]; jniDir = new File(path); if( jniDir.exists() ){ System.setProperty("java.library.tmpdir", path); return jniDir; } } String tmpdir = System.getProperty("java.io.tmpdir") + "/tmplib"; jniDir = new File( System.getProperty("java.library.tmpdir",tmpdir)); if(debug) System.err.println("Initialised JNI library working directory to '"+jniDir+"'"); } if ( !jniDir.exists() ) { if( !jniDir.mkdirs()) throw new IOException("Unable to create JNI library working directory "+jniDir); } return jniDir; }
public File getJniDir() throws IOException { String[] libPaths = { "Sikuli-IDE.app/Contents/Frameworks", "libs", "/Applications/Sikuli-IDE.app/Contents/Frameworks", System.getenv("SIKULI_HOME") + "libs" }; if(jniDir == null) { for(int i=0;i<libPaths.length;i++){ String path = libPaths[i]; jniDir = new File(path); if( jniDir.exists() ){ System.setProperty("java.library.tmpdir", path); return jniDir; } } String tmpdir = System.getProperty("java.io.tmpdir") + "/tmplib"; jniDir = new File( System.getProperty("java.library.tmpdir",tmpdir)); if(debug) System.err.println("Initialised JNI library working directory to '"+jniDir+"'"); } if ( !jniDir.exists() ) { if( !jniDir.mkdirs()) throw new IOException("Unable to create JNI library working directory "+jniDir); } return jniDir; }
diff --git a/GpsMidGraph/de/ueller/midlet/gps/data/Way.java b/GpsMidGraph/de/ueller/midlet/gps/data/Way.java index 7f0f2971..a3d86783 100644 --- a/GpsMidGraph/de/ueller/midlet/gps/data/Way.java +++ b/GpsMidGraph/de/ueller/midlet/gps/data/Way.java @@ -1,1659 +1,1659 @@ package de.ueller.midlet.gps.data; /* * GpsMid - Copyright (c) 2007 Harald Mueller james22 at users dot sourceforge dot net * Copyright (c) 2008 sk750 at users dot sourceforge dot net * See Copying */ import java.io.DataInputStream; import java.io.IOException; import java.util.Vector; import javax.microedition.lcdui.Font; import javax.microedition.lcdui.Graphics; import net.sourceforge.jmicropolygon.PolygonGraphics; import de.enough.polish.util.DrawUtil; import de.ueller.gps.data.Configuration; import de.ueller.gpsMid.mapData.SingleTile; import de.ueller.gpsMid.mapData.Tile; import de.ueller.midlet.gps.GpsMid; import de.ueller.midlet.gps.Logger; import de.ueller.midlet.gps.RouteInstructions; import de.ueller.midlet.gps.routing.ConnectionWithNode; import de.ueller.midlet.gps.Trace; import de.ueller.midlet.gps.tile.C; import de.ueller.midlet.gps.tile.PaintContext; import de.ueller.midlet.gps.tile.WayDescription; // TODO: explain /* Questions: * - What classes are involved for getting the necessary Way data from the Jar? * - Which region is covered by a SingleTile, does it always contain all Nodes of the complete way? * - Where are the way nodes combined if a tile was split in Osm2GpsMid? */ public class Way extends Entity{ public static final byte WAY_FLAG_NAME = 1; public static final byte WAY_FLAG_MAXSPEED = 2; public static final byte WAY_FLAG_LAYER = 4; public static final byte WAY_FLAG_LONGWAY = 8; public static final byte WAY_FLAG_ONEWAY = 16; // public static final byte WAY_FLAG_MULTIPATH = 4; public static final byte WAY_FLAG_NAMEHIGH = 32; public static final byte WAY_FLAG_AREA = 64; // public static final byte WAY_FLAG_ISINHIGH = 64; public static final int WAY_FLAG_ADDITIONALFLAG = 128; public static final byte WAY_FLAG2_ROUNDABOUT = 1; public static final byte WAY_FLAG2_TUNNEL = 2; public static final byte WAY_FLAG2_BRIDGE = 4; public static final byte DRAW_BORDER=1; public static final byte DRAW_AREA=2; public static final byte DRAW_FULL=3; private static final int MaxSpeedMask = 0xff; private static final int MaxSpeedShift = 0; private static final int ModMask = 0xff00; private static final int ModShift = 8; public static final int WAY_ONEWAY=1 << ModShift; public static final int WAY_AREA=2 << ModShift; public static final int WAY_ROUNDABOUT=4 << ModShift; public static final int WAY_TUNNEL=8 << ModShift; public static final int WAY_BRIDGE=16 << ModShift; public static final byte PAINTMODE_COUNTFITTINGCHARS = 0; public static final byte PAINTMODE_DRAWCHARS = 1; public static final byte INDENT_PATHNAME = 2; private static final int PATHSEG_DO_NOT_HIGHLIGHT = -1; private static final int PATHSEG_DO_NOT_DRAW = -2; private static final int HIGHLIGHT_NONE = 0; private static final int HIGHLIGHT_TARGET = 1; private static final int HIGHLIGHT_ROUTEPATH_CONTAINED = 2; protected static final Logger logger = Logger.getInstance(Way.class,Logger.TRACE); private int flags=0; public short[] path; public short minLat; public short minLon; public short maxLat; public short maxLon; /** * This is a buffer for the drawing routines * so that we don't have to allocate new * memory at each time we draw a way. This * saves some time on memory managment * too. * * This makes this function thread unsafe, * so make sure we only have a single thread * drawing a way at a time */ private static int [] x = new int[100]; private static int [] y = new int[100]; /** * contains either PATHSEG_DO_NOT_HIGHLIGHT, PATHSEG_DO_NOT_DRAW * or if this way's segment is part of the route path, * the index of the corresponding ConnectionWithNode in the route */ private static int [] hl = new int[100]; private static Font areaFont; private static int areaFontHeight; private static Font pathFont; private static int pathFontHeight; private static int pathFontMaxCharWidth; private static int pathFontBaseLinePos; static final IntPoint l1b = new IntPoint(); static final IntPoint l1e = new IntPoint(); static final IntPoint l2b = new IntPoint(); static final IntPoint l2e = new IntPoint(); static final IntPoint l3b = new IntPoint(); static final IntPoint l3e = new IntPoint(); static final IntPoint l4b = new IntPoint(); static final IntPoint l4e = new IntPoint(); static final IntPoint s1 = new IntPoint(); static final IntPoint s2 = new IntPoint(); /** * Enables or disables the match travelling direction for actual way calculation heuristic */ private static boolean addDirectionalPenalty = false; /** * Sets the scale of the directional penalty dependent on the projection used. */ private static float scalePen = 0; /* * Precalculated normalised vector for the direction of current travel, * used in the the directional penalty heuristic */ private static float courseVecX = 0; private static float courseVecY = 0; // private final static Logger logger = Logger.getInstance(Way.class, // Logger.TRACE); /** * the flag should be readed by caller. if Flag == 128 this is a dummy Way * and can ignored. * * @param is Tile inputstream * @param f flags * @param t Tile * @param layers: this is somewhat awkward. We need to get the layer information back out to * the caller, so use a kind of call by reference * @paran idx index into the layers array where to store the layer info. * @param nodes * @throws IOException */ public Way(DataInputStream is, byte f, Tile t, byte[] layers, int idx) throws IOException { minLat = is.readShort(); minLon = is.readShort(); maxLat = is.readShort(); maxLon = is.readShort(); // if (is.readByte() != 0x58){ // logger.error("worng magic after way bounds"); // } //System.out.println("Way flags: " + f); type = is.readByte(); if ((f & WAY_FLAG_NAME) == WAY_FLAG_NAME) { if ((f & WAY_FLAG_NAMEHIGH) == WAY_FLAG_NAMEHIGH) { nameIdx = is.readInt(); //System.out.println("Name_High " + f ); } else { nameIdx = is.readShort(); } } if ((f & WAY_FLAG_MAXSPEED) == WAY_FLAG_MAXSPEED) { // logger.debug("read maxspeed"); flags = is.readByte(); } byte f2=0; if ( (f & WAY_FLAG_ADDITIONALFLAG) > 0 ) { f2 = is.readByte(); if ( (f2 & WAY_FLAG2_ROUNDABOUT) > 0 ) { flags += WAY_ROUNDABOUT; } if ( (f2 & WAY_FLAG2_TUNNEL) > 0 ) { flags += WAY_TUNNEL; } if ( (f2 & WAY_FLAG2_BRIDGE) > 0 ) { flags += WAY_BRIDGE; } } layers[idx] = 0; if ((f & WAY_FLAG_LAYER) == WAY_FLAG_LAYER) { /** * TODO: We are currently ignoring the layer info * Please implement proper support for this when rendering */ layers[idx] = is.readByte(); } if ((f & WAY_FLAG_ONEWAY) == WAY_FLAG_ONEWAY) { flags += WAY_ONEWAY; } if (((f & WAY_FLAG_AREA) == WAY_FLAG_AREA) || C.getWayDescription(type).isArea) { if ((f & WAY_FLAG_AREA) == WAY_FLAG_AREA){ //#debug debug logger.debug("Loading explicit Area: " + this); } flags += WAY_AREA; } boolean longWays=false; if ((f & 8) == 8) { longWays=true; } int count; if (longWays){ count = is.readShort(); if (count < 0) { count+=65536; } } else { count = is.readByte(); if (count < 0) { count+=256; } } path = new short[count]; for (short i = 0; i < count; i++) { path[i] = is.readShort(); // logger.debug("read node id=" + path[i]); } // if (is.readByte() != 0x59 ){ // logger.error("wrong magic code after path"); // } } /** * Precalculate parameters to quickly test the the directional overlap between * a way and the current direction of travelling. This is used in processWay * to calculate the most likely way we are currently travelling on. * * @param pc * @param speed */ public static void setupDirectionalPenalty(PaintContext pc, int speed, boolean gpsRecenter) { //Only use this heuristic if we are travelling faster than 6 km/h, as otherwise //the direction estimate is too bad to be of much use. Also, only use the direction //if we are actually using the gps to center the map and not manually panning around. if ((speed < 7) || !gpsRecenter) { addDirectionalPenalty = false; scalePen = 0; return; } addDirectionalPenalty = true; Projection p = pc.getP(); float lat1 = pc.center.radlat; float lon1 = pc.center.radlon; IntPoint lineP1 = new IntPoint(); IntPoint lineP2 = new IntPoint(); float lat2 = pc.center.radlat + (float) (0.00001*Math.cos(pc.course * MoreMath.FAC_DECTORAD)); float lon2 = pc.center.radlon + (float) (0.00001*Math.sin(pc.course * MoreMath.FAC_DECTORAD)); p.forward(lat1, lon1, lineP1); p.forward(lat2, lon2, lineP2); courseVecX = lineP1.x - lineP2.x; courseVecY = lineP1.y - lineP2.y; float norm = (float)Math.sqrt(courseVecX*courseVecX + courseVecY*courseVecY); courseVecX /= norm; courseVecY /= norm; //Calculate the lat and lon coordinates of two //points that are 35 pixels apart Node n1 = new Node(); Node n2 = new Node(); pc.getP().inverse(10, 10, n1); pc.getP().inverse(45, 10, n2); //Calculate the distance between them in meters float d = ProjMath.getDistance(n1, n2); //Set the scale of the direction penalty to roughly //match that of a penalty of 100m at a 90 degree angle scalePen = 35.0f/d*100.0f; } public boolean isOnScreen( short pcLDlat, short pcLDlon, short pcRUlat, short pcRUlon) { if ((maxLat < pcLDlat) || (minLat > pcRUlat)) { return false; } if ((maxLon < pcLDlon) || (minLon > pcRUlon)) { return false; } return true; } public float wayBearing(SingleTile t) { return (float) MoreMath.bearing_int(t.nodeLat[path[0]]*SingleTile.fpminv + t.centerLat, t.nodeLon[path[0]]*SingleTile.fpminv + t.centerLon, t.nodeLat[path[path.length - 1]]*SingleTile.fpminv + t.centerLat, t.nodeLon[path[path.length - 1]]*SingleTile.fpminv + t.centerLon); } public void paintAsPath(PaintContext pc, SingleTile t, byte layer) { processPath(pc,t,Tile.OPT_PAINT, layer); } public void paintHighlightPath(PaintContext pc, SingleTile t, byte layer) { processPath(pc,t,Tile.OPT_PAINT | Tile.OPT_HIGHLIGHT, layer); } private void changeCountNameIdx(PaintContext pc, int diff) { if (nameIdx >= 0) { Integer oCount = (Integer) pc.conWayNameIdxs.get(nameIdx); int nCount = 0; if (oCount != null) { nCount = oCount.intValue(); } pc.conWayNameIdxs.put(nameIdx, new Integer(nCount + diff) ); } } /* check if the way contains the nodes searchCon1 and searchCon2 * if it does, but we already have a matching way, * only take this way if it has the shortest path from searchCon1 to searchCon2 **/ public void connections2WayMatch(PaintContext pc, SingleTile t) { boolean containsCon1 = false; boolean containsCon2 = false; short containsCon1At = 0; short containsCon2At = 0; short searchCon1Lat = (short) ((pc.searchCon1Lat - t.centerLat) * t.fpm); short searchCon1Lon = (short) ((pc.searchCon1Lon - t.centerLon) * t.fpm); short searchCon2Lat = (short) ((pc.searchCon2Lat - t.centerLat) * t.fpm); short searchCon2Lon = (short) ((pc.searchCon2Lon - t.centerLon) * t.fpm); boolean isCircleway = isCircleway(t); // check if way contains both search connections // System.out.println("search path nodes: " + path.length); for (short i = 0; i < path.length; i++) { int idx = path[i]; // System.out.println("lat:" + t.nodeLat[idx] + "/" + searchCon1Lat); if ( (Math.abs(t.nodeLat[idx] - searchCon1Lat) < 2) && (Math.abs(t.nodeLon[idx] - searchCon1Lon) < 2) ) { if ( C.getWayDescription(this.type).routable // count in roundabouts only once (search connection could match at start and end node) && !containsCon1 // count only if it's not a oneway ending at this connection && !(isOneway() && (i == path.length - 1 && !isCircleway) ) ) { // remember bearings of the ways at this connection, so we can later check out if we have multiple straight-ons requiring a bearing instruction // we do this twice for each found way to add the bearings for forward and backward for (int d = -1 ; d <= 1; d += 2) { // do not add bearings against direction if this is a oneway if (d == -1 && isOneway()) { continue; } if ( (i + d) < path.length && (i + d) >= 0) { short rfCurr = (short) C.getWayDescription(this.type).routeFlags; // count bearings for entering / leaving the motorway. We don't need to give bearing instructions if there's only one motorway alternative at the connection if (RouteInstructions.isEnterMotorway(pc.searchConPrevWayRouteFlags, rfCurr) || RouteInstructions.isLeaveMotorway(pc.searchConPrevWayRouteFlags, rfCurr) ) { pc.conWayNumMotorways++; } int idxC = path[i + d]; byte bearing = MoreMath.bearing_start( (pc.searchCon1Lat), (pc.searchCon1Lon), (t.centerLat + t.nodeLat[idxC] * t.fpminv), (t.centerLon + t.nodeLon[idxC] * t.fpminv) ); pc.conWayBearings.addElement(new Byte(bearing) ); } } // remember nameIdx's leading away from the connection, so we can later on check if multiple ways lead to the same street name changeCountNameIdx(pc, 1); //System.out.println("add 1 " + "con1At: " + i + " pathlen-1: " + (path.length-1) ); pc.conWayNumToRoutableWays++; // if we are in the middle of the way, count the way once more if (i != 0 && i != path.length-1 && !isOneway()) { pc.conWayNumToRoutableWays++; changeCountNameIdx(pc, 1); //System.out.println("add middle 1 " + "con1At: " + i + " pathlen-1: " + (path.length-1) ); } } containsCon1 = true; containsCon1At = i; // System.out.println("con1 match"); if (containsCon1 && containsCon2) break; } if ( (Math.abs(t.nodeLat[idx] - searchCon2Lat) < 2) && (Math.abs(t.nodeLon[idx] - searchCon2Lon) < 2) ) { containsCon2 = true; containsCon2At = i; // System.out.println("con2 match"); if (containsCon1 && containsCon2) break; } } // we've got a match if (containsCon1 && containsCon2) { float conWayRealDistance = 0; short from = containsCon1At; short to = containsCon2At; int direction = 1; if (from > to && !(isRoundAbout() || isCircleway) ) { // if this is a oneway but not a roundabout or circleway it can't be the route path as we would go against the oneway's direction if (isOneway()) return; // swap direction from = to; to = containsCon1At; direction = -1; } int idx1 = path[from]; int idx2; // sum up the distance of the segments between searchCon1 and searchCon2 for (short i = from; i != to; i++) { if ( (isRoundAbout() || isCircleway) && i >= (path.length-2)) { i=-1; // if in roundabout at end of path continue at first node if (to == (path.length-1) ) { break; } } idx2 = path[i+1]; float dist = ProjMath.getDistance( (t.centerLat + t.nodeLat[idx1] * t.fpminv), (t.centerLon + t.nodeLon[idx1] * t.fpminv), (t.centerLat + t.nodeLat[idx2] * t.fpminv), (t.centerLon + t.nodeLon[idx2] * t.fpminv)); conWayRealDistance += dist; idx1 = idx2; } /* check if this is a better match than a maybe previous one: if the distance is closer than the already matching one this way contains a better path between the connections */ if (conWayRealDistance < pc.conWayDistanceToNext && /* check if wayDescription has the routable flag set * (there are situations where 2 ways have the same nodes, e.g. a tram and a highway) */ C.getWayDescription(this.type).routable ) { // if (pc.conWayDistanceToNext != Float.MAX_VALUE) { // String name1=null, name2=null; // if (pc.conWayNameIdx != -1) name1=Trace.getInstance().getName(pc.conWayNameIdx); // if (this.nameIdx != -1) name2=Trace.getInstance().getName(this.nameIdx); // System.out.println("REPLACE " + pc.conWayDistanceToNext + "m (" + C.getWayDescription(pc.conWayType).description + " " + (name1==null?"":name1) + ")"); // System.out.println("WITH " + conWayRealDistance + "m (" + C.getWayDescription(this.type).description + " " + (name2==null?"":name2) + ")"); // } // this is currently the best path between searchCon1 and searchCon2 pc.conWayDistanceToNext = conWayRealDistance; pc.conWayFromAt = containsCon1At; pc.conWayToAt = containsCon2At; pc.conWayNameIdx= this.nameIdx; pc.conWayType = this.type; short routeFlags = (short) C.getWayDescription(this.type).routeFlags; if (isRoundAbout()) routeFlags += C.ROUTE_FLAG_ROUNDABOUT; if (isTunnel()) routeFlags += C.ROUTE_FLAG_TUNNEL; if (isBridge()) routeFlags += C.ROUTE_FLAG_BRIDGE; if (isOneway()) routeFlags += C.ROUTE_FLAG_COMING_FROM_ONEWAY; pc.conWayRouteFlags = routeFlags; // substract way we are coming from from turn options with same name changeCountNameIdx(pc, -1); //System.out.println("sub 1"); // calculate bearings if ( (direction==1 && containsCon1At < (path.length - 1)) || (direction==-1 && containsCon1At > 0) ) { int idxC = path[containsCon1At + direction]; pc.conWayStartBearing = MoreMath.bearing_start( (pc.searchCon1Lat), (pc.searchCon1Lon), (t.centerLat + t.nodeLat[idxC] * t.fpminv), (t.centerLon + t.nodeLon[idxC] * t.fpminv) ); } if ( (direction==1 && containsCon2At > 0) || (direction==-1 && containsCon2At < (path.length - 1)) ) { int idxC = path[containsCon2At - direction]; pc.conWayEndBearing = MoreMath.bearing_start( (t.centerLat + t.nodeLat[idxC] * t.fpminv), (t.centerLon + t.nodeLon[idxC] * t.fpminv), (pc.searchCon2Lat), (pc.searchCon2Lon) ); } } } } public void processPath(PaintContext pc, SingleTile t, int mode, byte layer) { WayDescription wayDesc = C.getWayDescription(type); /** width of the way to be painted */ int w = 0; byte highlight=HIGHLIGHT_NONE; /** * If the static array is not large enough, increase it */ if (x.length < path.length) { x = new int[path.length]; y = new int[path.length]; hl = new int[path.length]; } // initialize with default draw states for the path's segments int hlDefault = PATHSEG_DO_NOT_HIGHLIGHT; if ( (mode & Tile.OPT_HIGHLIGHT) != 0) { hlDefault = PATHSEG_DO_NOT_DRAW; } for (int i1 = 0; i1 < path.length; i1++) { hl[i1] = hlDefault; } if ((mode & Tile.OPT_PAINT) > 0) { byte om = C.getWayOverviewMode(type); switch (om & C.OM_MODE_MASK) { case C.OM_SHOWNORMAL: // if not in Overview Mode check for scale if (pc.scale > wayDesc.maxScale * Configuration.getDetailBoostMultiplier()) { return; } break; case C.OM_HIDE: if (wayDesc.hideable) { return; } break; } switch (om & C.OM_NAME_MASK) { case C.OM_WITH_NAMEPART: if (nameIdx == -1) return; String name = pc.trace.getName(nameIdx); if (name == null) return; /** * The overview filter mode allows you to restrict showing ways if their name * does not match a substring. So check if this condition is fulfilled. */ if (name.toUpperCase().indexOf(C.get0Poi1Area2WayNamePart((byte) 2).toUpperCase()) == -1) return; break; case C.OM_WITH_NAME: if (nameIdx == -1) return; break; case C.OM_NO_NAME: if (nameIdx != -1) return; break; } /** * check if way matches to one or more route connections, * so we can highlight the route line parts */ Vector route=pc.trace.getRoute(); ConnectionWithNode c; if (route!=null && route.size()!=0) { for (int i=0; i<route.size()-1; i++){ c = (ConnectionWithNode) route.elementAt(i); if (c.wayNameIdx == this.nameIdx && wayDesc.routable) { if (path.length > c.wayFromConAt && path.length > c.wayToConAt) { int idx = path[c.wayFromConAt]; short searchCon1Lat = (short) ((c.to.lat - t.centerLat) * t.fpm); if ( (Math.abs(t.nodeLat[idx] - searchCon1Lat) < 2) ) { short searchCon1Lon = (short) ((c.to.lon - t.centerLon) * t.fpm); if ( (Math.abs(t.nodeLon[idx] - searchCon1Lon) < 2) ) { idx = path[c.wayToConAt]; ConnectionWithNode c2 = (ConnectionWithNode) route.elementAt(i+1); searchCon1Lat = (short) ((c2.to.lat - t.centerLat) * t.fpm); if ( (Math.abs(t.nodeLat[idx] - searchCon1Lat) < 2) ) { searchCon1Lon = (short) ((c2.to.lon - t.centerLon) * t.fpm); if ( (Math.abs(t.nodeLon[idx] - searchCon1Lon) < 2) ) { // if we are not in highlight mode, flag that this layer contains a path segment to highlight if ((mode & Tile.OPT_HIGHLIGHT) == 0) { pc.hlLayers |= (1<<layer); } // set way highlight flag so we can quickly determine if this way contains a route line part highlight = HIGHLIGHT_ROUTEPATH_CONTAINED; /* * flag the parts of the way as to be highlighted * by putting in the index of the corresponding connection */ short from = c.wayFromConAt; short to = c.wayToConAt; boolean isCircleway = isCircleway(t); if (from > to && !(isRoundAbout() || isCircleway) ) { // swap direction to = from; from = c.wayToConAt; } for (int n = from; n != to; n++) { hl[n] = i; if ( ( isRoundAbout() || isCircleway ) && n >= (path.length-1) ) { n=-1; // // if in roundabout at end of path continue at first node if (to == (path.length-1) ) { break; } } } } } } } } } } } } /** * If this way is not to be highlighted but we are in highlight mode, * skip the rest of the processing of this way */ if (highlight == HIGHLIGHT_NONE && (mode & Tile.OPT_HIGHLIGHT) != 0) { return; } /** * We go through the way segment by segment * (a segment is a line between two consecutive points on the path). * lineP1 is first node of the segment, lineP2 is the second. */ IntPoint lineP1 = pc.lineP1; IntPoint lineP2 = pc.lineP2; IntPoint swapLineP = pc.swapLineP; Projection p = pc.getP(); int pi=0; for (int i1 = 0; i1 < path.length; i1++) { int idx = path[i1]; p.forward(t.nodeLat[idx], t.nodeLon[idx], lineP2,t); if (lineP1 == null) { /** * This is the first segment of the path, so we don't have a lineP1 yet */ lineP1 = lineP2; lineP2 = swapLineP; x[pi] = lineP1.x; y[pi++] = lineP1.y; } else { /** * We save some rendering time, by doing a line simplification on the fly. * If two nodes are very close by, then we can simply drop one of the nodes * and draw the line between the other points. If the way is highlighted, * we can't do any simplification, as we need to determine the index of the segment * that is closest to the center (= map center) of the PaintContext */ if (highlight == HIGHLIGHT_ROUTEPATH_CONTAINED || ! lineP1.approximatelyEquals(lineP2)){ /** * calculate closest distance to specific ways */ float dst = MoreMath.ptSegDistSq(lineP1.x, lineP1.y, lineP2.x, lineP2.y, pc.xSize / 2, pc.ySize / 2); if (dst < pc.squareDstToWay || dst < pc.squareDstToActualRoutableWay) { float pen = 0; /** * Add a heuristic so that the direction of travel and the direction * of the way should more or less match if we are travelling on this way */ if (addDirectionalPenalty) { int segDirVecX = lineP1.x-lineP2.x; int segDirVecY = lineP1.y-lineP2.y; float norm = (float) Math.sqrt((double)(segDirVecX*segDirVecX + segDirVecY*segDirVecY)); //This is a hack to use a linear approximation to keep computational requirements down pen = scalePen*(1.0f - Math.abs((segDirVecX*courseVecX + segDirVecY*courseVecY)/norm)); pen*=pen; } // if this way is closer including penalty than the old one set it as new actualWay if (dst + pen < pc.squareDstToWay) { pc.squareDstToWay = dst + pen; pc.actualWay = this; pc.actualSingleTile = t; } // if this routable way is closer including penalty than the old one set it as new actualRoutableWay - if (dst < pc.squareDstToActualRoutableWay + pen && wayDesc.routable) { + if (dst + pen < pc.squareDstToActualRoutableWay && wayDesc.routable) { pc.squareDstToActualRoutableWay = dst + pen; pc.actualRoutableWay = this; } } if (dst < pc.squareDstToRoutableWay && wayDesc.routable) { pc.squareDstToRoutableWay = dst; pc.nearestRoutableWay = this; } if ((hl[i1-1] > PATHSEG_DO_NOT_HIGHLIGHT) && (dst < pc.squareDstToRoutePath)) { pc.squareDstToRoutePath = dst; pc.routePathConnection = hl[i1-1]; pc.pathIdxInRoutePathConnection = pi; } x[pi] = lineP2.x; y[pi++] = lineP2.y; swapLineP = lineP1; lineP1 = lineP2; lineP2 = swapLineP; } else if ((i1+1) == path.length){ /** * This is an endpoint, so we can't simply drop it, as the lines would potentially look disconnected */ //System.out.println(" endpoint " + lineP2.x + "/" + lineP2.y+ " " +pc.trace.getName(nameIdx)); if (!lineP1.equals(lineP2)){ x[pi] = lineP2.x; y[pi++] = lineP2.y; } else { //System.out.println(" discarding never the less"); } } else { /** * Drop this point, it is redundant */ //System.out.println(" discard " + lineP2.x + "/" + lineP2.y+ " " +pc.trace.getName(nameIdx)); } } } swapLineP = lineP1; lineP1 = null; /** * TODO: Can we remove this call and do it the same way as with actualWay and introduce a * pc.nearestRoutableWaySingleTile and only calculate the entity and position mark when we need them? */ if ((pc.nearestRoutableWay == this) && ((pc.currentPos == null) || (pc.currentPos.entity != this))) { pc.currentPos = new PositionMark(pc.center.radlat, pc.center.radlon); pc.currentPos.setEntity(this, getNodesLatLon(t, true), getNodesLatLon(t, false)); } if ((mode & Tile.OPT_PAINT) > 0) { /** * Calculate the width of the path to be drawn. A width of 1 * corresponds to it being draw as a thin line rather than as a * street */ if (Configuration .getCfgBitState(Configuration.CFGBIT_STREETRENDERMODE) && wayDesc.wayWidth > 1) { w = (int) (pc.ppm * wayDesc.wayWidth / 2 + 0.5); } if (highlight != HIGHLIGHT_ROUTEPATH_CONTAINED && pc.target != null && this.equals(pc.target.entity)) { highlight = HIGHLIGHT_TARGET; } // if render as lines and no part of the way is highlighted if (w == 0 && highlight == HIGHLIGHT_NONE) { setColor(pc); PolygonGraphics.drawOpenPolygon(pc.g, x, y, pi - 1); // if render as streets or a part of the way is highlighted } else { draw(pc, t, (w == 0) ? 1 : w, x, y, hl, pi - 1, highlight); } if (isOneway()) { paintPathOnewayArrows(pc, t); } paintPathName(pc, t); } } public void paintPathName(PaintContext pc, SingleTile t) { //boolean info=false; // exit if not zoomed in enough WayDescription wayDesc = C.getWayDescription(type); if (pc.scale > wayDesc.maxTextScale * Configuration.getDetailBoostMultiplier() ) { return; } if ( !Configuration.getCfgBitState(Configuration.CFGBIT_WAYTEXTS)) { return; } //remember previous font Font originalFont = pc.g.getFont(); if (pathFont==null) { pathFont=Font.getFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_SMALL); pathFontHeight=pathFont.getHeight(); pathFontMaxCharWidth = pathFont.charWidth('W'); pathFontBaseLinePos = pathFont.getBaselinePosition(); } // At least the half font height must fit to the on-screen-width of the way // (is calculation of w correct???) int w = (int)(pc.ppm*wayDesc.wayWidth); if (pathFontHeight/4>w) { return; } String name=null; if ( Configuration.getCfgBitState(Configuration.CFGBIT_SHOWWAYPOITYPE)) { name=(this.isRoundAbout()?"rab ":"") + wayDesc.description; } else { if (nameIdx != -1) { name=Trace.getInstance().getName(nameIdx); } } if (name==null) { return; } // determine region in which chars can be drawn int minCharScreenX = pc.g.getClipX() - pathFontMaxCharWidth; int minCharScreenY = pc.g.getClipY() - pathFontBaseLinePos - (w/2); int maxCharScreenX = minCharScreenX + pc.g.getClipWidth() + pathFontMaxCharWidth; int maxCharScreenY = minCharScreenY + pc.g.getClipHeight() + pathFontBaseLinePos * 2; StringBuffer sbName= new StringBuffer(); pc.g.setFont(pathFont); pc.g.setColor(0,0,0); IntPoint posChar = new IntPoint(); char letter=' '; short charsDrawable=0; Projection p = pc.getP(); //if(info)System.out.println("Draw " + name + " from " + path.length + " points"); boolean reversed=false; boolean abbreviated=false; int iNameRepeatable=0; int iNameRepeated=0; // 2 passes: // - 1st pass only counts fitting chars, so we can correctly // abbreviate reversed strings // - 2nd pass actually draws for (byte mode=PAINTMODE_COUNTFITTINGCHARS;mode<=PAINTMODE_DRAWCHARS; mode++) { double posChar_x = 0; double posChar_y = 0; double slope_x=0; double slope_y=0; double nextDeltaSub=0; int delta=0; IntPoint lineP1 = pc.lineP1; IntPoint lineP2 = pc.lineP2; IntPoint swapLineP = pc.swapLineP; // do indent because first letter position would often // be covered by other connecting streets short streetNameCharIndex=-INDENT_PATHNAME; // draw name again and again until end of path for (int i1 = 0; i1 < path.length; i1++) { // get the next line point coordinates into lineP2 int idx = this.path[i1]; // forward() is in Mercator.java p.forward(t.nodeLat[idx], t.nodeLon[idx], lineP2, t); // if we got only one line point, get a second one if (lineP1 == null) { lineP1 = lineP2; lineP2 = swapLineP; continue; } // calculate the slope of the new line double distance = Math.sqrt( ((double)lineP2.y-(double)lineP1.y)*((double)lineP2.y-(double)lineP1.y) + ((double)lineP2.x-(double)lineP1.x)*((double)lineP2.x-(double)lineP1.x) ); if (distance!=0) { slope_x = ((double)lineP2.x-(double)lineP1.x)/distance; slope_y = ((double)lineP2.y-(double)lineP1.y)/distance; } else { //logger.debug("ZERO distance in path segment " + i1 + "/" + path.length + " of " + name); break; } // new char position is first line point position // minus the delta we've drawn over the previous // line point posChar_x = lineP1.x - nextDeltaSub * slope_x; posChar_y = lineP1.y - nextDeltaSub * slope_y; // as long as we have not passed the next line point while( ( (slope_x<=0 && posChar_x >= lineP2.x) || (slope_x>=0 && posChar_x <= lineP2.x) ) && ( (slope_y<=0 && posChar_y >= lineP2.y) || (slope_y>=0 && posChar_y <= lineP2.y) ) ) { // get the street name into the buffer if (streetNameCharIndex==-INDENT_PATHNAME) { // use full name to count fitting chars sbName.setLength(0); sbName.append(name); abbreviated=false; reversed=false; if(mode==PAINTMODE_DRAWCHARS) { if ( iNameRepeated>=iNameRepeatable && charsDrawable>0 && charsDrawable<name.length() ) { //if(info)System.out.println(sbName.toString() + " i1: " + i1 + " lastFitI1 " + lastFittingI1 + " charsdrawable: " + charsDrawable ); sbName.setLength(charsDrawable-1); abbreviated=true; if (sbName.length()==0) { sbName.append("."); } } // always begin drawing street names // left to right if (lineP1.x > lineP2.x) { sbName.reverse(); reversed=true; } } } // draw letter if (streetNameCharIndex >=0) { // char to draw letter=sbName.charAt(streetNameCharIndex); if (mode==PAINTMODE_DRAWCHARS) { // draw char only if it's at least partly on-screen if ( (int)posChar_x >= minCharScreenX && (int)posChar_x <= maxCharScreenX && (int)posChar_y >= minCharScreenX && (int)posChar_y <= maxCharScreenY ) { if (abbreviated) { pc.g.setColor(100,100,100); } else { pc.g.setColor(0,0,0); } pc.g.drawChar( letter, (int)posChar_x, (int)(posChar_y+(w/2)), Graphics.BASELINE | Graphics.HCENTER ); } } // if (mode==PAINTMODE_COUNTFITTINGCHARS ) { // pc.g.setColor(150,150,150); // pc.g.drawChar(letter, // (int)posChar_x, (int)(posChar_y+(w/2)), // Graphics.BASELINE | Graphics.HCENTER); // } // delta calculation should be improved if (Math.abs(slope_x) > Math.abs(slope_y)) { delta=(pathFont.charWidth(letter) + pathFontHeight ) /2; } else { delta=pathFontHeight*3/4; } } else { // delta for indent delta=pathFontHeight; } streetNameCharIndex++; if(mode==PAINTMODE_COUNTFITTINGCHARS) { charsDrawable=streetNameCharIndex; } // if at end of name if (streetNameCharIndex>=sbName.length()) { streetNameCharIndex=-INDENT_PATHNAME; if(mode==PAINTMODE_COUNTFITTINGCHARS) { // increase number of times the name fitted completely iNameRepeatable++; } else { iNameRepeated++; } } // add slope to char position posChar_x += slope_x * delta; posChar_y += slope_y * delta; // how much would we start to draw the next char over the end point if (slope_x != 0) { nextDeltaSub=(lineP2.x-posChar_x) / slope_x; } else { nextDeltaSub=0; } } // end while loop // continue in next path segment swapLineP = lineP1; lineP1 = lineP2; lineP2 = swapLineP; } // end segment for-loop } // end mode for-loop pc.g.setFont(originalFont); } public void paintPathOnewayArrows(PaintContext pc, SingleTile t) { // exit if not zoomed in enough WayDescription wayDesc = C.getWayDescription(type); if (pc.scale > wayDesc.maxOnewayArrowScale /* * pc.config.getDetailBoostMultiplier() */ ) { return; } if ( !Configuration.getCfgBitState(Configuration.CFGBIT_ONEWAY_ARROWS)) { return; } // calculate on-screen-width of the way double w = (int)(pc.ppm*wayDesc.wayWidth + 1); // if arrow would get too small do not draw if(w<3) { return; } // if arrow would be very small make it a bit larger if(w<5) { w=5; } // limit maximum arrow width if (w > 10) { w=10; } // calculate arrow length int lenTriangle = (int) ((w * 5) / 4); int lenLine = (int) ((w * 4) / 3); int completeLen = lenTriangle + lenLine; int sumTooSmallLen = 0; // determine region in which arrows can be drawn int minArrowScreenX = pc.g.getClipX() - completeLen; int minArrowScreenY = pc.g.getClipY() - completeLen; int maxArrowScreenX = minArrowScreenX + pc.g.getClipWidth() + completeLen; int maxArrowScreenY = minArrowScreenY + pc.g.getClipHeight() + completeLen; Projection p = pc.getP(); double posArrow_x = 0; double posArrow_y = 0; double slope_x=0; double slope_y=0; // int delta=0; // double nextDeltaSub=0; IntPoint lineP1 = pc.lineP1; IntPoint lineP2 = pc.lineP2; IntPoint swapLineP = pc.swapLineP; // draw arrow in each segment of path for (int i1 = 0; i1 < path.length; i1++) { // get the next line point coordinates into lineP2 int idx = this.path[i1]; // forward() is in Mercator.java p.forward(t.nodeLat[idx], t.nodeLon[idx], lineP2, t); // if we got only one line point, get a second one if (lineP1 == null) { lineP1 = lineP2; lineP2 = swapLineP; continue; } // calculate the slope of the new line double distance = Math.sqrt( ((double)lineP2.y-(double)lineP1.y)*((double)lineP2.y-(double)lineP1.y) + ((double)lineP2.x-(double)lineP1.x)*((double)lineP2.x-(double)lineP1.x) ); if (distance > completeLen || sumTooSmallLen > completeLen) { if (sumTooSmallLen > completeLen) { sumTooSmallLen = 0; // special color for not completely fitting arrows pc.g.setColor(80,80,80); } else { // normal color pc.g.setColor(50,50,50); } if (distance!=0) { slope_x = ((double)lineP2.x-(double)lineP1.x)/distance; slope_y = ((double)lineP2.y-(double)lineP1.y)/distance; } else { //logger.debug("ZERO distance in path segment " + i1 + "/" + path.length + " of " + name); break; } // new arrow position is middle of way segment posArrow_x = lineP1.x + slope_x * (distance-completeLen)/2; posArrow_y = lineP1.y + slope_y * (distance-completeLen)/2; // draw arrow only if it's at least partly on-screen if ( (int)posArrow_x >= minArrowScreenX && (int)posArrow_x <= maxArrowScreenX && (int)posArrow_y >= minArrowScreenX && (int)posArrow_y <= maxArrowScreenY ) { drawArrow(pc, posArrow_x, posArrow_y, slope_x, slope_y, w, lenLine, lenTriangle ); } // // delta calculation should be improved // delta = completeLen * 3; // // add slope to arrow position // posArrow_x += slope_x * delta; // posArrow_y += slope_y * delta; // if (slope_x==0 && slope_y==0) { // break; // } // // // how much would we start to draw the next arrow over the end point // if (slope_x != 0) { // nextDeltaSub=(lineP2.x-posArrow_x) / slope_x; // } } else { sumTooSmallLen += distance; } // continue in next path segment swapLineP = lineP1; lineP1 = lineP2; lineP2 = swapLineP; } // end segment for-loop } private void drawArrow( PaintContext pc, double x, double y, double slopeX, double slopeY, double w, int lenLine, int lenTriangle) { double x2 = x + slopeX * (double) lenLine; double y2 = y + slopeY * (double) lenLine; pc.g.drawLine((int) x, (int) y, (int) x2, (int) y2); pc.g.fillTriangle( (int)(x2 + slopeY * w/2), (int)(y2 - slopeX * w/2), (int)(x2 - slopeY * w/2), (int)(y2 + slopeX * w/2), (int)(x2 + slopeX * lenTriangle), (int)(y2 + slopeY * lenTriangle) ); } private float getParLines(int xPoints[], int yPoints[], int i, int w, IntPoint p1, IntPoint p2, IntPoint p3, IntPoint p4) { int i1 = i + 1; int dx = xPoints[i1] - xPoints[i]; int dy = yPoints[i1] - yPoints[i]; int l2 = dx * dx + dy * dy; float l2f = (float) Math.sqrt(l2); float lf = w / l2f; int xb = (int) ((Math.abs(lf * dy)) + 0.5f); int yb = (int) ((Math.abs(lf * dx)) + 0.5f); int rfx = 1; int rfy = 1; if (dy < 0) { rfx = -1; } if (dx > 0) { rfy = -1; } int xd = rfx * xb; int yd = rfy * yb; p1.x = xPoints[i] + xd; p1.y = yPoints[i] + yd; p2.x = xPoints[i] - xd; p2.y = yPoints[i] - yd; p3.x = xPoints[i1] + xd; p3.y = yPoints[i1] + yd; p4.x = xPoints[i1] - xd; p4.y = yPoints[i1] - yd; if (dx != 0) { return (MoreMath.atan(1f * dy / dx)); } else { if (dy > 0) { return MoreMath.PiDiv2; } else { return -MoreMath.PiDiv2; } } } private void draw(PaintContext pc, SingleTile t, int w, int xPoints[], int yPoints[], int hl[], int count,byte highlight/*,byte mode*/) { float roh1=0.0f; float roh2; IntPoint closestP = new IntPoint(); int wClosest = 0; boolean dividedSeg = false; boolean dividedHighlight = true; int originalX = 0; int originalY = 0; int max = count ; int beforeMax = max - 1; int wOriginal = w; if (w <1) w=1; int wDraw = w; int oldWDraw = 0; // setting this to 0 gets roh1 in the first step for (int i = 0; i < max; i++) { wDraw = w; // draw route line wider if ( highlight == HIGHLIGHT_ROUTEPATH_CONTAINED && hl[i] >= 0 && wDraw < Configuration.getMinRouteLineWidth() ) { wDraw = Configuration.getMinRouteLineWidth(); } if (dividedSeg) { // if this is a divided seg, draw second part of it xPoints[i] = xPoints[i+1]; yPoints[i] = yPoints[i+1]; xPoints[i+1] = originalX; yPoints[i+1] = originalY; dividedHighlight = !dividedHighlight; } else { // if not turn off the highlight dividedHighlight = false; } if (hl[i] >= 0 // if this is the closest segment of the closest connection && RouteInstructions.routePathConnection == hl[i] && i==RouteInstructions.pathIdxInRoutePathConnection - 1 && !dividedSeg ) { IntPoint centerP = new IntPoint(); // this is a divided seg (partly prior route line, partly current route line) dividedSeg = true; pc.getP().forward( (short) (SingleTile.fpm * (pc.center.radlat - t.centerLat)), (short) (SingleTile.fpm * (pc.center.radlon - t.centerLon)), centerP, t); // get point dividing the seg closestP = closestPointOnLine(xPoints[i], yPoints[i], xPoints[i + 1], yPoints[i + 1], centerP.x, centerP.y); // remember original next point originalX = xPoints[i + 1]; originalY = yPoints[i + 1]; // replace next point with closest point xPoints[i + 1] = closestP.x; yPoints[i + 1] = closestP.y; // remember width for drawing the closest point wClosest = wDraw; // get direction we go on the way Vector route=pc.trace.getRoute(); ConnectionWithNode c = (ConnectionWithNode) route.elementAt(hl[i]); dividedHighlight = (c.wayFromConAt > c.wayToConAt); } else { dividedSeg = false; } // get parLine again, if width has changed (when switching between highlighted / non-highlighted parts of the way) if (wDraw != oldWDraw) { roh1 = getParLines(xPoints, yPoints, i, wDraw, l1b, l2b, l1e, l2e); } if (i < beforeMax) { roh2 = getParLines(xPoints, yPoints, i + 1, wDraw, l3b, l4b, l3e, l4e); if (!MoreMath.approximately_equal(roh1, roh2, 0.5f)) { intersectionPoint(l1b, l1e, l3b, l3e, s1); intersectionPoint(l2b, l2e, l4b, l4e, s2); l1e.set(s1); l2e.set(s2); l3b.set(s1); l4b.set(s2); } } if (hl[i] != PATHSEG_DO_NOT_DRAW) { // if (mode == DRAW_AREA){ if (hl[i] >= 0) { if (isCurrentRoutePath(pc, i) || dividedHighlight) { pc.g.setColor(C.ROUTE_COLOR); } else { pc.g.setColor(C.ROUTEPRIOR_COLOR); } } else if (highlight == HIGHLIGHT_TARGET) { pc.g.setColor(255,50,50); } else { setColor(pc); } // when this is not render as lines (for the non-highlighted part of the way) or it is a highlighted part, draw as area if (wOriginal != 0 || hl[i] >= 0) { pc.g.fillTriangle(l2b.x, l2b.y, l1b.x, l1b.y, l1e.x, l1e.y); pc.g.fillTriangle(l1e.x, l1e.y, l2e.x, l2e.y, l2b.x, l2b.y); // draw borders of way if (hl[i] >= 0){ if (isCurrentRoutePath(pc, i) || dividedHighlight) { pc.g.setColor(C.ROUTE_BORDERCOLOR); } else { pc.g.setColor(C.ROUTEPRIOR_BORDERCOLOR); } } else if (highlight == HIGHLIGHT_TARGET){ pc.g.setColor(255,50,50); } else { setBorderColor(pc); } pc.g.drawLine(l1b.x, l1b.y, l1e.x, l1e.y); pc.g.drawLine(l2b.x, l2b.y, l2e.x, l2e.y); } else { pc.g.drawLine(xPoints[i], yPoints[i], xPoints[i + 1], yPoints[i + 1]); } } l1b.set(l3b); l2b.set(l4b); l1e.set(l3e); l2e.set(l4e); if (dividedSeg) { // if this is a divided seg, in the next step draw the second part i--; } } if (wClosest != 0) { // if we got a closest seg, draw closest point to the center in it pc.g.setColor(C.ROUTEDOT_COLOR); pc.g.fillArc(closestP.x-wClosest, closestP.y-wClosest, wClosest*2, wClosest*2, 0, 360); pc.g.setColor(C.ROUTEDOT_BORDERCOLOR); pc.g.drawArc(closestP.x-wClosest, closestP.y-wClosest, wClosest*2, wClosest*2, 0, 360); } } /** * * @param lineP1x - in screen coordinates * @param lineP1y - in screen coordinates * @param lineP2x - in screen coordinates * @param lineP2y - in screen coordinates * @param offPointX - point outside the line in screen coordinates * @param offPointY - point outside the line in screen coordinates * @return IntPoint - closest point on line in screen coordinates */ private static IntPoint closestPointOnLine(int lineP1x, int lineP1y, int lineP2x, int lineP2y, int offPointX, int offPointY) { float uX = (float) (lineP2x - lineP1x); float uY = (float) (lineP2y - lineP1y); float u = ( (offPointX - lineP1x) * uX + (offPointY - lineP1y) * uY) / (uX * uX + uY * uY); if (u > 1.0) { return new IntPoint(lineP2x, lineP2y); } else if (u <= 0.0) { return new IntPoint(lineP1x, lineP1y); } else { return new IntPoint( (int)(lineP2x * u + lineP1x * (1.0 - u ) + 0.5), (int) (lineP2y * u + lineP1y * (1.0-u) + 0.5)); } } /** * @param pc * @param i - segment idx in the way's path to check * @return true, if the current segment in the way's path is not reached yet, else false */ private boolean isCurrentRoutePath(PaintContext pc, int i) { if (RouteInstructions.routePathConnection != hl[i]) { return (RouteInstructions.routePathConnection < hl[i]); } ConnectionWithNode c = (ConnectionWithNode) pc.trace.getRoute().elementAt(RouteInstructions.routePathConnection); return ( (c.wayFromConAt < c.wayToConAt) ?RouteInstructions.pathIdxInRoutePathConnection <= i :RouteInstructions.pathIdxInRoutePathConnection > i+1 ); } private IntPoint intersectionPoint(IntPoint p1, IntPoint p2, IntPoint p3, IntPoint p4, IntPoint ret) { int dx1 = p2.x - p1.x; int dx2 = p4.x - p3.x; int dx3 = p1.x - p3.x; int dy1 = p2.y - p1.y; int dy2 = p1.y - p3.y; int dy3 = p4.y - p3.y; float r = dx1 * dy3 - dy1 * dx2; if (r != 0f) { r = (1f * (dy2 * (p4.x - p3.x) - dx3 * dy3)) / r; ret.x = (int) ((p1.x + r * dx1) + 0.5); ret.y = (int) ((p1.y + r * dy1) + 0.5); } else { if (((p2.x - p1.x) * (p3.y - p1.y) - (p3.x - p1.x) * (p2.y - p1.y)) == 0) { ret.x = p3.x; ret.y = p3.y; } else { ret.x = p4.x; ret.y = p4.y; } } return ret; } /* private boolean getLineLineIntersection(IntPoint p1, IntPoint p2, IntPoint p3, IntPoint p4, IntPoint ret) { float x1 = p1.x; float y1 = p1.y; float x2 = p2.x; float y2 = p2.y; float x3 = p3.x; float y3 = p3.y; float x4 = p4.x; float y4 = p4.y; ret.x = (int) ((det(det(x1, y1, x2, y2), x1 - x2, det(x3, y3, x4, y4), x3 - x4) / det(x1 - x2, y1 - y2, x3 - x4, y3 - y4)) + 0.5); ret.y = (int) ((det(det(x1, y1, x2, y2), y1 - y2, det(x3, y3, x4, y4), y3 - y4) / det(x1 - x2, y1 - y2, x3 - x4, y3 - y4)) + 0.5); return true; } */ /* private static float det(float a, float b, float c, float d) { return a * d - b * c; } */ public void paintAsArea(PaintContext pc, SingleTile t) { WayDescription wayDesc = C.getWayDescription(type); byte om = C.getWayOverviewMode(type); switch (om & C.OM_MODE_MASK) { case C.OM_SHOWNORMAL: // if not in Overview Mode check for scale if (pc.scale > wayDesc.maxScale * Configuration.getDetailBoostMultiplier()) { return; } if (wayDesc.hideable && !Configuration.getCfgBitState(Configuration.CFGBIT_AREAS)) { return; } break; case C.OM_HIDE: if (wayDesc.hideable) { return; } break; } switch (om & C.OM_NAME_MASK) { case C.OM_WITH_NAMEPART: if (nameIdx == -1) return; String name = pc.trace.getName(nameIdx); if (name == null) return; if (name.toUpperCase().indexOf(C.get0Poi1Area2WayNamePart((byte) 1).toUpperCase()) == -1) return; break; case C.OM_WITH_NAME: if (nameIdx == -1) return; break; case C.OM_NO_NAME: if (nameIdx != -1) return; break; } IntPoint lineP2 = pc.lineP2; Projection p = pc.getP(); /** * we should probably use the static x and y variables * but that would require to rewrite the fillPolygon * function */ int[] x = new int[path.length]; int[] y = new int[path.length]; for (int i1 = 0; i1 < path.length; i1++) { int idx = path[i1]; p.forward(t.nodeLat[idx], t.nodeLon[idx], lineP2, t); x[i1] = lineP2.x; y[i1] = lineP2.y; } /*if ((x[0] != x[path.length - 1]) || (y[0] != y[path.length - 1])){ System.out.println("WARNING: start and end coordinates of area don't match " + this); return; }*/ //PolygonGraphics.drawPolygon(g, x, y); //DrawUtil.fillPolygon(x, y, wayDesc.lineColor, pc.g); PolygonGraphics.fillPolygon(pc.g, x, y); paintAreaName(pc,t); } public void paintAreaName(PaintContext pc, SingleTile t) { WayDescription wayDesc = C.getWayDescription(type); if (pc.scale > wayDesc.maxTextScale * Configuration.getDetailBoostMultiplier() ) { return; } if (wayDesc.hideable && !Configuration.getCfgBitState(Configuration.CFGBIT_AREATEXTS)) { return; } String name=null; if ( Configuration.getCfgBitState(Configuration.CFGBIT_SHOWWAYPOITYPE)) { name=wayDesc.description; } else { if (nameIdx != -1) { name=Trace.getInstance().getName(nameIdx); } } // if zoomed in enough, show description if (pc.scale < wayDesc.maxDescriptionScale) { // show waydescription if (name==null) { name=wayDesc.description; } else { name=name + " (" + wayDesc.description + ")"; } } if (name == null) return; IntPoint lineP2 = pc.lineP2; Projection p = pc.getP(); int x; int y; // get screen clip int clipX=pc.g.getClipX(); int clipY=pc.g.getClipY(); int clipMaxX=clipX+pc.g.getClipWidth(); int clipMaxY=clipY+pc.g.getClipHeight();; // find center of area int minX=clipMaxX; int maxX=clipX; int minY=clipMaxY; int maxY=clipY; for (int i1 = 0; i1 < path.length; i1++) { int idx = path[i1]; p.forward(t.nodeLat[idx], t.nodeLon[idx], lineP2, t); x = lineP2.x; y = lineP2.y; if (minX>x) minX=x; if (minY>y) minY=y; if (maxX<x) maxX=x; if (maxY<y) maxY=y; } // System.out.println("name:" + name + " ClipX:" + clipX + " ClipMaxX:" + clipMaxX + " ClipY:" + clipY + " ClipMaxY:" + clipMaxY + " minx:" + minX + " maxX:"+maxX + " miny:"+minY+ " maxY" + maxY); Font originalFont = pc.g.getFont(); if (areaFont==null) { areaFont=Font.getFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_SMALL); areaFontHeight=areaFont.getHeight(); } // find out how many chars of the name fit into the area int i=name.length()+1; int w; do { i--; w=areaFont.substringWidth(name,0,i); } while (w>(maxX-minX) && i>1); // is area wide enough to draw at least a dot into it? if ((maxX-minX)>=3 ) { pc.g.setColor(0,0,0); // if at least two chars have fit or name is a fitting single char, draw name if (i>1 || (i==name.length() && w<=(maxX-minX)) ) { pc.g.setFont(areaFont); // center vertically in area int y1=(minY+maxY-areaFontHeight)/2; // draw centered into area pc.g.drawSubstring(name, 0, i, (minX+maxX-w)/2, y1, Graphics.TOP | Graphics.LEFT); // if name fits not completely, append "..." if (i!=name.length()) { pc.g.drawString("...", (minX+maxX+w)/2, y1, Graphics.TOP | Graphics.LEFT); } pc.g.setFont(originalFont); // else draw a dot to indicate there's a name for this area available } else { pc.g.drawRect((minX+maxX)/2, (minY+maxY)/2, 0, 0 ); } } } public void setColor(PaintContext pc) { WayDescription wayDesc = C.getWayDescription(type); pc.g.setStrokeStyle(wayDesc.lineStyle); pc.g.setColor(wayDesc.lineColor); } public int getWidth(PaintContext pc) { WayDescription wayDesc = C.getWayDescription(type); return wayDesc.wayWidth; } public void setBorderColor(PaintContext pc) { pc.g.setStrokeStyle(Graphics.SOLID); WayDescription wayDesc = C.getWayDescription(type); pc.g.setColor(wayDesc.boardedColor); } public boolean isOneway(){ return ((flags & WAY_ONEWAY) == WAY_ONEWAY); } /** * Checks if the way is a cirlceway (a closed way - with the same node at the start and the end) * @return true if this way is a circleway */ public boolean isCircleway(SingleTile t) { return (path[0] == path[path.length - 1]); } public boolean isArea() { return ((flags & WAY_AREA) > 0); } public boolean isRoundAbout() { return ((flags & WAY_ROUNDABOUT) > 0); } public boolean isTunnel() { return ((flags & WAY_TUNNEL) > 0); } public boolean isBridge() { return ((flags & WAY_BRIDGE) > 0); } public int getMaxSpeed() { return ((flags & MaxSpeedMask) >> MaxSpeedShift); } /* private float[] getFloatNodes(SingleTile t, short[] nodes, float offset) { float [] res = new float[nodes.length]; for (int i = 0; i < nodes.length; i++) { res[i] = nodes[i]*SingleTile.fpminv + offset; } return res; } */ public float[] getNodesLatLon(SingleTile t, boolean latlon) { float offset; short [] nodes; int len = path.length; float [] lat = new float[len]; if (latlon) { offset = t.centerLat; nodes = t.nodeLat; } else { offset = t.centerLon; nodes = t.nodeLon; } for (int i = 0; i < len; i++) { lat[i] = nodes[path[i]]*SingleTile.fpminv + offset; } return lat; } public String toString() { return "Way " + Trace.getInstance().getName(nameIdx) + " type: " + C.getWayDescription(type).description; } }
true
true
public void processPath(PaintContext pc, SingleTile t, int mode, byte layer) { WayDescription wayDesc = C.getWayDescription(type); /** width of the way to be painted */ int w = 0; byte highlight=HIGHLIGHT_NONE; /** * If the static array is not large enough, increase it */ if (x.length < path.length) { x = new int[path.length]; y = new int[path.length]; hl = new int[path.length]; } // initialize with default draw states for the path's segments int hlDefault = PATHSEG_DO_NOT_HIGHLIGHT; if ( (mode & Tile.OPT_HIGHLIGHT) != 0) { hlDefault = PATHSEG_DO_NOT_DRAW; } for (int i1 = 0; i1 < path.length; i1++) { hl[i1] = hlDefault; } if ((mode & Tile.OPT_PAINT) > 0) { byte om = C.getWayOverviewMode(type); switch (om & C.OM_MODE_MASK) { case C.OM_SHOWNORMAL: // if not in Overview Mode check for scale if (pc.scale > wayDesc.maxScale * Configuration.getDetailBoostMultiplier()) { return; } break; case C.OM_HIDE: if (wayDesc.hideable) { return; } break; } switch (om & C.OM_NAME_MASK) { case C.OM_WITH_NAMEPART: if (nameIdx == -1) return; String name = pc.trace.getName(nameIdx); if (name == null) return; /** * The overview filter mode allows you to restrict showing ways if their name * does not match a substring. So check if this condition is fulfilled. */ if (name.toUpperCase().indexOf(C.get0Poi1Area2WayNamePart((byte) 2).toUpperCase()) == -1) return; break; case C.OM_WITH_NAME: if (nameIdx == -1) return; break; case C.OM_NO_NAME: if (nameIdx != -1) return; break; } /** * check if way matches to one or more route connections, * so we can highlight the route line parts */ Vector route=pc.trace.getRoute(); ConnectionWithNode c; if (route!=null && route.size()!=0) { for (int i=0; i<route.size()-1; i++){ c = (ConnectionWithNode) route.elementAt(i); if (c.wayNameIdx == this.nameIdx && wayDesc.routable) { if (path.length > c.wayFromConAt && path.length > c.wayToConAt) { int idx = path[c.wayFromConAt]; short searchCon1Lat = (short) ((c.to.lat - t.centerLat) * t.fpm); if ( (Math.abs(t.nodeLat[idx] - searchCon1Lat) < 2) ) { short searchCon1Lon = (short) ((c.to.lon - t.centerLon) * t.fpm); if ( (Math.abs(t.nodeLon[idx] - searchCon1Lon) < 2) ) { idx = path[c.wayToConAt]; ConnectionWithNode c2 = (ConnectionWithNode) route.elementAt(i+1); searchCon1Lat = (short) ((c2.to.lat - t.centerLat) * t.fpm); if ( (Math.abs(t.nodeLat[idx] - searchCon1Lat) < 2) ) { searchCon1Lon = (short) ((c2.to.lon - t.centerLon) * t.fpm); if ( (Math.abs(t.nodeLon[idx] - searchCon1Lon) < 2) ) { // if we are not in highlight mode, flag that this layer contains a path segment to highlight if ((mode & Tile.OPT_HIGHLIGHT) == 0) { pc.hlLayers |= (1<<layer); } // set way highlight flag so we can quickly determine if this way contains a route line part highlight = HIGHLIGHT_ROUTEPATH_CONTAINED; /* * flag the parts of the way as to be highlighted * by putting in the index of the corresponding connection */ short from = c.wayFromConAt; short to = c.wayToConAt; boolean isCircleway = isCircleway(t); if (from > to && !(isRoundAbout() || isCircleway) ) { // swap direction to = from; from = c.wayToConAt; } for (int n = from; n != to; n++) { hl[n] = i; if ( ( isRoundAbout() || isCircleway ) && n >= (path.length-1) ) { n=-1; // // if in roundabout at end of path continue at first node if (to == (path.length-1) ) { break; } } } } } } } } } } } } /** * If this way is not to be highlighted but we are in highlight mode, * skip the rest of the processing of this way */ if (highlight == HIGHLIGHT_NONE && (mode & Tile.OPT_HIGHLIGHT) != 0) { return; } /** * We go through the way segment by segment * (a segment is a line between two consecutive points on the path). * lineP1 is first node of the segment, lineP2 is the second. */ IntPoint lineP1 = pc.lineP1; IntPoint lineP2 = pc.lineP2; IntPoint swapLineP = pc.swapLineP; Projection p = pc.getP(); int pi=0; for (int i1 = 0; i1 < path.length; i1++) { int idx = path[i1]; p.forward(t.nodeLat[idx], t.nodeLon[idx], lineP2,t); if (lineP1 == null) { /** * This is the first segment of the path, so we don't have a lineP1 yet */ lineP1 = lineP2; lineP2 = swapLineP; x[pi] = lineP1.x; y[pi++] = lineP1.y; } else { /** * We save some rendering time, by doing a line simplification on the fly. * If two nodes are very close by, then we can simply drop one of the nodes * and draw the line between the other points. If the way is highlighted, * we can't do any simplification, as we need to determine the index of the segment * that is closest to the center (= map center) of the PaintContext */ if (highlight == HIGHLIGHT_ROUTEPATH_CONTAINED || ! lineP1.approximatelyEquals(lineP2)){ /** * calculate closest distance to specific ways */ float dst = MoreMath.ptSegDistSq(lineP1.x, lineP1.y, lineP2.x, lineP2.y, pc.xSize / 2, pc.ySize / 2); if (dst < pc.squareDstToWay || dst < pc.squareDstToActualRoutableWay) { float pen = 0; /** * Add a heuristic so that the direction of travel and the direction * of the way should more or less match if we are travelling on this way */ if (addDirectionalPenalty) { int segDirVecX = lineP1.x-lineP2.x; int segDirVecY = lineP1.y-lineP2.y; float norm = (float) Math.sqrt((double)(segDirVecX*segDirVecX + segDirVecY*segDirVecY)); //This is a hack to use a linear approximation to keep computational requirements down pen = scalePen*(1.0f - Math.abs((segDirVecX*courseVecX + segDirVecY*courseVecY)/norm)); pen*=pen; } // if this way is closer including penalty than the old one set it as new actualWay if (dst + pen < pc.squareDstToWay) { pc.squareDstToWay = dst + pen; pc.actualWay = this; pc.actualSingleTile = t; } // if this routable way is closer including penalty than the old one set it as new actualRoutableWay if (dst < pc.squareDstToActualRoutableWay + pen && wayDesc.routable) { pc.squareDstToActualRoutableWay = dst + pen; pc.actualRoutableWay = this; } } if (dst < pc.squareDstToRoutableWay && wayDesc.routable) { pc.squareDstToRoutableWay = dst; pc.nearestRoutableWay = this; } if ((hl[i1-1] > PATHSEG_DO_NOT_HIGHLIGHT) && (dst < pc.squareDstToRoutePath)) { pc.squareDstToRoutePath = dst; pc.routePathConnection = hl[i1-1]; pc.pathIdxInRoutePathConnection = pi; } x[pi] = lineP2.x; y[pi++] = lineP2.y; swapLineP = lineP1; lineP1 = lineP2; lineP2 = swapLineP; } else if ((i1+1) == path.length){ /** * This is an endpoint, so we can't simply drop it, as the lines would potentially look disconnected */ //System.out.println(" endpoint " + lineP2.x + "/" + lineP2.y+ " " +pc.trace.getName(nameIdx)); if (!lineP1.equals(lineP2)){ x[pi] = lineP2.x; y[pi++] = lineP2.y; } else { //System.out.println(" discarding never the less"); } } else { /** * Drop this point, it is redundant */ //System.out.println(" discard " + lineP2.x + "/" + lineP2.y+ " " +pc.trace.getName(nameIdx)); } } } swapLineP = lineP1; lineP1 = null; /** * TODO: Can we remove this call and do it the same way as with actualWay and introduce a * pc.nearestRoutableWaySingleTile and only calculate the entity and position mark when we need them? */ if ((pc.nearestRoutableWay == this) && ((pc.currentPos == null) || (pc.currentPos.entity != this))) { pc.currentPos = new PositionMark(pc.center.radlat, pc.center.radlon); pc.currentPos.setEntity(this, getNodesLatLon(t, true), getNodesLatLon(t, false)); } if ((mode & Tile.OPT_PAINT) > 0) { /** * Calculate the width of the path to be drawn. A width of 1 * corresponds to it being draw as a thin line rather than as a * street */ if (Configuration .getCfgBitState(Configuration.CFGBIT_STREETRENDERMODE) && wayDesc.wayWidth > 1) { w = (int) (pc.ppm * wayDesc.wayWidth / 2 + 0.5); } if (highlight != HIGHLIGHT_ROUTEPATH_CONTAINED && pc.target != null && this.equals(pc.target.entity)) { highlight = HIGHLIGHT_TARGET; } // if render as lines and no part of the way is highlighted if (w == 0 && highlight == HIGHLIGHT_NONE) { setColor(pc); PolygonGraphics.drawOpenPolygon(pc.g, x, y, pi - 1); // if render as streets or a part of the way is highlighted } else { draw(pc, t, (w == 0) ? 1 : w, x, y, hl, pi - 1, highlight); } if (isOneway()) { paintPathOnewayArrows(pc, t); } paintPathName(pc, t); } }
public void processPath(PaintContext pc, SingleTile t, int mode, byte layer) { WayDescription wayDesc = C.getWayDescription(type); /** width of the way to be painted */ int w = 0; byte highlight=HIGHLIGHT_NONE; /** * If the static array is not large enough, increase it */ if (x.length < path.length) { x = new int[path.length]; y = new int[path.length]; hl = new int[path.length]; } // initialize with default draw states for the path's segments int hlDefault = PATHSEG_DO_NOT_HIGHLIGHT; if ( (mode & Tile.OPT_HIGHLIGHT) != 0) { hlDefault = PATHSEG_DO_NOT_DRAW; } for (int i1 = 0; i1 < path.length; i1++) { hl[i1] = hlDefault; } if ((mode & Tile.OPT_PAINT) > 0) { byte om = C.getWayOverviewMode(type); switch (om & C.OM_MODE_MASK) { case C.OM_SHOWNORMAL: // if not in Overview Mode check for scale if (pc.scale > wayDesc.maxScale * Configuration.getDetailBoostMultiplier()) { return; } break; case C.OM_HIDE: if (wayDesc.hideable) { return; } break; } switch (om & C.OM_NAME_MASK) { case C.OM_WITH_NAMEPART: if (nameIdx == -1) return; String name = pc.trace.getName(nameIdx); if (name == null) return; /** * The overview filter mode allows you to restrict showing ways if their name * does not match a substring. So check if this condition is fulfilled. */ if (name.toUpperCase().indexOf(C.get0Poi1Area2WayNamePart((byte) 2).toUpperCase()) == -1) return; break; case C.OM_WITH_NAME: if (nameIdx == -1) return; break; case C.OM_NO_NAME: if (nameIdx != -1) return; break; } /** * check if way matches to one or more route connections, * so we can highlight the route line parts */ Vector route=pc.trace.getRoute(); ConnectionWithNode c; if (route!=null && route.size()!=0) { for (int i=0; i<route.size()-1; i++){ c = (ConnectionWithNode) route.elementAt(i); if (c.wayNameIdx == this.nameIdx && wayDesc.routable) { if (path.length > c.wayFromConAt && path.length > c.wayToConAt) { int idx = path[c.wayFromConAt]; short searchCon1Lat = (short) ((c.to.lat - t.centerLat) * t.fpm); if ( (Math.abs(t.nodeLat[idx] - searchCon1Lat) < 2) ) { short searchCon1Lon = (short) ((c.to.lon - t.centerLon) * t.fpm); if ( (Math.abs(t.nodeLon[idx] - searchCon1Lon) < 2) ) { idx = path[c.wayToConAt]; ConnectionWithNode c2 = (ConnectionWithNode) route.elementAt(i+1); searchCon1Lat = (short) ((c2.to.lat - t.centerLat) * t.fpm); if ( (Math.abs(t.nodeLat[idx] - searchCon1Lat) < 2) ) { searchCon1Lon = (short) ((c2.to.lon - t.centerLon) * t.fpm); if ( (Math.abs(t.nodeLon[idx] - searchCon1Lon) < 2) ) { // if we are not in highlight mode, flag that this layer contains a path segment to highlight if ((mode & Tile.OPT_HIGHLIGHT) == 0) { pc.hlLayers |= (1<<layer); } // set way highlight flag so we can quickly determine if this way contains a route line part highlight = HIGHLIGHT_ROUTEPATH_CONTAINED; /* * flag the parts of the way as to be highlighted * by putting in the index of the corresponding connection */ short from = c.wayFromConAt; short to = c.wayToConAt; boolean isCircleway = isCircleway(t); if (from > to && !(isRoundAbout() || isCircleway) ) { // swap direction to = from; from = c.wayToConAt; } for (int n = from; n != to; n++) { hl[n] = i; if ( ( isRoundAbout() || isCircleway ) && n >= (path.length-1) ) { n=-1; // // if in roundabout at end of path continue at first node if (to == (path.length-1) ) { break; } } } } } } } } } } } } /** * If this way is not to be highlighted but we are in highlight mode, * skip the rest of the processing of this way */ if (highlight == HIGHLIGHT_NONE && (mode & Tile.OPT_HIGHLIGHT) != 0) { return; } /** * We go through the way segment by segment * (a segment is a line between two consecutive points on the path). * lineP1 is first node of the segment, lineP2 is the second. */ IntPoint lineP1 = pc.lineP1; IntPoint lineP2 = pc.lineP2; IntPoint swapLineP = pc.swapLineP; Projection p = pc.getP(); int pi=0; for (int i1 = 0; i1 < path.length; i1++) { int idx = path[i1]; p.forward(t.nodeLat[idx], t.nodeLon[idx], lineP2,t); if (lineP1 == null) { /** * This is the first segment of the path, so we don't have a lineP1 yet */ lineP1 = lineP2; lineP2 = swapLineP; x[pi] = lineP1.x; y[pi++] = lineP1.y; } else { /** * We save some rendering time, by doing a line simplification on the fly. * If two nodes are very close by, then we can simply drop one of the nodes * and draw the line between the other points. If the way is highlighted, * we can't do any simplification, as we need to determine the index of the segment * that is closest to the center (= map center) of the PaintContext */ if (highlight == HIGHLIGHT_ROUTEPATH_CONTAINED || ! lineP1.approximatelyEquals(lineP2)){ /** * calculate closest distance to specific ways */ float dst = MoreMath.ptSegDistSq(lineP1.x, lineP1.y, lineP2.x, lineP2.y, pc.xSize / 2, pc.ySize / 2); if (dst < pc.squareDstToWay || dst < pc.squareDstToActualRoutableWay) { float pen = 0; /** * Add a heuristic so that the direction of travel and the direction * of the way should more or less match if we are travelling on this way */ if (addDirectionalPenalty) { int segDirVecX = lineP1.x-lineP2.x; int segDirVecY = lineP1.y-lineP2.y; float norm = (float) Math.sqrt((double)(segDirVecX*segDirVecX + segDirVecY*segDirVecY)); //This is a hack to use a linear approximation to keep computational requirements down pen = scalePen*(1.0f - Math.abs((segDirVecX*courseVecX + segDirVecY*courseVecY)/norm)); pen*=pen; } // if this way is closer including penalty than the old one set it as new actualWay if (dst + pen < pc.squareDstToWay) { pc.squareDstToWay = dst + pen; pc.actualWay = this; pc.actualSingleTile = t; } // if this routable way is closer including penalty than the old one set it as new actualRoutableWay if (dst + pen < pc.squareDstToActualRoutableWay && wayDesc.routable) { pc.squareDstToActualRoutableWay = dst + pen; pc.actualRoutableWay = this; } } if (dst < pc.squareDstToRoutableWay && wayDesc.routable) { pc.squareDstToRoutableWay = dst; pc.nearestRoutableWay = this; } if ((hl[i1-1] > PATHSEG_DO_NOT_HIGHLIGHT) && (dst < pc.squareDstToRoutePath)) { pc.squareDstToRoutePath = dst; pc.routePathConnection = hl[i1-1]; pc.pathIdxInRoutePathConnection = pi; } x[pi] = lineP2.x; y[pi++] = lineP2.y; swapLineP = lineP1; lineP1 = lineP2; lineP2 = swapLineP; } else if ((i1+1) == path.length){ /** * This is an endpoint, so we can't simply drop it, as the lines would potentially look disconnected */ //System.out.println(" endpoint " + lineP2.x + "/" + lineP2.y+ " " +pc.trace.getName(nameIdx)); if (!lineP1.equals(lineP2)){ x[pi] = lineP2.x; y[pi++] = lineP2.y; } else { //System.out.println(" discarding never the less"); } } else { /** * Drop this point, it is redundant */ //System.out.println(" discard " + lineP2.x + "/" + lineP2.y+ " " +pc.trace.getName(nameIdx)); } } } swapLineP = lineP1; lineP1 = null; /** * TODO: Can we remove this call and do it the same way as with actualWay and introduce a * pc.nearestRoutableWaySingleTile and only calculate the entity and position mark when we need them? */ if ((pc.nearestRoutableWay == this) && ((pc.currentPos == null) || (pc.currentPos.entity != this))) { pc.currentPos = new PositionMark(pc.center.radlat, pc.center.radlon); pc.currentPos.setEntity(this, getNodesLatLon(t, true), getNodesLatLon(t, false)); } if ((mode & Tile.OPT_PAINT) > 0) { /** * Calculate the width of the path to be drawn. A width of 1 * corresponds to it being draw as a thin line rather than as a * street */ if (Configuration .getCfgBitState(Configuration.CFGBIT_STREETRENDERMODE) && wayDesc.wayWidth > 1) { w = (int) (pc.ppm * wayDesc.wayWidth / 2 + 0.5); } if (highlight != HIGHLIGHT_ROUTEPATH_CONTAINED && pc.target != null && this.equals(pc.target.entity)) { highlight = HIGHLIGHT_TARGET; } // if render as lines and no part of the way is highlighted if (w == 0 && highlight == HIGHLIGHT_NONE) { setColor(pc); PolygonGraphics.drawOpenPolygon(pc.g, x, y, pi - 1); // if render as streets or a part of the way is highlighted } else { draw(pc, t, (w == 0) ? 1 : w, x, y, hl, pi - 1, highlight); } if (isOneway()) { paintPathOnewayArrows(pc, t); } paintPathName(pc, t); } }
diff --git a/Hadoop/src/main/java/uk/bl/wap/hadoop/ArchiveFileRecordReader.java b/Hadoop/src/main/java/uk/bl/wap/hadoop/ArchiveFileRecordReader.java index 4b293a2..c236a0a 100644 --- a/Hadoop/src/main/java/uk/bl/wap/hadoop/ArchiveFileRecordReader.java +++ b/Hadoop/src/main/java/uk/bl/wap/hadoop/ArchiveFileRecordReader.java @@ -1,201 +1,201 @@ package uk.bl.wap.hadoop; import static org.archive.io.warc.WARCConstants.HEADER_KEY_TYPE; import static org.archive.io.warc.WARCConstants.RESPONSE; import java.io.IOException; import java.util.Iterator; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.mapred.FileSplit; import org.apache.hadoop.mapred.InputSplit; import org.apache.hadoop.mapred.MultiFileSplit; import org.apache.hadoop.mapred.RecordReader; import org.apache.log4j.Logger; import org.archive.io.ArchiveReader; import org.archive.io.ArchiveReaderFactory; import org.archive.io.ArchiveRecord; import org.archive.io.ArchiveRecordHeader; import uk.bl.wap.util.warc.WARCRecordUtils; @SuppressWarnings( "deprecation" ) public class ArchiveFileRecordReader<Key extends WritableComparable<?>, Value extends Writable> implements RecordReader<Text, WritableArchiveRecord> { private static Logger log = Logger.getLogger(ArchiveFileRecordReader.class.getName()); private FSDataInputStream datainputstream; private FileStatus status; private FileSystem filesystem; private long maxPayloadSize; private String[] url_excludes; private String[] response_includes; private String[] protocol_includes; private Path[] paths; int currentPath = -1; Long offset = 0L; private ArchiveReader arcreader; private Iterator<ArchiveRecord> iterator; private ArchiveRecord record; private ArchiveRecordHeader header; private String archiveName; public ArchiveFileRecordReader( Configuration conf, InputSplit split ) throws IOException { this.maxPayloadSize = conf.getLong( "archive.size.max", 104857600L ); log.warn("maxPayloadSize="+this.maxPayloadSize); this.url_excludes = conf.getStrings( "record.exclude.url", new String[] {} ); log.warn("url_excludes="+this.printList(url_excludes)); this.response_includes = conf.getStrings( "record.include.response", new String[] { "200" } ); log.warn("response_includes="+this.printList(response_includes)); this.protocol_includes = conf.getStrings( "record.include.protocol", new String[] { "http", "https" } ); log.warn("protocol_includes="+this.printList(protocol_includes)); this.filesystem = FileSystem.get( conf ); if( split instanceof FileSplit ) { this.paths = new Path[ 1 ]; this.paths[ 0 ] = ( ( FileSplit ) split ).getPath(); } else if( split instanceof MultiFileSplit ) { this.paths = ( ( MultiFileSplit ) split ).getPaths(); } else { throw new IOException( "InputSplit is not a file split or a multi-file split - aborting" ); } this.nextFile(); } private String printList(String[] set ) { String list = ""; for( String item : set ) { if( ! "".equals(list) ) list += ","; list += item; } return list; } @Override public void close() throws IOException { if( datainputstream != null ) { try { datainputstream.close(); } catch( IOException e ) { System.err.println( "close(): " + e.getMessage() ); } } } @Override public Text createKey() { return new Text(); } @Override public WritableArchiveRecord createValue() { return new WritableArchiveRecord(); } @Override public long getPos() throws IOException { return datainputstream.getPos(); } @Override public float getProgress() throws IOException { return datainputstream.getPos() / ( 1024 * 1024 * this.status.getLen() ); } @Override public boolean next( Text key, WritableArchiveRecord value ) throws IOException { boolean found = false; while( !found ) { boolean hasNext = false; try { hasNext = iterator.hasNext(); } catch( Exception e ) { System.err.println( e.toString() ); hasNext = false; } try { if( hasNext ) { record = ( ArchiveRecord ) iterator.next(); header = record.getHeader(); String url = header.getUrl(); if( header.getHeaderFieldKeys().contains( HEADER_KEY_TYPE ) && !header.getHeaderValue( HEADER_KEY_TYPE ).equals( RESPONSE ) ) { continue; } if( header.getLength() <= maxPayloadSize && this.checkUrl( url ) && this.checkProtocol( url ) ) { String http = WARCRecordUtils.getHeaders( record, true ); value.setHttpHeaders( http ); if( value.getHttpHeader( "bl_status" ) != null && this.checkResponse( value.getHttpHeader( "bl_status" ).split( " " )[ 1 ] ) ) { found = true; key.set( this.archiveName ); value.setRecord( record ); } } else { log.debug("Skipped record, length="+header.getLength()+" checkUrl="+checkUrl(url)+" checkProtocol="+checkProtocol(url)); } } else if( !this.nextFile() ) { break; } - } catch( Exception e ) { + } catch( Throwable e ) { found = false; - e.printStackTrace(); - System.err.println( e.toString() ); + log.error( "ERROR reading "+this.archiveName+": "+ e.toString() ); + //e.printStackTrace(); } } return found; } private boolean nextFile() throws IOException { currentPath++; if( currentPath >= paths.length ) { return false; } this.status = this.filesystem.getFileStatus( paths[ currentPath ] ); datainputstream = this.filesystem.open( paths[ currentPath ] ); arcreader = ( ArchiveReader ) ArchiveReaderFactory.get( paths[ currentPath ].getName(), datainputstream, true ); iterator = arcreader.iterator(); this.archiveName = paths[ currentPath ].getName(); return true; } private boolean checkUrl( String url ) { for( String exclude : url_excludes ) { if( !"".equals(exclude) && url.matches( ".*" + exclude + ".*" ) ) { return false; } } return true; } private boolean checkProtocol( String url ) { for( String include : protocol_includes ) { if( "".equals(include) || url.startsWith( include ) ) { return true; } } return false; } private boolean checkResponse( String response ) { for( String include : response_includes ) { if( "".equals(include) || response.matches( include ) ) { return true; } } return false; } }
false
true
public boolean next( Text key, WritableArchiveRecord value ) throws IOException { boolean found = false; while( !found ) { boolean hasNext = false; try { hasNext = iterator.hasNext(); } catch( Exception e ) { System.err.println( e.toString() ); hasNext = false; } try { if( hasNext ) { record = ( ArchiveRecord ) iterator.next(); header = record.getHeader(); String url = header.getUrl(); if( header.getHeaderFieldKeys().contains( HEADER_KEY_TYPE ) && !header.getHeaderValue( HEADER_KEY_TYPE ).equals( RESPONSE ) ) { continue; } if( header.getLength() <= maxPayloadSize && this.checkUrl( url ) && this.checkProtocol( url ) ) { String http = WARCRecordUtils.getHeaders( record, true ); value.setHttpHeaders( http ); if( value.getHttpHeader( "bl_status" ) != null && this.checkResponse( value.getHttpHeader( "bl_status" ).split( " " )[ 1 ] ) ) { found = true; key.set( this.archiveName ); value.setRecord( record ); } } else { log.debug("Skipped record, length="+header.getLength()+" checkUrl="+checkUrl(url)+" checkProtocol="+checkProtocol(url)); } } else if( !this.nextFile() ) { break; } } catch( Exception e ) { found = false; e.printStackTrace(); System.err.println( e.toString() ); } } return found; }
public boolean next( Text key, WritableArchiveRecord value ) throws IOException { boolean found = false; while( !found ) { boolean hasNext = false; try { hasNext = iterator.hasNext(); } catch( Exception e ) { System.err.println( e.toString() ); hasNext = false; } try { if( hasNext ) { record = ( ArchiveRecord ) iterator.next(); header = record.getHeader(); String url = header.getUrl(); if( header.getHeaderFieldKeys().contains( HEADER_KEY_TYPE ) && !header.getHeaderValue( HEADER_KEY_TYPE ).equals( RESPONSE ) ) { continue; } if( header.getLength() <= maxPayloadSize && this.checkUrl( url ) && this.checkProtocol( url ) ) { String http = WARCRecordUtils.getHeaders( record, true ); value.setHttpHeaders( http ); if( value.getHttpHeader( "bl_status" ) != null && this.checkResponse( value.getHttpHeader( "bl_status" ).split( " " )[ 1 ] ) ) { found = true; key.set( this.archiveName ); value.setRecord( record ); } } else { log.debug("Skipped record, length="+header.getLength()+" checkUrl="+checkUrl(url)+" checkProtocol="+checkProtocol(url)); } } else if( !this.nextFile() ) { break; } } catch( Throwable e ) { found = false; log.error( "ERROR reading "+this.archiveName+": "+ e.toString() ); //e.printStackTrace(); } } return found; }
diff --git a/ui/webui/src/eu/sqooss/webui/Project.java b/ui/webui/src/eu/sqooss/webui/Project.java index f4838fd8..9ad12e93 100644 --- a/ui/webui/src/eu/sqooss/webui/Project.java +++ b/ui/webui/src/eu/sqooss/webui/Project.java @@ -1,702 +1,702 @@ /* * This file is part of the Alitheia system, developed by the SQO-OSS * consortium as part of the IST FP6 SQO-OSS project, number 033331. * * Copyright 2007-2008 by the SQO-OSS consortium members <[email protected]> * Copyright 2007-2008 by Sebastian Kuegler <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package eu.sqooss.webui; import java.util.*; import eu.sqooss.webui.datatype.Developer; import eu.sqooss.webui.datatype.Version; import eu.sqooss.webui.util.DevelopersList; import eu.sqooss.webui.util.MetricsList; import eu.sqooss.webui.util.TaggedVersionsList; import eu.sqooss.webui.util.VersionsList; import eu.sqooss.ws.client.datatypes.WSStoredProject; /** * This class represents a project that has been evaluated by the SQO-OSS * framework. * <br/> * It provides access to the project metadata, versions and files. * In addition it provides information about the metrics that have been * applied to this project and its resources. */ public class Project extends WebuiItem { /* * Project meta-data fields */ private String bts; private String repository; private String mail; private String contact; private String website; private long[] developersIds; private long[] mailingListIds; /* * Holds the Id of the currently selected project version. */ private Long currentVersionId; /* * Holds the number of versions that exist in this project. */ private Long versionsCount = null; /* * Key versions cache */ private Version firstVersion = null; private Version lastVersion = null; /* * A cache for all versions associated with this project, that were * retrieved from the SQO-OSS framework during this session. */ private VersionsList versions = new VersionsList(); /* * A cache for all tagged versions that exist in this project. */ private TaggedVersionsList tagged = new TaggedVersionsList(); /* * A cache for the version that has been selected for this project. */ private Version selectedVersion = null; /* * A cache for all metrics that have been evaluated on this project. */ private MetricsList metrics = new MetricsList(); /* * A cache for all metrics that have been selected for this project. */ private MetricsList selectedMetrics = new MetricsList(); /* * A cache for all developers that are/were working on this project. */ private DevelopersList developers = new DevelopersList(); /* * A cache for all developers that have been selected for this project. */ private DevelopersList selectedDevelopers = new DevelopersList(); /** * Instantiates a new <code>Project</code> object, without initializing * its data. The object can be initialized later on by calling its * <code>initProject()</code> method. */ public Project() { setServletPath("/projects.jsp"); reqParName = "pid"; } /** * Instantiates a new <code>Project</code> object, and initializes it with * the meta-data stored in the given <code>WStoredProject</code> object. * * @param p the project object */ public Project(WSStoredProject p) { setServletPath("/projects.jsp"); reqParName = "pid"; initProject(p); } /** * Initializes or updates this object with the meta-data stored in the * given <code>WStoredProject</code> object. * * @param p the project object */ private void initProject(WSStoredProject p) { if (p != null) { id = p.getId(); name = p.getName(); bts = p.getBugs(); repository = p.getRepository(); mail = p.getMail(); contact = p.getContact(); website = p.getWebsite(); Long[] devIds = Functions.strToLongArray(p.getDevelopers(), ";"); if (devIds != null) { int index = 0; developersIds = new long[devIds.length]; for (Long id : devIds) developersIds[index++] = id; } Long[] mlIds = Functions.strToLongArray(p.getMailingLists(), ";"); if ((mlIds != null) && (mlIds.length > 0)) { int index = 0; - mailingListIds = new long[devIds.length]; + mailingListIds = new long[mlIds.length]; for (Long id : mlIds) mailingListIds[index++] = id; } } } /** * Copies the target object's meta-data into this object. * * @param p the target <code>Project</code> instance */ public void copy (Project p) { if (p != null) { id = p.getId(); name = p.getName(); bts = p.getBugs(); repository = p.getRepository(); mail = p.getMail(); contact = p.getContact(); website = p.getWebsite(); developersIds = p.getDevelopersIds(); mailingListIds = p.getMailingListIds(); } } /** * Gets the project's home-page location. * * @return the project's home-page location, or <code>null</code> when * the project is not yet initialized. */ public String getWebsite () { return website; } /** * Gets the project's contact email address. * * @return the project's contact email address, or <code>null</code> when * the project is not yet initialized. */ public String getContact () { return contact; } /** * Gets the project's mailing lists location. * * @return the project's mailing lists location, or <code>null</code> * when the project is not yet initialized. */ public String getMail () { return mail; } /** * Gets the project's BTS location. * * @return the project's BTS location, or <code>null</code> when the * project is not yet initialized. */ public String getBugs() { return bts; } /** * Gets the project's source repository location. * * @return the project's source repository location, or <code>null</code> * when the project is not yet initialized. */ public String getRepository() { return repository; } /** * Gets the list of Ids of all developers, which are working on this * project * * @return the list of developer Ids */ public long[] getDevelopersIds() { return developersIds; } /** * Gets the list of Ids of all mailing lists, which are associated with * this project * * @return the list of mailing list Ids */ public long[] getMailingListIds() { return mailingListIds; } //======================================================================== // DATA RETRIEVAL METHODS //======================================================================== /** * Retrieves the version with the given Id from the SQO-OSS framework, * unless the local cache contains that version already. * * @param versionId the version Id * * @return the version object, or <code>null</code> if a version with the * given Id doesn't exist for this project. */ public Version getVersion (Long versionId) { Version result = null; // Check in the versions cache first if (versions.getVersionById(versionId) != null) result = versions.getVersionById(versionId); // Otherwise retrieve it from the SQO-OSS framework else if (terrier != null) { result = terrier.getVersion(this.getId(), versionId); if (result != null) versions.add(result); } return result; } /** * Retrieves the version with the given number from the SQO-OSS framework, * unless the local cache contains that version already. * * @param versionNumber the version number * * @return the version object, or <code>null</code> if a version with the * given number doesn't exist for this project. */ public Version getVersionByNumber (long versionNumber) { Version result = null; // Check in the versions cache first if (versions.getVersionByNumber(versionNumber) != null) result = versions.getVersionByNumber(versionNumber); // Otherwise retrieve it from the SQO-OSS framework else if (terrier != null) { List<Version> version = terrier.getVersionsByNumber( this.getId(), new long[]{versionNumber}); if (version.isEmpty() == false) result = version.get(0); if (result != null) versions.add(result); } return result; } /** * Retrieves the list of tagged versions for this project from the SQO-OSS * framework, unless the local cache contains these versions already. * * @return the list of tagged project versions, or an empty list when none * are found. */ public TaggedVersionsList getTaggedVersions() { if ((tagged.isEmpty()) && (terrier != null)) tagged.addAll(terrier.getTaggedVersionsByProjectId(this.getId())); return tagged; } /** * Retrieves the list of all metrics that have been evaluated on this * project from the SQO-OSS framework, unless the local cache contains * some data already. * * @return the list of metrics evaluated on this project, or an empty * list when none are found or the project not yet initialized. */ public MetricsList getEvaluatedMetrics() { if (terrier == null) return metrics; if (isValid()) { if (metrics.isEmpty()) { metrics.addAll(terrier.getMetricsForProject(id)); selectAllMetrics(); } } else terrier.addError("Invalid project!"); return metrics; } /** * Retrieves the list of all developers that are/were working on this * project from the SQO-OSS framework, unless the local cache contains * some data already. * * @return the list of developers working on this project, or an empty * list when none are found or the project not yet initialized. */ public DevelopersList getDevelopers() { if (terrier == null) return developers; if (isValid()) { if ((developersIds != null) && (developers.isEmpty())) { developers.addAll(terrier.getDevelopers(developersIds)); } } return developers; } /** * Returns the total number of developers in this project * * @return Total number of developers in this project. */ public long getDevelopersCount() { if (developersIds != null) return developersIds.length; else return 0; } /** * Returns the total number of mailing lists in this project * * @return Total number of mailing lists in this project. */ public long getMailingListCount() { if (mailingListIds != null) return mailingListIds.length; else return 0; } /** * Retrieves all the data that is required by this object from the * SQO-OSS framework, unless the cache contains some data already * or this project is not yet initialized. * * @param terrier the <code>Terrier<code> instance */ public void retrieveData(Terrier terrier) { if (terrier == null) return; if (isValid()) { setTerrier(terrier); getEvaluatedMetrics(); getDevelopers(); } else terrier.addError("Invalid project!"); } /** * Flushes all the data that is cached by this object. */ public void flushData() { currentVersionId = null; versionsCount = null; firstVersion = null; lastVersion = null; selectedVersion = null; versions.clear(); metrics.clear(); developers.clear(); selectedMetrics = new MetricsList(); } /** * Flushes the list of evaluated metrics that is cached by this object. */ public void flushMetrics() { metrics.clear(); } //======================================================================== // VERSION RELATED METHODS //======================================================================== /** * Sets the first version of this project. * * @param version the version object */ public void setFirstVersion(Version version) { if (version != null) firstVersion = version; } /** * Gets the first known version of this project. * * @return the first version's object, or <code>null<code> if the project * has no versions at all. */ public Version getFirstVersion() { if (isValid()) { if ((firstVersion == null) && (terrier != null)) firstVersion = terrier.getFirstProjectVersion(getId()); } else terrier.addError("Invalid project!"); return firstVersion; } /** * Sets the last version of this project. * * @param version the version object */ public void setLastVersion(Version version) { if (version != null) lastVersion = version; } /** * Gets the last known version of this project. * * @return the last version's object, or <code>null</code> if the project * has no versions at all. */ public Version getLastVersion() { if (isValid()) { if ((lastVersion == null) && (terrier != null)) lastVersion = terrier.getLastProjectVersion(getId()); } else terrier.addError("Invalid project!"); return lastVersion; } /** * Sets the current version. * * @param version the version object */ public void setCurrentVersion(Version version) { if ((version != null) && (version.isValid())){ selectedVersion = version; currentVersionId = version.getId(); } } /** * Gets the current version. * * @return The version object. */ public Version getCurrentVersion() { if (selectedVersion == null) selectedVersion = getLastVersion(); return selectedVersion; } /** * Sets the version with the given number as current. * * @param versionNumber the version number */ public void setCurrentVersionId(Long versionNumber) { currentVersionId = versionNumber; } /** * Returns the number of the current version. * * @return the version number, or <code>null</code> if a current version * is not yet defined. */ public Long getCurrentVersionId() { try { if (currentVersionId == null) { return getLastVersion().getId(); } return currentVersionId; } catch (NullPointerException e) { terrier.addError("Could not retrieve current version."); return null; } } /** * Returns the total number of versions in this project * * @return Total number of versions in this project. */ public long getVersionsCount() { if (versionsCount == null) versionsCount = terrier.getVersionsCount(id); if (versionsCount != null) return versionsCount; else return 0; } //======================================================================== // METRIC SELECTION METHODS //======================================================================== /** * Adds the metric with the given Id to the list of metrics that are * selected for this project. * * @param id the metric Id */ public void selectMetric (Long id) { if (id != null) { Metric metric = metrics.getMetricById(id); if (metric != null) selectedMetrics.add(metric); } } /** * Removes the metric with the given Id from the list of metrics that were * selected for this project. * * @param id the metric Id */ public void deselectMetric (Long id) { if (id != null) { Metric metric = metrics.getMetricById(id); if (metric != null) selectedMetrics.remove(metric); } } /** * Adds all evaluated metrics to the list of selected metrics. */ public void selectAllMetrics () { for (Metric metric : metrics) if (selectedMetrics.contains(metric) == false) selectedMetrics.add(metric); } /** * Cleans up the list of selected metrics. */ public void deselectAllMetrics () { selectedMetrics.clear(); } /** * Returns the list of all metrics that were selected for this project. * * @return the list of selected metrics. */ public MetricsList getSelectedMetrics() { return selectedMetrics; } //======================================================================== // DEVELOPER SELECTION METHODS //======================================================================== /** * Adds the developer with the given Id to the list of developers that are * selected for this project. * * @param id the developer Id */ public void selectDeveloper (Long id) { if (id != null) { Developer developer = developers.getDeveloperById(id); if (developer != null) selectedDevelopers.add(developer); } } /** * Removes the developer with the given Id from the list of developers * that were selected for this project. * * @param id the developer Id */ public void deselectDeveloper (Long id) { if (id != null) { Developer developer = developers.getDeveloperById(id); if (developer != null) selectedDevelopers.remove(developer); } } /** * Adds all project developers to the list of selected developers. */ public void selectAllDevelopers () { for (Developer developer : developers) if (selectedDevelopers.contains(developer) == false) selectedDevelopers.add(developer); } /** * Cleans up the list of selected developers. */ public void deselectAllDevelopers () { selectedDevelopers.clear(); } /** * Returns the list of all developers that were selected for this project. * * @return the list of selected developers. */ public DevelopersList getSelectedDevelopers() { return selectedDevelopers; } //======================================================================== // RESULTS RENDERING METHODS //======================================================================== /* (non-Javadoc) * @see eu.sqooss.webui.WebuiItem#getHtml(long) */ public String getHtml(long in) { // Holds the accumulated HTML content StringBuilder html = new StringBuilder(""); if (isValid()) html.append(sp(in) + "<h2>" + getName() + "</h2>"); else html.append(sp(in) + Functions.error("Invalid project!")); return html.toString(); } //======================================================================== // IMPLEMENTATIONS OF REQUIRED java.lang.Object METHODS //======================================================================== /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object target) { if (this == target) return true; if (target == null) return false; if (getClass() != target.getClass()) return false; Project project = (Project) target; if (getId().equals(project.getId())) if (getName().equals(project.getId())) return true; return false; } }
true
true
private void initProject(WSStoredProject p) { if (p != null) { id = p.getId(); name = p.getName(); bts = p.getBugs(); repository = p.getRepository(); mail = p.getMail(); contact = p.getContact(); website = p.getWebsite(); Long[] devIds = Functions.strToLongArray(p.getDevelopers(), ";"); if (devIds != null) { int index = 0; developersIds = new long[devIds.length]; for (Long id : devIds) developersIds[index++] = id; } Long[] mlIds = Functions.strToLongArray(p.getMailingLists(), ";"); if ((mlIds != null) && (mlIds.length > 0)) { int index = 0; mailingListIds = new long[devIds.length]; for (Long id : mlIds) mailingListIds[index++] = id; } } }
private void initProject(WSStoredProject p) { if (p != null) { id = p.getId(); name = p.getName(); bts = p.getBugs(); repository = p.getRepository(); mail = p.getMail(); contact = p.getContact(); website = p.getWebsite(); Long[] devIds = Functions.strToLongArray(p.getDevelopers(), ";"); if (devIds != null) { int index = 0; developersIds = new long[devIds.length]; for (Long id : devIds) developersIds[index++] = id; } Long[] mlIds = Functions.strToLongArray(p.getMailingLists(), ";"); if ((mlIds != null) && (mlIds.length > 0)) { int index = 0; mailingListIds = new long[mlIds.length]; for (Long id : mlIds) mailingListIds[index++] = id; } } }