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/strategy/FilterWriter.java b/src/strategy/FilterWriter.java index c475567..34a1821 100644 --- a/src/strategy/FilterWriter.java +++ b/src/strategy/FilterWriter.java @@ -1,176 +1,175 @@ package strategy; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import model.SensorInfo; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; public class FilterWriter implements IPsaWriter{ ArrayList<SensorInfo> sensors; Document doc; @Override public void setup(ArrayList<SensorInfo> orderedSensors) { sensors = orderedSensors; System.out.println(); System.out.println("2 strategy"); System.out.println(orderedSensors); } @Override public void readTemplate() throws JDOMException, IOException { SAXBuilder builder = new SAXBuilder(); doc = builder.build (new File("./psa_templates/FilterTemplate.xml")); } @Override public void writeUpperSection() { // TODO Auto-generated method stub Element root = doc.getRootElement(); Element inputFileArray = root.getChild("InputFileArray"); inputFileArray.setAttribute("size", "" + 0); } @Override public void writeCalcArray(String userPoly) { //CalcArray Element from Element root = doc.getRootElement(); Element calcArray = root.getChild("CalcArray"); //sets the size of the calcArray calcArray.setAttribute("Size", "" + sensors.size()); //counter int counter = 0; //places sensors in calcArray for (SensorInfo sensor : sensors){ //set up CalcArrayItem Element calcArrayItem = new Element("CalcArrayItem"); calcArrayItem.setAttribute("index", "" + counter++); calcArrayItem.setAttribute("CalcID", "" + sensor.getCalcID()); //adds calcArrayItem to calcArray calcArray.addContent(calcArrayItem); //set up Calc Element calc = new Element("Calc"); calc.setAttribute("UnitID", "" + sensor.getUnitID()); calc.setAttribute("Ordinal", "" + sensor.getOrdinal()); //add calc to calcaArrayItem calcArrayItem.addContent(calc); //set up FullName Element fullName = new Element("FullName"); if (sensor.getFullName().startsWith("Upoly")) { - fullName.setAttribute("value", - "" + sensor.getFullName() + ", " + userPoly); + fullName.setAttribute("value", "Upoly 0, " + sensor.getFullName() + ", " + userPoly); } else { fullName.setAttribute("value", "" + sensor.getFullName() ); } //add fullname to calc calc.addContent(fullName); //set up elements unqiue to 'Upoly 0, Upoly 0, ISUS V3 Nitrate' if (sensor.getFullName().startsWith("Upoly")) { Element calcName = new Element("CalcName"); calcName.setAttribute("value", "Upoly 0, " + userPoly); calc.addContent(calcName); } //set up elements unqiue to 'Oxygen, SBE 43' else if (sensor.getFullName().startsWith("Oxygen")) { //set up windowsize Element windowSize = new Element("WindowSize"); windowSize.setAttribute("value", "2.000000"); //set up applyHysteresisCorrection Element applyHysteresisCorrection = new Element("ApplyHysteresisCorrection"); applyHysteresisCorrection.setAttribute("value", "1"); //set up applyTauCorrection Element applyTauCorrection = new Element("ApplyTauCorrection"); applyTauCorrection.setAttribute("value", "1"); calc.addContent(windowSize); calc.addContent(applyHysteresisCorrection); calc.addContent(applyTauCorrection); } //set up elements unqiue to Descent Rate [m/s] else if (sensor.getFullName().startsWith("Descent")){ Element windowSize = new Element("WindowSize"); windowSize.setAttribute("value", "2.000000"); calc.addContent(windowSize); } } } @Override public void writeLowerSection() { //FilterTypeArray Element from Element root = doc.getRootElement(); Element filterTypeArray = root.getChild("FilterTypeArray"); boolean first = true; int counter = 0; for (SensorInfo sensor: sensors){ Element arrayItem = new Element("ArrayItem"); arrayItem.setAttribute("index", "" + counter++); int value; if (first){ value = 2; first = false; } else { value = 1; } arrayItem.setAttribute("value", "" + value); filterTypeArray.addContent(arrayItem); } } @Override public void writeToNewPsaFile() throws FileNotFoundException, IOException { // TODO Auto-generated method stub XMLOutputter xmlOutput = new XMLOutputter(Format.getPrettyFormat()); xmlOutput.output(doc, new FileOutputStream(new File( "output/FilterIMOS.psa"))); System.out.println("Wrote to file"); } }
true
true
public void writeCalcArray(String userPoly) { //CalcArray Element from Element root = doc.getRootElement(); Element calcArray = root.getChild("CalcArray"); //sets the size of the calcArray calcArray.setAttribute("Size", "" + sensors.size()); //counter int counter = 0; //places sensors in calcArray for (SensorInfo sensor : sensors){ //set up CalcArrayItem Element calcArrayItem = new Element("CalcArrayItem"); calcArrayItem.setAttribute("index", "" + counter++); calcArrayItem.setAttribute("CalcID", "" + sensor.getCalcID()); //adds calcArrayItem to calcArray calcArray.addContent(calcArrayItem); //set up Calc Element calc = new Element("Calc"); calc.setAttribute("UnitID", "" + sensor.getUnitID()); calc.setAttribute("Ordinal", "" + sensor.getOrdinal()); //add calc to calcaArrayItem calcArrayItem.addContent(calc); //set up FullName Element fullName = new Element("FullName"); if (sensor.getFullName().startsWith("Upoly")) { fullName.setAttribute("value", "" + sensor.getFullName() + ", " + userPoly); } else { fullName.setAttribute("value", "" + sensor.getFullName() ); } //add fullname to calc calc.addContent(fullName); //set up elements unqiue to 'Upoly 0, Upoly 0, ISUS V3 Nitrate' if (sensor.getFullName().startsWith("Upoly")) { Element calcName = new Element("CalcName"); calcName.setAttribute("value", "Upoly 0, " + userPoly); calc.addContent(calcName); } //set up elements unqiue to 'Oxygen, SBE 43' else if (sensor.getFullName().startsWith("Oxygen")) { //set up windowsize Element windowSize = new Element("WindowSize"); windowSize.setAttribute("value", "2.000000"); //set up applyHysteresisCorrection Element applyHysteresisCorrection = new Element("ApplyHysteresisCorrection"); applyHysteresisCorrection.setAttribute("value", "1"); //set up applyTauCorrection Element applyTauCorrection = new Element("ApplyTauCorrection"); applyTauCorrection.setAttribute("value", "1"); calc.addContent(windowSize); calc.addContent(applyHysteresisCorrection); calc.addContent(applyTauCorrection); } //set up elements unqiue to Descent Rate [m/s] else if (sensor.getFullName().startsWith("Descent")){ Element windowSize = new Element("WindowSize"); windowSize.setAttribute("value", "2.000000"); calc.addContent(windowSize); } } }
public void writeCalcArray(String userPoly) { //CalcArray Element from Element root = doc.getRootElement(); Element calcArray = root.getChild("CalcArray"); //sets the size of the calcArray calcArray.setAttribute("Size", "" + sensors.size()); //counter int counter = 0; //places sensors in calcArray for (SensorInfo sensor : sensors){ //set up CalcArrayItem Element calcArrayItem = new Element("CalcArrayItem"); calcArrayItem.setAttribute("index", "" + counter++); calcArrayItem.setAttribute("CalcID", "" + sensor.getCalcID()); //adds calcArrayItem to calcArray calcArray.addContent(calcArrayItem); //set up Calc Element calc = new Element("Calc"); calc.setAttribute("UnitID", "" + sensor.getUnitID()); calc.setAttribute("Ordinal", "" + sensor.getOrdinal()); //add calc to calcaArrayItem calcArrayItem.addContent(calc); //set up FullName Element fullName = new Element("FullName"); if (sensor.getFullName().startsWith("Upoly")) { fullName.setAttribute("value", "Upoly 0, " + sensor.getFullName() + ", " + userPoly); } else { fullName.setAttribute("value", "" + sensor.getFullName() ); } //add fullname to calc calc.addContent(fullName); //set up elements unqiue to 'Upoly 0, Upoly 0, ISUS V3 Nitrate' if (sensor.getFullName().startsWith("Upoly")) { Element calcName = new Element("CalcName"); calcName.setAttribute("value", "Upoly 0, " + userPoly); calc.addContent(calcName); } //set up elements unqiue to 'Oxygen, SBE 43' else if (sensor.getFullName().startsWith("Oxygen")) { //set up windowsize Element windowSize = new Element("WindowSize"); windowSize.setAttribute("value", "2.000000"); //set up applyHysteresisCorrection Element applyHysteresisCorrection = new Element("ApplyHysteresisCorrection"); applyHysteresisCorrection.setAttribute("value", "1"); //set up applyTauCorrection Element applyTauCorrection = new Element("ApplyTauCorrection"); applyTauCorrection.setAttribute("value", "1"); calc.addContent(windowSize); calc.addContent(applyHysteresisCorrection); calc.addContent(applyTauCorrection); } //set up elements unqiue to Descent Rate [m/s] else if (sensor.getFullName().startsWith("Descent")){ Element windowSize = new Element("WindowSize"); windowSize.setAttribute("value", "2.000000"); calc.addContent(windowSize); } } }
diff --git a/src/main/java/com/ssm/llp/web/controller/secure/FilterController.java b/src/main/java/com/ssm/llp/web/controller/secure/FilterController.java index 66cd9d4..df2f378 100644 --- a/src/main/java/com/ssm/llp/web/controller/secure/FilterController.java +++ b/src/main/java/com/ssm/llp/web/controller/secure/FilterController.java @@ -1,57 +1,63 @@ package com.ssm.llp.web.controller.secure; import com.ssm.llp.core.dao.SsmFilterDao; import com.ssm.llp.core.model.SsmFilter; import org.hibernate.SessionFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; /** * @author rafizan.baharum * @since 9/14/13 */ @Controller @RequestMapping("/secure/filter") @Transactional public class FilterController extends SecureControllerSupport { private Logger log = LoggerFactory.getLogger(FilterController.class); @Autowired private SessionFactory sessionFactory; @Autowired private SsmFilterDao filterDao; @RequestMapping(value = "/all", method = {RequestMethod.GET}) public String all(ModelMap model) { model.put("filters", filterDao.find()); return "secure/filter"; } @RequestMapping(value = "/edit/{id}", method = {RequestMethod.GET}) public String edit(@PathVariable Long id, ModelMap model) { model.put("filter", filterDao.findById(id)); return "secure/filter_edit"; } @RequestMapping(value = "/update", method = {RequestMethod.POST}) - public String update(@RequestParam Long id, @RequestParam String name, @RequestParam String description, @RequestParam String script, ModelMap model) { + public String update(@RequestParam Long id, + @RequestParam String name, + @RequestParam String description, + @RequestParam String error, + @RequestParam String script, + ModelMap model) { SsmFilter n = filterDao.findById(id); n.setName(name); n.setDescription(description); + n.setError(error); n.setScript(script); filterDao.update(n, getCurrentUser()); sessionFactory.getCurrentSession().flush(); return "redirect:/secure/filter/edit/" + n.getId(); } }
false
true
public String update(@RequestParam Long id, @RequestParam String name, @RequestParam String description, @RequestParam String script, ModelMap model) { SsmFilter n = filterDao.findById(id); n.setName(name); n.setDescription(description); n.setScript(script); filterDao.update(n, getCurrentUser()); sessionFactory.getCurrentSession().flush(); return "redirect:/secure/filter/edit/" + n.getId(); }
public String update(@RequestParam Long id, @RequestParam String name, @RequestParam String description, @RequestParam String error, @RequestParam String script, ModelMap model) { SsmFilter n = filterDao.findById(id); n.setName(name); n.setDescription(description); n.setError(error); n.setScript(script); filterDao.update(n, getCurrentUser()); sessionFactory.getCurrentSession().flush(); return "redirect:/secure/filter/edit/" + n.getId(); }
diff --git a/table/src/main/uk/ac/starlink/table/storage/FileByteStore.java b/table/src/main/uk/ac/starlink/table/storage/FileByteStore.java index b1bcd77a9..64591db5c 100644 --- a/table/src/main/uk/ac/starlink/table/storage/FileByteStore.java +++ b/table/src/main/uk/ac/starlink/table/storage/FileByteStore.java @@ -1,176 +1,177 @@ package uk.ac.starlink.table.storage; import java.io.File; import java.io.FileOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.FileChannel; import java.nio.channels.WritableByteChannel; import java.util.logging.Logger; import uk.ac.starlink.table.ByteStore; /** * ByteStore implementation which uses a temporary file. * * @author Mark Taylor * @since 11 Jul 2008 */ public class FileByteStore implements ByteStore { private final File file_; private final OutputStream out_; private final int maxBufLen_; private long length_; private final Logger logger_ = Logger.getLogger( "uk.ac.starlink.table.storage" ); /** * Constructs a new FileByteStore which uses the given file as a * backing store. Nothing is done to mark this file as temporary. * * @param file location of the backing file which will be used * @throws IOException if there is some I/O-related problem with * opening the file * @throws SecurityException if the current security context does not * allow writing to a temporary file */ public FileByteStore( File file ) throws IOException { file_ = file; out_ = new FileOutputStream( file_ ) { public void write( int b ) throws IOException { super.write( b ); length_++; } public void write( byte[] b ) throws IOException { super.write( b ); length_ += b.length; } public void write( byte[] b, int off, int len ) throws IOException { super.write( b, off, len ); length_ += len; } }; maxBufLen_ = Integer.MAX_VALUE; } /** * Constructs a new FileByteStore which uses a temporary file as * backing store. * The temporary file will be written to the default temporary * directory, given by the value of the <tt>java.io.tmpdir</tt> * system property. * * @throws IOException if there is some I/O-related problem with * opening the file * @throws SecurityException if the current security context does not * allow writing to a temporary file */ public FileByteStore() throws IOException { this( File.createTempFile( "FileByteStore", ".bin" ) ); file_.deleteOnExit(); logger_.info( "Creating new temporary file: " + file_ ); } /** * Returns the file used by this store. * * @return file */ public File getFile() { return file_; } public OutputStream getOutputStream() { return out_; } public long getLength() { return length_; } public void copy( OutputStream out ) throws IOException { out_.flush(); copy( file_, out ); } public ByteBuffer[] toByteBuffers() throws IOException { out_.flush(); return toByteBuffers( file_, maxBufLen_ ); } /** * Utility method to copy the contents of a file to an output stream. * The stream is not closed. * * @param file file * @param out destination stream */ static void copy( File file, OutputStream out ) throws IOException { FileInputStream in = new FileInputStream( file ); long size = file.length(); FileChannel inChannel = in.getChannel(); WritableByteChannel outChannel = out instanceof FileOutputStream ? ((FileOutputStream) out).getChannel() : Channels.newChannel( out ); long count = inChannel.transferTo( 0, size, outChannel ); in.close(); if ( count < size ) { throw new IOException( "Only " + count + "/" + size + " bytes could be transferred" ); } } /** * Utility method to return a ByteBuffer backed by a file. * * @param file file * @param maxLen maximum length of a single buffer * @return mapped byte buffers */ static ByteBuffer[] toByteBuffers( File file, int maxLen ) throws IOException { long size = file.length(); if ( size == 0 ) { return new ByteBuffer[] { ByteBuffer.allocate( 0 ) }; } FileInputStream in = new FileInputStream( file ); FileChannel chan = in.getChannel(); FileChannel.MapMode mode = FileChannel.MapMode.READ_ONLY; long mBuf = ( ( size - 1 ) / maxLen ) + 1; int nBuf = (int) mBuf; if ( nBuf != mBuf ) { throw new IOException( "HOW big???" ); } ByteBuffer[] bufs = new ByteBuffer[ nBuf ]; for ( int ib = 0; ib < nBuf; ib++ ) { - long start = ib * maxLen; + long start = ib * (long) maxLen; + assert size >= 0; assert size - start > 0; long len = Math.min( size - start, maxLen ); bufs[ ib ] = chan.map( mode, start, len ); } in.close(); return bufs; } public void close() { try { out_.close(); } catch ( IOException e ) { logger_.warning( "close error: " + e ); } if ( file_.delete() ) { logger_.info( "Deleting temporary file: " + file_ ); } else if ( file_.exists() ) { logger_.warning( "Failed to delete temporary file " + file_ ); } else { logger_.info( "Temporary file got deleted before close" ); } } }
true
true
static ByteBuffer[] toByteBuffers( File file, int maxLen ) throws IOException { long size = file.length(); if ( size == 0 ) { return new ByteBuffer[] { ByteBuffer.allocate( 0 ) }; } FileInputStream in = new FileInputStream( file ); FileChannel chan = in.getChannel(); FileChannel.MapMode mode = FileChannel.MapMode.READ_ONLY; long mBuf = ( ( size - 1 ) / maxLen ) + 1; int nBuf = (int) mBuf; if ( nBuf != mBuf ) { throw new IOException( "HOW big???" ); } ByteBuffer[] bufs = new ByteBuffer[ nBuf ]; for ( int ib = 0; ib < nBuf; ib++ ) { long start = ib * maxLen; assert size - start > 0; long len = Math.min( size - start, maxLen ); bufs[ ib ] = chan.map( mode, start, len ); } in.close(); return bufs; }
static ByteBuffer[] toByteBuffers( File file, int maxLen ) throws IOException { long size = file.length(); if ( size == 0 ) { return new ByteBuffer[] { ByteBuffer.allocate( 0 ) }; } FileInputStream in = new FileInputStream( file ); FileChannel chan = in.getChannel(); FileChannel.MapMode mode = FileChannel.MapMode.READ_ONLY; long mBuf = ( ( size - 1 ) / maxLen ) + 1; int nBuf = (int) mBuf; if ( nBuf != mBuf ) { throw new IOException( "HOW big???" ); } ByteBuffer[] bufs = new ByteBuffer[ nBuf ]; for ( int ib = 0; ib < nBuf; ib++ ) { long start = ib * (long) maxLen; assert size >= 0; assert size - start > 0; long len = Math.min( size - start, maxLen ); bufs[ ib ] = chan.map( mode, start, len ); } in.close(); return bufs; }
diff --git a/sip-core/src/main/java/eu/delving/metadata/AnalysisTreeNode.java b/sip-core/src/main/java/eu/delving/metadata/AnalysisTreeNode.java index 66bbe69b..bce036f7 100644 --- a/sip-core/src/main/java/eu/delving/metadata/AnalysisTreeNode.java +++ b/sip-core/src/main/java/eu/delving/metadata/AnalysisTreeNode.java @@ -1,228 +1,228 @@ /* * Copyright 2010 DELVING BV * * Licensed under the EUPL, Version 1.0 or? as soon they * will be approved by the European Commission - subsequent * versions of the EUPL (the "Licence"); * you may not use this work except in compliance with the * Licence. * You may obtain a copy of the Licence at: * * http://ec.europa.eu/idabc/eupl * * Unless required by applicable law or agreed to in * writing, software distributed under the Licence is * distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. * See the Licence for the specific language governing * permissions and limitations under the Licence. */ package eu.delving.metadata; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import java.io.Serializable; import java.util.*; /** * A node of the analysis tree * * @author Gerald de Jong <[email protected]> */ public class AnalysisTreeNode implements AnalysisTree.Node, Serializable { private static final long serialVersionUID = -8362212829296408316L; private AnalysisTreeNode parent; private List<AnalysisTreeNode> children = new ArrayList<AnalysisTreeNode>(); private Tag tag; private boolean recordRoot, uniqueElement; private FieldStatistics fieldStatistics; AnalysisTreeNode(Tag tag) { this.tag = tag; } AnalysisTreeNode(AnalysisTreeNode parent, Tag tag) { this.parent = parent; this.tag = tag; } AnalysisTreeNode(AnalysisTreeNode parent, FieldStatistics fieldStatistics) { this.parent = parent; this.fieldStatistics = fieldStatistics; this.tag = fieldStatistics.getPath().peek(); } public void setStatistics(FieldStatistics fieldStatistics) { this.fieldStatistics = fieldStatistics; } public List<AnalysisTreeNode> getChildren() { return children; } public boolean hasStatistics() { return fieldStatistics != null; } @Override public FieldStatistics getStatistics() { return fieldStatistics; } @Override public TreePath getTreePath() { List<AnalysisTreeNode> list = new ArrayList<AnalysisTreeNode>(); compilePathList(list); return new TreePath(list.toArray()); } @Override public Tag getTag() { return tag; } @Override public Path getPath() { List<AnalysisTreeNode> list = new ArrayList<AnalysisTreeNode>(); compilePathList(list); Path path = new Path(); for (AnalysisTreeNode node : list) { path.push(node.getTag()); } return path; } @Override public boolean setRecordRoot(Path recordRoot) { boolean oldValue = this.recordRoot; this.recordRoot = recordRoot != null && getPath().equals(recordRoot); return this.recordRoot || this.recordRoot != oldValue; } @Override public boolean setUniqueElement(Path uniqueElement) { boolean oldValue = this.uniqueElement; this.uniqueElement = uniqueElement != null && getPath().equals(uniqueElement); return this.uniqueElement != oldValue; } @Override public boolean isRecordRoot() { return recordRoot; } @Override public boolean isUniqueElement() { return uniqueElement; } @Override public Iterable<? extends AnalysisTree.Node> getChildNodes() { return children; } @Override public boolean couldBeRecordRoot() { return fieldStatistics != null && !fieldStatistics.hasValues(); } @Override public boolean couldBeUniqueElement() { if (couldBeRecordRoot()) return false; AnalysisTreeNode walk = parent; while (walk != null) { // ancestor must be record root if (walk.isRecordRoot()) return true; walk = walk.parent; } return false; } @Override public String getVariableName() { if (tag.isAttribute()) throw new RuntimeException("Should never ask an attribute for its variable name"); List<AnalysisTreeNode> path = new ArrayList<AnalysisTreeNode>(); AnalysisTreeNode node = this; while (node != null && !node.isRecordRoot()) { path.add(node); node = node.parent; } Collections.reverse(path); StringBuilder out = new StringBuilder("input."); Iterator<AnalysisTreeNode> nodeWalk = path.iterator(); while (nodeWalk.hasNext()) { - String nodeName = nodeWalk.next().toString(); + String nodeName = nodeWalk.next().tag.toString(); out.append(SourceVariable.Filter.tagToVariable(nodeName)); if (nodeWalk.hasNext()) { out.append('.'); } } return out.toString(); } private void compilePathList(List<AnalysisTreeNode> list) { if (parent != null) { parent.compilePathList(list); } list.add(this); } public void add(AnalysisTreeNode child) { children.add(child); } @Override public TreeNode getChildAt(int index) { return children.get(index); } @Override public int getChildCount() { return children.size(); } @Override public TreeNode getParent() { return parent; } @Override public int getIndex(TreeNode treeNode) { AnalysisTreeNode qNameNode = (AnalysisTreeNode) treeNode; return children.indexOf(qNameNode); } @Override public boolean getAllowsChildren() { return !children.isEmpty(); } @Override public boolean isLeaf() { return children.isEmpty(); } @Override public Enumeration children() { return new Vector<AnalysisTreeNode>(children).elements(); } @Override public int compareTo(AnalysisTree.Node other) { return getVariableName().compareTo(other.getVariableName()); } public String toString() { if (tag == null) { return "?"; } else if (fieldStatistics != null) { return String.format("%s (%d)", tag.toString(), fieldStatistics.getTotal()); } else { return tag.toString(); } } }
true
true
public String getVariableName() { if (tag.isAttribute()) throw new RuntimeException("Should never ask an attribute for its variable name"); List<AnalysisTreeNode> path = new ArrayList<AnalysisTreeNode>(); AnalysisTreeNode node = this; while (node != null && !node.isRecordRoot()) { path.add(node); node = node.parent; } Collections.reverse(path); StringBuilder out = new StringBuilder("input."); Iterator<AnalysisTreeNode> nodeWalk = path.iterator(); while (nodeWalk.hasNext()) { String nodeName = nodeWalk.next().toString(); out.append(SourceVariable.Filter.tagToVariable(nodeName)); if (nodeWalk.hasNext()) { out.append('.'); } } return out.toString(); }
public String getVariableName() { if (tag.isAttribute()) throw new RuntimeException("Should never ask an attribute for its variable name"); List<AnalysisTreeNode> path = new ArrayList<AnalysisTreeNode>(); AnalysisTreeNode node = this; while (node != null && !node.isRecordRoot()) { path.add(node); node = node.parent; } Collections.reverse(path); StringBuilder out = new StringBuilder("input."); Iterator<AnalysisTreeNode> nodeWalk = path.iterator(); while (nodeWalk.hasNext()) { String nodeName = nodeWalk.next().tag.toString(); out.append(SourceVariable.Filter.tagToVariable(nodeName)); if (nodeWalk.hasNext()) { out.append('.'); } } return out.toString(); }
diff --git a/geotools2/geotools-src/proj4j/src/org/geotools/proj4j/Ellipse.java b/geotools2/geotools-src/proj4j/src/org/geotools/proj4j/Ellipse.java index 8bda1fe12..868d6e978 100644 --- a/geotools2/geotools-src/proj4j/src/org/geotools/proj4j/Ellipse.java +++ b/geotools2/geotools-src/proj4j/src/org/geotools/proj4j/Ellipse.java @@ -1,223 +1,223 @@ /* * Ellipse.java * * Created on 19 February 2002, 22:25 */ package org.geotools.proj4j; /** * * @author James Macgill */ public class Ellipse implements Constants { // protected String id; /* ellipse keyword name */ // protected String major; /* a= value */ // protected String ell; /* elliptical parameter */ // protected String name; /* comments */ public double a, /* major axis or radius if es==0 */ e, /* eccentricity */ es, /* e ^ 2 */ ra, /* 1/A */ one_es, /* 1 - e^2 */ rone_es; /* 1/one_es */ /** Creates a new instance of Elips * * @param id ellipse keyword name. * @param major 'a=' value * @param elliptical parameter * @param name description and comments */ public Ellipse(ParamSet params) throws ProjectionException{ System.out.println(params.toString()); setup(params); } private void setup(ParamSet params) throws ProjectionException{ - double b=0.0, e; + double b=0.0; a=es=0d; /* R takes precedence */ if(params.contains("R")){ a = params.getFloatParam("R"); } else{ /* probable elliptical figure */ if(params.contains("ellips")){ String[] defaults = Ellipse.getDefaultsForEllipse(params.getStringParam("ellips")); if(ellips==null){ throw new ProjectionException("Unknown ellipse"); } System.out.println("Ellipse Defaults "+defaults[1]+" "+defaults[2]); params.addParamIfNotSet(defaults[1]); // major axis params.addParamIfNotSet(defaults[2]); // elliptical param } if(params.contains("a")){ a=params.getFloatParam("a"); } if(params.contains("es")){ es=params.getFloatParam("es"); } else if(params.contains("e")){ e = params.getFloatParam("e"); es = e*e; } else if(params.contains("rf")){/* recip flattening */ es=params.getFloatParam("rf"); if(es==0){ throw new ProjectionException("reciprocal flattening (1/f) = 0"); } es = 1f/es; es = es*(2f-es); } else if(params.contains("f")){/* flattening */ es = params.getFloatParam("f"); es = es * (2-es); } else if(params.contains("b")){ /* minor axis */ b = params.getFloatParam("b"); es = 1f-(b*b)/(a*a); } if(b==0){ b=a*Math.sqrt(es); } /* following options turn ellipsoid into equivalent sphere */ if(params.contains("R_A")){/* sphere--area of ellipsoid */ a=1f-es*(SIXTH*es*(RA4+es*RA6)); es=0f; } else if(params.contains("R_V")){/* sphere--vol. of ellipsoid */ a=1f-es*(SIXTH*es*(RV4+es*RV6)); es=0f; } else if(params.contains("R_a")){/* sphere--arithmetic mean */ a=0.5f*(a+b); es=0; } else if(params.contains("R_g")){/* sphere--geometric mean */ a=Math.sqrt(a*b); es=0; } else if(params.contains("R_h")){/* sphere--harmonic mean */ a=2f*a*b/(a+b); es=0; } else if(params.contains("R_lat_a")){/* sphere--arith. */ double tmp1 = Math.sin(params.getFloatParam("R_lat_a")); if(Math.abs(tmp1)>HALFPI){ throw new ProjectionException("|radius reference latitude| > 90"); } tmp1 =1f-es*tmp1*tmp1; a = 0.5f*(1f-es*tmp1)/tmp1*Math.sqrt(tmp1); es=0; } else if(params.contains("R_lat_g")){ /* or geom. mean at latitude */ double tmp2; tmp2 = Math.sin(params.getFloatParam("R_lat_g")); if(Math.abs(tmp2)>HALFPI){ throw new ProjectionException("|radius reference latitude| > 90"); } tmp2 =1f-es*tmp2*tmp2; a=Math.sqrt(1f-es)/tmp2; es=0; } //should probably removed added params } if(es<0){ throw new ProjectionException("squared eccentricity < 0"); } if(a<=0){ throw new ProjectionException("major axis or radius = 0 or not given"); } e=Math.sqrt(es); ra=1f/a; one_es=1f-es; if(one_es==0){ throw new ProjectionException("effective eccentricity = 1"); } rone_es = 1f/one_es; System.out.println(params.toString()); } /** * Retreve standard predefined ellipse by keyword id. * @param id keyword id of ellips to retrive, matching is case insensitive * @return An Ellips from the standard list or <code>null</code> if no match is found */ public static String[] getDefaultsForEllipse(String id){ for(int i=0;i<ellips.length;i++){ if(id.equalsIgnoreCase(ellips[i][0])){ return ellips[i]; } } return null; } /** Getter for property a. * @return Value of property a. */ public double getA() { return a; } /** Getter for property e. * @return Value of property e. */ public double getE() { return e; } /** * List of standard ellips defenitions, individual ellips from this list can be retreved by calling {@link #getEllips}. */ static final String[][] ellips={ // id major elliptical name/comments new String[] {"MERIT", "a=6378137.0", "rf=298.257", "MERIT 1983"}, new String[] {"SGS85", "a=6378136.0", "rf=298.257", "Soviet Geodetic System 85"}, new String[] {"GRS80", "a=6378137.0", "rf=298.257222101", "GRS 1980(IUGG, 1980)"}, new String[] {"IAU76", "a=6378140.0", "rf=298.257", "IAU 1976"}, new String[] {"airy", "a=6377563.396", "b=6356256.910", "Airy 1830"}, new String[] {"APL4.9", "a=6378137.0.", "rf=298.25", "Appl. Physics. 1965"}, new String[] {"NWL9D", "a=6378145.0.", "rf=298.25", "Naval Weapons Lab., 1965"}, new String[] {"mod_airy", "a=6377340.189", "b=6356034.446", "Modified Airy"}, new String[] {"andrae", "a=6377104.43", "rf=300.0", "Andrae 1876 (Den., Iclnd.)"}, new String[] {"aust_SA", "a=6378160.0", "rf=298.25", "Australian Natl & S. Amer. 1969"}, new String[] {"GRS67", "a=6378160.0", "rf=298.2471674270", "GRS 67(IUGG 1967)"}, new String[] {"bessel", "a=6377397.155", "rf=299.1528128", "Bessel 1841"}, new String[] {"bess_nam", "a=6377483.865", "rf=299.1528128", "Bessel 1841 (Namibia)"}, new String[] {"clrk66", "a=6378206.4", "b=6356583.8", "Clarke 1866"}, new String[] {"clrk80", "a=6378249.145", "rf=293.4663", "Clarke 1880 mod."}, new String[] {"CPM", "a=6375738.7", "rf=334.29", "Comm. des Poids et Mesures 1799"}, new String[] {"delmbr", "a=6376428.", "rf=311.5", "Delambre 1810 (Belgium)"}, new String[] {"engelis", "a=6378136.05", "rf=298.2566", "Engelis 1985"}, new String[] {"evrst30", "a=6377276.345", "rf=300.8017", "Everest 1830"}, new String[] {"evrst48", "a=6377304.063", "rf=300.8017", "Everest 1948"}, new String[] {"evrst56", "a=6377301.243", "rf=300.8017", "Everest 1956"}, new String[] {"evrst69", "a=6377295.664", "rf=300.8017", "Everest 1969"}, new String[] {"evrstSS", "a=6377298.556", "rf=300.8017", "Everest (Sabah & Sarawak)"}, new String[] {"fschr60", "a=6378166.", "rf=298.3", "Fischer (Mercury Datum) 1960"}, new String[] {"fschr60m", "a=6378155.", "rf=298.3", "Modified Fischer 1960"}, new String[] {"fschr68", "a=6378150.", "rf=298.3", "Fischer 1968"}, new String[] {"helmert", "a=6378200.", "rf=298.3", "Helmert 1906"}, new String[] {"hough", "a=6378270.0", "rf=297.", "Hough"}, new String[] {"intl", "a=6378388.0", "rf=297.", "International 1909 (Hayford)"}, new String[] {"krass", "a=6378245.0", "rf=298.3", "Krassovsky, 1942"}, new String[] {"kaula", "a=6378163.", "rf=298.24", "Kaula 1961"}, new String[] {"lerch", "a=6378139.", "rf=298.257", "Lerch 1979"}, new String[] {"mprts", "a=6397300.", "rf=191.", "Maupertius 1738"}, new String[] {"new_intl", "a=6378157.5", "b=6356772.2", "New International 1967"}, new String[] {"plessis", "a=6376523.", "b=6355863.", "Plessis 1817 (France)"}, new String[] {"SEasia", "a=6378155.0", "b=6356773.3205", "Southeast Asia"}, new String[] {"walbeck", "a=6376896.0", "b=6355834.8467", "Walbeck"}, new String[] {"WGS60", "a=6378165.0", "rf=298.3", "WGS 60"}, new String[] {"WGS66", "a=6378145.0", "rf=298.25", "WGS 66"}, new String[] {"WGS72", "a=6378135.0", "rf=298.26", "WGS 72"}, new String[] {"WGS84", "a=6378137.0", "rf=298.257223563", "WGS 84"}, new String[] {"sphere", "a=6370997.0", "b=6370997.0", "Normal Sphere (r=6370997)"} }; }
true
true
private void setup(ParamSet params) throws ProjectionException{ double b=0.0, e; a=es=0d; /* R takes precedence */ if(params.contains("R")){ a = params.getFloatParam("R"); } else{ /* probable elliptical figure */ if(params.contains("ellips")){ String[] defaults = Ellipse.getDefaultsForEllipse(params.getStringParam("ellips")); if(ellips==null){ throw new ProjectionException("Unknown ellipse"); } System.out.println("Ellipse Defaults "+defaults[1]+" "+defaults[2]); params.addParamIfNotSet(defaults[1]); // major axis params.addParamIfNotSet(defaults[2]); // elliptical param } if(params.contains("a")){ a=params.getFloatParam("a"); } if(params.contains("es")){ es=params.getFloatParam("es"); } else if(params.contains("e")){ e = params.getFloatParam("e"); es = e*e; } else if(params.contains("rf")){/* recip flattening */ es=params.getFloatParam("rf"); if(es==0){ throw new ProjectionException("reciprocal flattening (1/f) = 0"); } es = 1f/es; es = es*(2f-es); } else if(params.contains("f")){/* flattening */ es = params.getFloatParam("f"); es = es * (2-es); } else if(params.contains("b")){ /* minor axis */ b = params.getFloatParam("b"); es = 1f-(b*b)/(a*a); } if(b==0){ b=a*Math.sqrt(es); } /* following options turn ellipsoid into equivalent sphere */ if(params.contains("R_A")){/* sphere--area of ellipsoid */ a=1f-es*(SIXTH*es*(RA4+es*RA6)); es=0f; } else if(params.contains("R_V")){/* sphere--vol. of ellipsoid */ a=1f-es*(SIXTH*es*(RV4+es*RV6)); es=0f; } else if(params.contains("R_a")){/* sphere--arithmetic mean */ a=0.5f*(a+b); es=0; } else if(params.contains("R_g")){/* sphere--geometric mean */ a=Math.sqrt(a*b); es=0; } else if(params.contains("R_h")){/* sphere--harmonic mean */ a=2f*a*b/(a+b); es=0; } else if(params.contains("R_lat_a")){/* sphere--arith. */ double tmp1 = Math.sin(params.getFloatParam("R_lat_a")); if(Math.abs(tmp1)>HALFPI){ throw new ProjectionException("|radius reference latitude| > 90"); } tmp1 =1f-es*tmp1*tmp1; a = 0.5f*(1f-es*tmp1)/tmp1*Math.sqrt(tmp1); es=0; } else if(params.contains("R_lat_g")){ /* or geom. mean at latitude */ double tmp2; tmp2 = Math.sin(params.getFloatParam("R_lat_g")); if(Math.abs(tmp2)>HALFPI){ throw new ProjectionException("|radius reference latitude| > 90"); } tmp2 =1f-es*tmp2*tmp2; a=Math.sqrt(1f-es)/tmp2; es=0; } //should probably removed added params } if(es<0){ throw new ProjectionException("squared eccentricity < 0"); } if(a<=0){ throw new ProjectionException("major axis or radius = 0 or not given"); } e=Math.sqrt(es); ra=1f/a; one_es=1f-es; if(one_es==0){ throw new ProjectionException("effective eccentricity = 1"); } rone_es = 1f/one_es; System.out.println(params.toString()); }
private void setup(ParamSet params) throws ProjectionException{ double b=0.0; a=es=0d; /* R takes precedence */ if(params.contains("R")){ a = params.getFloatParam("R"); } else{ /* probable elliptical figure */ if(params.contains("ellips")){ String[] defaults = Ellipse.getDefaultsForEllipse(params.getStringParam("ellips")); if(ellips==null){ throw new ProjectionException("Unknown ellipse"); } System.out.println("Ellipse Defaults "+defaults[1]+" "+defaults[2]); params.addParamIfNotSet(defaults[1]); // major axis params.addParamIfNotSet(defaults[2]); // elliptical param } if(params.contains("a")){ a=params.getFloatParam("a"); } if(params.contains("es")){ es=params.getFloatParam("es"); } else if(params.contains("e")){ e = params.getFloatParam("e"); es = e*e; } else if(params.contains("rf")){/* recip flattening */ es=params.getFloatParam("rf"); if(es==0){ throw new ProjectionException("reciprocal flattening (1/f) = 0"); } es = 1f/es; es = es*(2f-es); } else if(params.contains("f")){/* flattening */ es = params.getFloatParam("f"); es = es * (2-es); } else if(params.contains("b")){ /* minor axis */ b = params.getFloatParam("b"); es = 1f-(b*b)/(a*a); } if(b==0){ b=a*Math.sqrt(es); } /* following options turn ellipsoid into equivalent sphere */ if(params.contains("R_A")){/* sphere--area of ellipsoid */ a=1f-es*(SIXTH*es*(RA4+es*RA6)); es=0f; } else if(params.contains("R_V")){/* sphere--vol. of ellipsoid */ a=1f-es*(SIXTH*es*(RV4+es*RV6)); es=0f; } else if(params.contains("R_a")){/* sphere--arithmetic mean */ a=0.5f*(a+b); es=0; } else if(params.contains("R_g")){/* sphere--geometric mean */ a=Math.sqrt(a*b); es=0; } else if(params.contains("R_h")){/* sphere--harmonic mean */ a=2f*a*b/(a+b); es=0; } else if(params.contains("R_lat_a")){/* sphere--arith. */ double tmp1 = Math.sin(params.getFloatParam("R_lat_a")); if(Math.abs(tmp1)>HALFPI){ throw new ProjectionException("|radius reference latitude| > 90"); } tmp1 =1f-es*tmp1*tmp1; a = 0.5f*(1f-es*tmp1)/tmp1*Math.sqrt(tmp1); es=0; } else if(params.contains("R_lat_g")){ /* or geom. mean at latitude */ double tmp2; tmp2 = Math.sin(params.getFloatParam("R_lat_g")); if(Math.abs(tmp2)>HALFPI){ throw new ProjectionException("|radius reference latitude| > 90"); } tmp2 =1f-es*tmp2*tmp2; a=Math.sqrt(1f-es)/tmp2; es=0; } //should probably removed added params } if(es<0){ throw new ProjectionException("squared eccentricity < 0"); } if(a<=0){ throw new ProjectionException("major axis or radius = 0 or not given"); } e=Math.sqrt(es); ra=1f/a; one_es=1f-es; if(one_es==0){ throw new ProjectionException("effective eccentricity = 1"); } rone_es = 1f/one_es; System.out.println(params.toString()); }
diff --git a/src/test/java/org/apache/hadoop/hbase/util/TestMergeTool.java b/src/test/java/org/apache/hadoop/hbase/util/TestMergeTool.java index cf6ad9a25..ccd181424 100644 --- a/src/test/java/org/apache/hadoop/hbase/util/TestMergeTool.java +++ b/src/test/java/org/apache/hadoop/hbase/util/TestMergeTool.java @@ -1,285 +1,286 @@ /** * Copyright 2008 The Apache Software Foundation * * 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.hadoop.hbase.util; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.HBaseTestCase; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.HRegionInfo; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.regionserver.wal.HLog; import org.apache.hadoop.hbase.regionserver.HRegion; import org.apache.hadoop.hbase.regionserver.InternalScanner; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.apache.hadoop.util.ToolRunner; /** Test stand alone merge tool that can merge arbitrary regions */ public class TestMergeTool extends HBaseTestCase { static final Log LOG = LogFactory.getLog(TestMergeTool.class); // static final byte [] COLUMN_NAME = Bytes.toBytes("contents:"); static final byte [] FAMILY = Bytes.toBytes("contents"); static final byte [] QUALIFIER = Bytes.toBytes("dc"); private final HRegionInfo[] sourceRegions = new HRegionInfo[5]; private final HRegion[] regions = new HRegion[5]; private HTableDescriptor desc; private byte [][][] rows; private MiniDFSCluster dfsCluster = null; @Override public void setUp() throws Exception { // Set the timeout down else this test will take a while to complete. this.conf.setLong("hbase.zookeeper.recoverable.waittime", 1000); this.conf.set("hbase.hstore.compactionThreshold", "2"); // Create table description this.desc = new HTableDescriptor("TestMergeTool"); this.desc.addFamily(new HColumnDescriptor(FAMILY)); /* * Create the HRegionInfos for the regions. */ // Region 0 will contain the key range [row_0200,row_0300) sourceRegions[0] = new HRegionInfo(this.desc.getName(), Bytes.toBytes("row_0200"), Bytes.toBytes("row_0300")); // Region 1 will contain the key range [row_0250,row_0400) and overlaps // with Region 0 sourceRegions[1] = new HRegionInfo(this.desc.getName(), Bytes.toBytes("row_0250"), Bytes.toBytes("row_0400")); // Region 2 will contain the key range [row_0100,row_0200) and is adjacent // to Region 0 or the region resulting from the merge of Regions 0 and 1 sourceRegions[2] = new HRegionInfo(this.desc.getName(), Bytes.toBytes("row_0100"), Bytes.toBytes("row_0200")); // Region 3 will contain the key range [row_0500,row_0600) and is not // adjacent to any of Regions 0, 1, 2 or the merged result of any or all // of those regions sourceRegions[3] = new HRegionInfo(this.desc.getName(), Bytes.toBytes("row_0500"), Bytes.toBytes("row_0600")); // Region 4 will have empty start and end keys and overlaps all regions. sourceRegions[4] = new HRegionInfo(this.desc.getName(), HConstants.EMPTY_BYTE_ARRAY, HConstants.EMPTY_BYTE_ARRAY); /* * Now create some row keys */ this.rows = new byte [5][][]; this.rows[0] = Bytes.toByteArrays(new String[] { "row_0210", "row_0280" }); this.rows[1] = Bytes.toByteArrays(new String[] { "row_0260", "row_0350", "row_035" }); this.rows[2] = Bytes.toByteArrays(new String[] { "row_0110", "row_0175", "row_0175", "row_0175"}); this.rows[3] = Bytes.toByteArrays(new String[] { "row_0525", "row_0560", "row_0560", "row_0560", "row_0560"}); this.rows[4] = Bytes.toByteArrays(new String[] { "row_0050", "row_1000", "row_1000", "row_1000", "row_1000", "row_1000" }); // Start up dfs this.dfsCluster = new MiniDFSCluster(conf, 2, true, (String[])null); this.fs = this.dfsCluster.getFileSystem(); System.out.println("fs=" + this.fs); this.conf.set("fs.defaultFS", fs.getUri().toString()); Path parentdir = fs.getHomeDirectory(); conf.set(HConstants.HBASE_DIR, parentdir.toString()); fs.mkdirs(parentdir); FSUtils.setVersion(fs, parentdir); // Note: we must call super.setUp after starting the mini cluster or // we will end up with a local file system super.setUp(); try { // Create root and meta regions createRootAndMetaRegions(); + FSUtils.createTableDescriptor(this.fs, this.testDir, this.desc); /* * Create the regions we will merge */ for (int i = 0; i < sourceRegions.length; i++) { regions[i] = HRegion.createHRegion(this.sourceRegions[i], this.testDir, this.conf, this.desc); /* * Insert data */ for (int j = 0; j < rows[i].length; j++) { byte [] row = rows[i][j]; Put put = new Put(row); put.add(FAMILY, QUALIFIER, row); regions[i].put(put); } HRegion.addRegionToMETA(meta, regions[i]); } // Close root and meta regions closeRootAndMeta(); } catch (Exception e) { shutdownDfs(dfsCluster); throw e; } } @Override public void tearDown() throws Exception { super.tearDown(); shutdownDfs(dfsCluster); } /* * @param msg Message that describes this merge * @param regionName1 * @param regionName2 * @param log Log to use merging. * @param upperbound Verifying, how high up in this.rows to go. * @return Merged region. * @throws Exception */ private HRegion mergeAndVerify(final String msg, final String regionName1, final String regionName2, final HLog log, final int upperbound) throws Exception { Merge merger = new Merge(this.conf); LOG.info(msg); System.out.println("fs2=" + this.conf.get("fs.defaultFS")); int errCode = ToolRunner.run(this.conf, merger, new String[] {this.desc.getNameAsString(), regionName1, regionName2} ); assertTrue("'" + msg + "' failed", errCode == 0); HRegionInfo mergedInfo = merger.getMergedHRegionInfo(); // Now verify that we can read all the rows from regions 0, 1 // in the new merged region. HRegion merged = HRegion.openHRegion(mergedInfo, this.desc, log, this.conf); verifyMerge(merged, upperbound); merged.close(); LOG.info("Verified " + msg); return merged; } private void verifyMerge(final HRegion merged, final int upperbound) throws IOException { //Test Scan scan = new Scan(); scan.addFamily(FAMILY); InternalScanner scanner = merged.getScanner(scan); try { List<KeyValue> testRes = null; while (true) { testRes = new ArrayList<KeyValue>(); boolean hasNext = scanner.next(testRes); if (!hasNext) { break; } } } finally { scanner.close(); } //!Test for (int i = 0; i < upperbound; i++) { for (int j = 0; j < rows[i].length; j++) { Get get = new Get(rows[i][j]); get.addFamily(FAMILY); Result result = merged.get(get, null); assertEquals(1, result.size()); byte [] bytes = result.sorted()[0].getValue(); assertNotNull(Bytes.toStringBinary(rows[i][j]), bytes); assertTrue(Bytes.equals(bytes, rows[i][j])); } } } /** * Test merge tool. * @throws Exception */ public void testMergeTool() throws Exception { // First verify we can read the rows from the source regions and that they // contain the right data. for (int i = 0; i < regions.length; i++) { for (int j = 0; j < rows[i].length; j++) { Get get = new Get(rows[i][j]); get.addFamily(FAMILY); Result result = regions[i].get(get, null); byte [] bytes = result.sorted()[0].getValue(); assertNotNull(bytes); assertTrue(Bytes.equals(bytes, rows[i][j])); } // Close the region and delete the log regions[i].close(); regions[i].getLog().closeAndDelete(); } // Create a log that we can reuse when we need to open regions Path logPath = new Path("/tmp", HConstants.HREGION_LOGDIR_NAME + "_" + System.currentTimeMillis()); LOG.info("Creating log " + logPath.toString()); Path oldLogDir = new Path("/tmp", HConstants.HREGION_OLDLOGDIR_NAME); HLog log = new HLog(this.fs, logPath, oldLogDir, this.conf); try { // Merge Region 0 and Region 1 HRegion merged = mergeAndVerify("merging regions 0 and 1", this.sourceRegions[0].getRegionNameAsString(), this.sourceRegions[1].getRegionNameAsString(), log, 2); // Merge the result of merging regions 0 and 1 with region 2 merged = mergeAndVerify("merging regions 0+1 and 2", merged.getRegionInfo().getRegionNameAsString(), this.sourceRegions[2].getRegionNameAsString(), log, 3); // Merge the result of merging regions 0, 1 and 2 with region 3 merged = mergeAndVerify("merging regions 0+1+2 and 3", merged.getRegionInfo().getRegionNameAsString(), this.sourceRegions[3].getRegionNameAsString(), log, 4); // Merge the result of merging regions 0, 1, 2 and 3 with region 4 merged = mergeAndVerify("merging regions 0+1+2+3 and 4", merged.getRegionInfo().getRegionNameAsString(), this.sourceRegions[4].getRegionNameAsString(), log, rows.length); } finally { log.closeAndDelete(); } } }
true
true
public void setUp() throws Exception { // Set the timeout down else this test will take a while to complete. this.conf.setLong("hbase.zookeeper.recoverable.waittime", 1000); this.conf.set("hbase.hstore.compactionThreshold", "2"); // Create table description this.desc = new HTableDescriptor("TestMergeTool"); this.desc.addFamily(new HColumnDescriptor(FAMILY)); /* * Create the HRegionInfos for the regions. */ // Region 0 will contain the key range [row_0200,row_0300) sourceRegions[0] = new HRegionInfo(this.desc.getName(), Bytes.toBytes("row_0200"), Bytes.toBytes("row_0300")); // Region 1 will contain the key range [row_0250,row_0400) and overlaps // with Region 0 sourceRegions[1] = new HRegionInfo(this.desc.getName(), Bytes.toBytes("row_0250"), Bytes.toBytes("row_0400")); // Region 2 will contain the key range [row_0100,row_0200) and is adjacent // to Region 0 or the region resulting from the merge of Regions 0 and 1 sourceRegions[2] = new HRegionInfo(this.desc.getName(), Bytes.toBytes("row_0100"), Bytes.toBytes("row_0200")); // Region 3 will contain the key range [row_0500,row_0600) and is not // adjacent to any of Regions 0, 1, 2 or the merged result of any or all // of those regions sourceRegions[3] = new HRegionInfo(this.desc.getName(), Bytes.toBytes("row_0500"), Bytes.toBytes("row_0600")); // Region 4 will have empty start and end keys and overlaps all regions. sourceRegions[4] = new HRegionInfo(this.desc.getName(), HConstants.EMPTY_BYTE_ARRAY, HConstants.EMPTY_BYTE_ARRAY); /* * Now create some row keys */ this.rows = new byte [5][][]; this.rows[0] = Bytes.toByteArrays(new String[] { "row_0210", "row_0280" }); this.rows[1] = Bytes.toByteArrays(new String[] { "row_0260", "row_0350", "row_035" }); this.rows[2] = Bytes.toByteArrays(new String[] { "row_0110", "row_0175", "row_0175", "row_0175"}); this.rows[3] = Bytes.toByteArrays(new String[] { "row_0525", "row_0560", "row_0560", "row_0560", "row_0560"}); this.rows[4] = Bytes.toByteArrays(new String[] { "row_0050", "row_1000", "row_1000", "row_1000", "row_1000", "row_1000" }); // Start up dfs this.dfsCluster = new MiniDFSCluster(conf, 2, true, (String[])null); this.fs = this.dfsCluster.getFileSystem(); System.out.println("fs=" + this.fs); this.conf.set("fs.defaultFS", fs.getUri().toString()); Path parentdir = fs.getHomeDirectory(); conf.set(HConstants.HBASE_DIR, parentdir.toString()); fs.mkdirs(parentdir); FSUtils.setVersion(fs, parentdir); // Note: we must call super.setUp after starting the mini cluster or // we will end up with a local file system super.setUp(); try { // Create root and meta regions createRootAndMetaRegions(); /* * Create the regions we will merge */ for (int i = 0; i < sourceRegions.length; i++) { regions[i] = HRegion.createHRegion(this.sourceRegions[i], this.testDir, this.conf, this.desc); /* * Insert data */ for (int j = 0; j < rows[i].length; j++) { byte [] row = rows[i][j]; Put put = new Put(row); put.add(FAMILY, QUALIFIER, row); regions[i].put(put); } HRegion.addRegionToMETA(meta, regions[i]); } // Close root and meta regions closeRootAndMeta(); } catch (Exception e) { shutdownDfs(dfsCluster); throw e; } }
public void setUp() throws Exception { // Set the timeout down else this test will take a while to complete. this.conf.setLong("hbase.zookeeper.recoverable.waittime", 1000); this.conf.set("hbase.hstore.compactionThreshold", "2"); // Create table description this.desc = new HTableDescriptor("TestMergeTool"); this.desc.addFamily(new HColumnDescriptor(FAMILY)); /* * Create the HRegionInfos for the regions. */ // Region 0 will contain the key range [row_0200,row_0300) sourceRegions[0] = new HRegionInfo(this.desc.getName(), Bytes.toBytes("row_0200"), Bytes.toBytes("row_0300")); // Region 1 will contain the key range [row_0250,row_0400) and overlaps // with Region 0 sourceRegions[1] = new HRegionInfo(this.desc.getName(), Bytes.toBytes("row_0250"), Bytes.toBytes("row_0400")); // Region 2 will contain the key range [row_0100,row_0200) and is adjacent // to Region 0 or the region resulting from the merge of Regions 0 and 1 sourceRegions[2] = new HRegionInfo(this.desc.getName(), Bytes.toBytes("row_0100"), Bytes.toBytes("row_0200")); // Region 3 will contain the key range [row_0500,row_0600) and is not // adjacent to any of Regions 0, 1, 2 or the merged result of any or all // of those regions sourceRegions[3] = new HRegionInfo(this.desc.getName(), Bytes.toBytes("row_0500"), Bytes.toBytes("row_0600")); // Region 4 will have empty start and end keys and overlaps all regions. sourceRegions[4] = new HRegionInfo(this.desc.getName(), HConstants.EMPTY_BYTE_ARRAY, HConstants.EMPTY_BYTE_ARRAY); /* * Now create some row keys */ this.rows = new byte [5][][]; this.rows[0] = Bytes.toByteArrays(new String[] { "row_0210", "row_0280" }); this.rows[1] = Bytes.toByteArrays(new String[] { "row_0260", "row_0350", "row_035" }); this.rows[2] = Bytes.toByteArrays(new String[] { "row_0110", "row_0175", "row_0175", "row_0175"}); this.rows[3] = Bytes.toByteArrays(new String[] { "row_0525", "row_0560", "row_0560", "row_0560", "row_0560"}); this.rows[4] = Bytes.toByteArrays(new String[] { "row_0050", "row_1000", "row_1000", "row_1000", "row_1000", "row_1000" }); // Start up dfs this.dfsCluster = new MiniDFSCluster(conf, 2, true, (String[])null); this.fs = this.dfsCluster.getFileSystem(); System.out.println("fs=" + this.fs); this.conf.set("fs.defaultFS", fs.getUri().toString()); Path parentdir = fs.getHomeDirectory(); conf.set(HConstants.HBASE_DIR, parentdir.toString()); fs.mkdirs(parentdir); FSUtils.setVersion(fs, parentdir); // Note: we must call super.setUp after starting the mini cluster or // we will end up with a local file system super.setUp(); try { // Create root and meta regions createRootAndMetaRegions(); FSUtils.createTableDescriptor(this.fs, this.testDir, this.desc); /* * Create the regions we will merge */ for (int i = 0; i < sourceRegions.length; i++) { regions[i] = HRegion.createHRegion(this.sourceRegions[i], this.testDir, this.conf, this.desc); /* * Insert data */ for (int j = 0; j < rows[i].length; j++) { byte [] row = rows[i][j]; Put put = new Put(row); put.add(FAMILY, QUALIFIER, row); regions[i].put(put); } HRegion.addRegionToMETA(meta, regions[i]); } // Close root and meta regions closeRootAndMeta(); } catch (Exception e) { shutdownDfs(dfsCluster); throw e; } }
diff --git a/controllers/src/main/java/org/idiginfo/docsvc/controller/harvest/LoadDocuments.java b/controllers/src/main/java/org/idiginfo/docsvc/controller/harvest/LoadDocuments.java index 0f7bed9..1802484 100644 --- a/controllers/src/main/java/org/idiginfo/docsvc/controller/harvest/LoadDocuments.java +++ b/controllers/src/main/java/org/idiginfo/docsvc/controller/harvest/LoadDocuments.java @@ -1,87 +1,91 @@ package org.idiginfo.docsvc.controller.harvest; import java.io.StringWriter; import java.util.Iterator; import java.util.List; import java.util.Vector; import org.idiginfo.docsvc.jpa.citagora.CitagoraFactoryImpl; import org.idiginfo.docsvc.model.apisvc.Annotation; import org.idiginfo.docsvc.model.apisvc.Document; import org.idiginfo.docsvc.model.apisvc.Documents; import org.idiginfo.docsvc.model.citagora.CitagoraFactory; import org.idiginfo.docsvc.model.citagora.CitagoraObject; import org.idiginfo.docsvc.model.citagora.Container; import org.idiginfo.docsvc.model.citagora.Reference; import org.idiginfo.docsvc.model.citagora.UriObject; import org.idiginfo.docsvc.model.mapping.MapSvcapiToCitagora; import org.idiginfo.docsvc.view.rdf.citagora.MapCitagoraObject; import com.hp.hpl.jena.rdf.model.Model; public class LoadDocuments { CitagoraFactoryImpl factory = new CitagoraFactoryImpl(); MapSvcapiToCitagora documentMapper = new MapSvcapiToCitagora(); List<Container> load(Container containerFields, Documents documents) { List<Container> containers = new Vector<Container>(); if (documents == null) return null; for (Document document : documents) { Container container = load(containerFields, document); containers.add(container); } return containers; } Container load(Container containerFields, Document document) { boolean localTransaction = false; String doi = document.getDoi(); + if (doi!=null && !doi.startsWith("10.")){ + //not a valid doi + doi = null; + } if (doi != null) { Reference ref = factory.findReferenceByDoi(doi); if (ref != null) { System.out.println(" doi: " + doi + " already present"); List<Container> containers = ref.getContainers(); if (containers != null && containers.size() > 0) return containers.get(0); // there is already a document return null; // no container } } String uri = document.getUri(); if (uri != null) { CitagoraObject obj = factory.findCitagoraObjectByURI(uri); if (obj != null) { System.out.println(" uri: " + uri + " already present"); return null; } } if (!factory.isTransactionActive()) { factory.openTransaction(); localTransaction = true; } Container container = documentMapper.createContainer(containerFields, document); System.out.println(" uri: " + (doi!=null?doi:uri) + " created"); if (localTransaction) { factory.commitTransaction(); } return container; } public String writeCitagoraRdf(UriObject document, String version, int level) { MapCitagoraObject mapper = new MapCitagoraObject(); mapper.add(document, level); Model model = mapper.getModel(); StringWriter out = new StringWriter(); model.write(out, version); return out.toString(); } public CitagoraFactory getFactory() { return factory; } }
true
true
Container load(Container containerFields, Document document) { boolean localTransaction = false; String doi = document.getDoi(); if (doi != null) { Reference ref = factory.findReferenceByDoi(doi); if (ref != null) { System.out.println(" doi: " + doi + " already present"); List<Container> containers = ref.getContainers(); if (containers != null && containers.size() > 0) return containers.get(0); // there is already a document return null; // no container } } String uri = document.getUri(); if (uri != null) { CitagoraObject obj = factory.findCitagoraObjectByURI(uri); if (obj != null) { System.out.println(" uri: " + uri + " already present"); return null; } } if (!factory.isTransactionActive()) { factory.openTransaction(); localTransaction = true; } Container container = documentMapper.createContainer(containerFields, document); System.out.println(" uri: " + (doi!=null?doi:uri) + " created"); if (localTransaction) { factory.commitTransaction(); } return container; }
Container load(Container containerFields, Document document) { boolean localTransaction = false; String doi = document.getDoi(); if (doi!=null && !doi.startsWith("10.")){ //not a valid doi doi = null; } if (doi != null) { Reference ref = factory.findReferenceByDoi(doi); if (ref != null) { System.out.println(" doi: " + doi + " already present"); List<Container> containers = ref.getContainers(); if (containers != null && containers.size() > 0) return containers.get(0); // there is already a document return null; // no container } } String uri = document.getUri(); if (uri != null) { CitagoraObject obj = factory.findCitagoraObjectByURI(uri); if (obj != null) { System.out.println(" uri: " + uri + " already present"); return null; } } if (!factory.isTransactionActive()) { factory.openTransaction(); localTransaction = true; } Container container = documentMapper.createContainer(containerFields, document); System.out.println(" uri: " + (doi!=null?doi:uri) + " created"); if (localTransaction) { factory.commitTransaction(); } return container; }
diff --git a/src/main/java/de/cismet/cids/custom/objecteditors/wunda_blau/Alb_picturePanel.java b/src/main/java/de/cismet/cids/custom/objecteditors/wunda_blau/Alb_picturePanel.java index ed5ca74e..3d5ab0ad 100644 --- a/src/main/java/de/cismet/cids/custom/objecteditors/wunda_blau/Alb_picturePanel.java +++ b/src/main/java/de/cismet/cids/custom/objecteditors/wunda_blau/Alb_picturePanel.java @@ -1,1041 +1,1041 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * Alb_picturePanel.java * * Created on 11.12.2009, 14:49:40 */ package de.cismet.cids.custom.objecteditors.wunda_blau; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.Point; import de.cismet.cids.custom.objectrenderer.utils.BaulastenPictureFinder; import de.cismet.cids.custom.objectrenderer.utils.CidsBeanSupport; import de.cismet.cids.custom.objectrenderer.utils.MD5Calculator; import de.cismet.cids.dynamics.CidsBean; import de.cismet.cismap.commons.features.Feature; import de.cismet.cismap.commons.features.FeatureCollectionEvent; import de.cismet.cismap.commons.features.PureNewFeature; import de.cismet.cismap.commons.gui.piccolo.eventlistener.MessenGeometryListener; import de.cismet.tools.BrowserLauncher; import de.cismet.tools.CismetThreadPool; import de.cismet.tools.StaticDecimalTools; import de.cismet.tools.collections.TypeSafeCollections; import de.cismet.tools.gui.MultiPagePictureReader; import java.awt.Color; import java.awt.EventQueue; import java.awt.image.BufferedImage; import java.io.File; import java.util.Collection; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JOptionPane; import javax.swing.ListModel; import javax.swing.SwingWorker; /** * * @author srichter */ public class Alb_picturePanel extends javax.swing.JPanel { // <editor-fold defaultstate="collapsed" desc="Static Variables"> private static final String[] MD5_PROPERTY_NAMES = new String[]{"lageplan_md5", "textblatt_md5"}; private static final int LAGEPLAN_DOCUMENT = 0; private static final int TEXTBLATT_DOCUMENT = 1; private static final int NO_SELECTION = -1; private static final Color KALIBRIERUNG_VORHANDEN = new Color(120,255,190); // private static final ListModel LADEN_MODEL = new DefaultListModel() { { add(0, "Wird geladen..."); } }; private static final ListModel FEHLER_MODEL = new DefaultListModel() { { add(0, "Lesefehler."); } }; // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Instance Variables"> private static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(Alb_picturePanel.class); private MultiPagePictureReader pictureReader; private CidsBean cidsBean; private File[] documentFiles; private JButton[] documentButtons; // private File planFile; // private File textFile; private JButton currentSelectedButton; private static boolean alreadyWarnedAboutPermissionProblem = false; private final MessenFeatureCollectionListener messenListener; // private volatile int currentDocument = NO_SELECTION; private volatile int currentPage = NO_SELECTION; private final String[] expectedMD5Values; // private String planFileMD5 = ""; // private String textFileMD5 = ""; private String currentActualDocumentMD5 = ""; private Map<Integer, Geometry> pageGeometries; // </editor-fold> /** Creates new form Alb_picturePanel */ public Alb_picturePanel() { this.pageGeometries = TypeSafeCollections.newHashMap(); this.documentFiles = new File[2]; this.documentButtons = new JButton[documentFiles.length]; initComponents(); documentButtons[LAGEPLAN_DOCUMENT] = btnPlan; documentButtons[TEXTBLATT_DOCUMENT] = btnTextblatt; messenListener = new MessenFeatureCollectionListener(); measureComponent.getFeatureCollection().addFeatureCollectionListener(messenListener); this.expectedMD5Values = new String[2]; } // <editor-fold defaultstate="collapsed" desc="Public Methods"> public void zoomToFeatureCollection() { measureComponent.zoomToFeatureCollection(); } /** * @return the cidsBean */ public CidsBean getCidsBean() { return cidsBean; } /** * @param cidsBean the cidsBean to set */ public void setCidsBean(CidsBean cidsBean) { this.cidsBean = cidsBean; if (cidsBean != null) { for (int i = 0; i < MD5_PROPERTY_NAMES.length; ++i) { Object propValObj = cidsBean.getProperty(MD5_PROPERTY_NAMES[i]); if (propValObj instanceof String) { expectedMD5Values[i] = (String) propValObj; } else { expectedMD5Values[i] = null; } } } setCurrentDocumentNull(); CismetThreadPool.execute(new FileSearchWorker()); } // @Override // public void removeNotify() { // //TODO: BUG! wird durchs Fenstermanagement auch umschalten // //auf Vollbild aufgerufen! // super.removeNotify(); // closeReader(); // } // </editor-fold> /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; btnGrpDocs = new javax.swing.ButtonGroup(); buttonGrpMode = new javax.swing.ButtonGroup(); panPicNavigation = new javax.swing.JPanel(); spDocuments = new de.cismet.tools.gui.RoundedPanel(); btnPlan = new javax.swing.JButton(); btnTextblatt = new javax.swing.JButton(); semiRoundedPanel2 = new de.cismet.tools.gui.SemiRoundedPanel(); jLabel1 = new javax.swing.JLabel(); rpSeiten = new de.cismet.tools.gui.RoundedPanel(); scpPictureList = new javax.swing.JScrollPane(); lstPictures = new javax.swing.JList(); semiRoundedPanel3 = new de.cismet.tools.gui.SemiRoundedPanel(); jLabel2 = new javax.swing.JLabel(); rpMessdaten = new de.cismet.tools.gui.RoundedPanel(); lblArea = new javax.swing.JLabel(); lblDistance = new javax.swing.JLabel(); lblTxtDistance = new javax.swing.JLabel(); lblTxtArea = new javax.swing.JLabel(); semiRoundedPanel5 = new de.cismet.tools.gui.SemiRoundedPanel(); jLabel6 = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); rpControls = new de.cismet.tools.gui.RoundedPanel(); togPan = new javax.swing.JToggleButton(); togZoom = new javax.swing.JToggleButton(); togMessenLine = new javax.swing.JToggleButton(); togMessenPoly = new javax.swing.JToggleButton(); togCalibrate = new javax.swing.JToggleButton(); btnHome = new javax.swing.JButton(); semiRoundedPanel4 = new de.cismet.tools.gui.SemiRoundedPanel(); jLabel3 = new javax.swing.JLabel(); btnPrint = new javax.swing.JButton(); panCenter = new javax.swing.JPanel(); measureComponent = new de.cismet.cismap.commons.gui.measuring.MeasuringComponent(); semiRoundedPanel1 = new de.cismet.tools.gui.SemiRoundedPanel(); lblCurrentViewTitle = new javax.swing.JLabel(); setOpaque(false); setLayout(new java.awt.BorderLayout()); panPicNavigation.setMinimumSize(new java.awt.Dimension(140, 216)); panPicNavigation.setOpaque(false); panPicNavigation.setPreferredSize(new java.awt.Dimension(140, 216)); panPicNavigation.setLayout(new java.awt.GridBagLayout()); spDocuments.setLayout(new java.awt.GridBagLayout()); btnPlan.setText("Plan"); btnPlan.setToolTipText("Plan"); btnGrpDocs.add(btnPlan); btnPlan.setMaximumSize(new java.awt.Dimension(53, 33)); btnPlan.setMinimumSize(new java.awt.Dimension(53, 33)); btnPlan.setPreferredSize(new java.awt.Dimension(53, 33)); btnPlan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnPlanActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 3, 5); spDocuments.add(btnPlan, gridBagConstraints); btnTextblatt.setText("Textblatt"); btnTextblatt.setToolTipText("Textblatt"); btnGrpDocs.add(btnTextblatt); btnTextblatt.setMaximumSize(new java.awt.Dimension(53, 33)); btnTextblatt.setMinimumSize(new java.awt.Dimension(53, 33)); btnTextblatt.setPreferredSize(new java.awt.Dimension(53, 33)); btnTextblatt.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnTextblattActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(2, 5, 5, 5); spDocuments.add(btnTextblatt, gridBagConstraints); semiRoundedPanel2.setBackground(new java.awt.Color(51, 51, 51)); semiRoundedPanel2.setLayout(new java.awt.FlowLayout()); jLabel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setText("Dokumentauswahl"); semiRoundedPanel2.add(jLabel1); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; spDocuments.add(semiRoundedPanel2, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 5, 7); panPicNavigation.add(spDocuments, gridBagConstraints); scpPictureList.setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 5, 5, 5)); scpPictureList.setMinimumSize(new java.awt.Dimension(100, 150)); scpPictureList.setOpaque(false); scpPictureList.setPreferredSize(new java.awt.Dimension(100, 150)); lstPictures.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); lstPictures.setEnabled(false); lstPictures.setFixedCellWidth(75); lstPictures.addListSelectionListener(new javax.swing.event.ListSelectionListener() { public void valueChanged(javax.swing.event.ListSelectionEvent evt) { lstPicturesValueChanged(evt); } }); scpPictureList.setViewportView(lstPictures); rpSeiten.add(scpPictureList, java.awt.BorderLayout.CENTER); semiRoundedPanel3.setBackground(new java.awt.Color(51, 51, 51)); semiRoundedPanel3.setLayout(new java.awt.FlowLayout()); jLabel2.setForeground(new java.awt.Color(255, 255, 255)); jLabel2.setText("Seitenauswahl"); semiRoundedPanel3.add(jLabel2); rpSeiten.add(semiRoundedPanel3, java.awt.BorderLayout.PAGE_START); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(5, 0, 5, 7); panPicNavigation.add(rpSeiten, gridBagConstraints); rpMessdaten.setLayout(new java.awt.GridBagLayout()); lblArea.setText("-"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(2, 5, 5, 5); rpMessdaten.add(lblArea, gridBagConstraints); lblDistance.setText("-"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(2, 5, 5, 5); rpMessdaten.add(lblDistance, gridBagConstraints); - lblTxtDistance.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N + lblTxtDistance.setFont(new java.awt.Font("Tahoma", 1, 11)); lblTxtDistance.setText("Länge/Umfang:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 3, 5); rpMessdaten.add(lblTxtDistance, gridBagConstraints); lblTxtArea.setFont(new java.awt.Font("Tahoma", 1, 11)); lblTxtArea.setText("Fläche:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 3, 5); rpMessdaten.add(lblTxtArea, gridBagConstraints); semiRoundedPanel5.setBackground(new java.awt.Color(51, 51, 51)); semiRoundedPanel5.setLayout(new java.awt.FlowLayout()); jLabel6.setForeground(new java.awt.Color(255, 255, 255)); jLabel6.setText("Messdaten"); semiRoundedPanel5.add(jLabel6); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; rpMessdaten.add(semiRoundedPanel5, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 7); panPicNavigation.add(rpMessdaten, gridBagConstraints); jPanel1.setOpaque(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.weighty = 1.0; panPicNavigation.add(jPanel1, gridBagConstraints); rpControls.setLayout(new java.awt.GridBagLayout()); buttonGrpMode.add(togPan); togPan.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/pan.gif"))); // NOI18N togPan.setSelected(true); togPan.setText("Verschieben"); togPan.setToolTipText("Verschieben"); togPan.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); togPan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { togPanActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(2, 5, 3, 5); rpControls.add(togPan, gridBagConstraints); buttonGrpMode.add(togZoom); togZoom.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/zoom.gif"))); // NOI18N togZoom.setText("Zoomen"); togZoom.setToolTipText("Zoomen"); togZoom.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); togZoom.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { togZoomActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(2, 5, 3, 5); rpControls.add(togZoom, gridBagConstraints); buttonGrpMode.add(togMessenLine); togMessenLine.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/newLinestring.png"))); // NOI18N togMessenLine.setText("Messlinie"); togMessenLine.setToolTipText("Messen (Linie)"); togMessenLine.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); togMessenLine.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { togMessenLineActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(2, 5, 3, 5); rpControls.add(togMessenLine, gridBagConstraints); buttonGrpMode.add(togMessenPoly); togMessenPoly.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/newPolygon.png"))); // NOI18N togMessenPoly.setText("Messfläche"); togMessenPoly.setToolTipText("Messen (Polygon)"); togMessenPoly.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); togMessenPoly.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { togMessenPolyActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(2, 5, 3, 5); rpControls.add(togMessenPoly, gridBagConstraints); buttonGrpMode.add(togCalibrate); togCalibrate.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/screen.gif"))); // NOI18N togCalibrate.setText("Kalibrieren"); togCalibrate.setToolTipText("Kalibrieren"); togCalibrate.setEnabled(false); togCalibrate.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); togCalibrate.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { togCalibrateActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 6; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(2, 5, 3, 5); rpControls.add(togCalibrate, gridBagConstraints); btnHome.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/home.gif"))); // NOI18N btnHome.setText("Übersicht"); btnHome.setToolTipText("Übersicht"); btnHome.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); btnHome.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnHomeActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(5, 5, 3, 5); rpControls.add(btnHome, gridBagConstraints); semiRoundedPanel4.setBackground(new java.awt.Color(51, 51, 51)); semiRoundedPanel4.setLayout(new java.awt.FlowLayout()); jLabel3.setForeground(new java.awt.Color(255, 255, 255)); jLabel3.setText("Steuerung"); semiRoundedPanel4.add(jLabel3); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; rpControls.add(semiRoundedPanel4, gridBagConstraints); - btnPrint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/frameprint.png"))); // NOI18N - btnPrint.setText("Drucken"); - btnPrint.setToolTipText("Übersicht"); + btnPrint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/folder-image.png"))); // NOI18N + btnPrint.setText("Öffnen"); + btnPrint.setToolTipText("Extern öffnen"); btnPrint.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); btnPrint.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnPrintActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 7; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(2, 5, 5, 5); rpControls.add(btnPrint, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(5, 0, 5, 7); panPicNavigation.add(rpControls, gridBagConstraints); add(panPicNavigation, java.awt.BorderLayout.WEST); panCenter.setOpaque(false); panCenter.setLayout(new java.awt.BorderLayout()); panCenter.add(measureComponent, java.awt.BorderLayout.CENTER); semiRoundedPanel1.setBackground(new java.awt.Color(51, 51, 51)); semiRoundedPanel1.setLayout(new java.awt.FlowLayout()); lblCurrentViewTitle.setForeground(new java.awt.Color(255, 255, 255)); lblCurrentViewTitle.setText("Keine Auswahl"); semiRoundedPanel1.add(lblCurrentViewTitle); panCenter.add(semiRoundedPanel1, java.awt.BorderLayout.NORTH); add(panCenter, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents private void lstPicturesValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_lstPicturesValueChanged if (!evt.getValueIsAdjusting()) { final Object selObj = lstPictures.getSelectedValue(); if (selObj instanceof Integer) { int pageNo = (Integer) selObj; //page -> offset CismetThreadPool.execute(new PictureSelectWorker(pageNo - 1)); } } }//GEN-LAST:event_lstPicturesValueChanged private void btnPlanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPlanActionPerformed loadPlan(); }//GEN-LAST:event_btnPlanActionPerformed private void btnTextblattActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTextblattActionPerformed loadTextBlatt(); }//GEN-LAST:event_btnTextblattActionPerformed private void togPanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_togPanActionPerformed measureComponent.actionPan(); }//GEN-LAST:event_togPanActionPerformed private void togMessenPolyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_togMessenPolyActionPerformed measureComponent.actionMeasurePolygon(); }//GEN-LAST:event_togMessenPolyActionPerformed private void togZoomActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_togZoomActionPerformed measureComponent.actionZoom(); }//GEN-LAST:event_togZoomActionPerformed private void togMessenLineActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_togMessenLineActionPerformed measureComponent.actionMeasureLine(); }//GEN-LAST:event_togMessenLineActionPerformed private void togCalibrateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_togCalibrateActionPerformed if (currentPage != NO_SELECTION) { double distance = askForDistanceValue(); if (distance > 0d) { measureComponent.actionCalibrate(distance); final Geometry documentGeom = measureComponent.getMainDocumentGeometry(); try { registerGeometryForPage(documentGeom, currentDocument, currentPage); } catch (Exception ex) { log.error(ex, ex); } } else { JOptionPane.showMessageDialog(this, "Eingegebene(r) Distanz bzw. Umfang ist kein gültiger Wert oder gleich 0.", "Ungültige Eingabe", JOptionPane.WARNING_MESSAGE); } togPan.setSelected(true); } }//GEN-LAST:event_togCalibrateActionPerformed private void btnHomeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnHomeActionPerformed measureComponent.actionOverview(); }//GEN-LAST:event_btnHomeActionPerformed private void btnPrintActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPrintActionPerformed File current = documentFiles[currentDocument]; try { BrowserLauncher.openURL(current.toURI().toURL().toString()); } catch (Exception ex) { log.error(ex, ex); } }//GEN-LAST:event_btnPrintActionPerformed // <editor-fold defaultstate="collapsed" desc="Private Helper Methods"> private Collection<CidsBean> getPages() { if (cidsBean != null) { Object o = null; if (currentDocument == TEXTBLATT_DOCUMENT) { o = cidsBean.getProperty("textblatt_pages"); } else if (currentDocument == LAGEPLAN_DOCUMENT) { o = cidsBean.getProperty("lageplan_pages"); } if (o instanceof Collection) { return (Collection<CidsBean>) o; } } return null; } private void registerGeometryForPage(Geometry geometry, int documentNo, int pageNo) throws Exception { if (geometry != null && documentNo > NO_SELECTION && pageNo > NO_SELECTION) { Geometry oldVal = pageGeometries.get(pageNo); if (oldVal == null || !oldVal.equals(geometry)) { pageGeometries.put(pageNo, geometry); Collection<CidsBean> pageGeoCollection = getPages(); if (pageGeoCollection != null) { boolean pageFound = false; for (CidsBean pageGeom : pageGeoCollection) { Object pageNumberObj = pageGeom.getProperty("page_number"); if (pageNumberObj instanceof Integer) { if (pageNo == (Integer) pageNumberObj) { pageGeom.setProperty("geometry", geometry); pageFound = true; log.fatal("found: " + pageNo); break; } } } if (!pageFound) { final CidsBean newBean = CidsBeanSupport.createNewCidsBeanFromTableName("ALB_GEO_DOCUMENT_PAGE"); pageGeoCollection.add(newBean); newBean.setProperty("page_number", pageNo); newBean.setProperty("geometry", geometry); } persistBean(); } else { log.error("Empty Page Collection!"); } } } } private void loadPlan() { currentSelectedButton = btnPlan; lblCurrentViewTitle.setText("Lageplan"); currentDocument = LAGEPLAN_DOCUMENT; CismetThreadPool.execute(new PictureReaderWorker(documentFiles[currentDocument])); lstPictures.setEnabled(true); } private void loadTextBlatt() { currentSelectedButton = btnTextblatt; lblCurrentViewTitle.setText("Textblatt"); currentDocument = TEXTBLATT_DOCUMENT; CismetThreadPool.execute(new PictureReaderWorker(documentFiles[currentDocument])); lstPictures.setEnabled(true); } private void setControlsEnabled(boolean enabled) { for (int i = 0; i < documentFiles.length; ++i) { JButton current = documentButtons[i]; current.setEnabled(documentFiles[LAGEPLAN_DOCUMENT] != null && enabled && currentSelectedButton != current); } } private void setCurrentDocumentNull() { currentDocument = NO_SELECTION; currentActualDocumentMD5 = ""; pageGeometries.clear(); setCurrentPageNull(); } private void setCurrentPageNull() { currentPage = NO_SELECTION; } private void closeReader() { if (pictureReader != null) { pictureReader.close(); pictureReader = null; } } private void showPermissionWarning() { if (!alreadyWarnedAboutPermissionProblem) { JOptionPane.showMessageDialog(this, "Kein Schreibrecht", "Kein Schreibrecht für die Klasse. Änderungen werden nicht gespeichert.", JOptionPane.WARNING_MESSAGE); } log.warn("User has no right to save Baulast bean!"); alreadyWarnedAboutPermissionProblem = true; } private void persistBean() throws Exception { if (CidsBeanSupport.checkWritePermission(cidsBean)) { alreadyWarnedAboutPermissionProblem = false; cidsBean.persist(); } else { showPermissionWarning(); } } private double askForDistanceValue() { try { String laenge = JOptionPane.showInputDialog(this, "Bitte Länge bzw. Umfang in Metern eingeben:", "Kalibrierung", JOptionPane.QUESTION_MESSAGE); if (laenge != null) { return Math.abs(Double.parseDouble(laenge.replace(',', '.'))); } } catch (Exception ex) { log.warn(ex, ex); } return 0d; } // </editor-fold> // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.ButtonGroup btnGrpDocs; private javax.swing.JButton btnHome; private javax.swing.JButton btnPlan; private javax.swing.JButton btnPrint; private javax.swing.JButton btnTextblatt; private javax.swing.ButtonGroup buttonGrpMode; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel6; private javax.swing.JPanel jPanel1; private javax.swing.JLabel lblArea; private javax.swing.JLabel lblCurrentViewTitle; private javax.swing.JLabel lblDistance; private javax.swing.JLabel lblTxtArea; private javax.swing.JLabel lblTxtDistance; private javax.swing.JList lstPictures; private de.cismet.cismap.commons.gui.measuring.MeasuringComponent measureComponent; private javax.swing.JPanel panCenter; private javax.swing.JPanel panPicNavigation; private de.cismet.tools.gui.RoundedPanel rpControls; private de.cismet.tools.gui.RoundedPanel rpMessdaten; private de.cismet.tools.gui.RoundedPanel rpSeiten; private javax.swing.JScrollPane scpPictureList; private de.cismet.tools.gui.SemiRoundedPanel semiRoundedPanel1; private de.cismet.tools.gui.SemiRoundedPanel semiRoundedPanel2; private de.cismet.tools.gui.SemiRoundedPanel semiRoundedPanel3; private de.cismet.tools.gui.SemiRoundedPanel semiRoundedPanel4; private de.cismet.tools.gui.SemiRoundedPanel semiRoundedPanel5; private de.cismet.tools.gui.RoundedPanel spDocuments; private javax.swing.JToggleButton togCalibrate; private javax.swing.JToggleButton togMessenLine; private javax.swing.JToggleButton togMessenPoly; private javax.swing.JToggleButton togPan; private javax.swing.JToggleButton togZoom; // End of variables declaration//GEN-END:variables // <editor-fold defaultstate="collapsed" desc="FileSearchWorker"> final class FileSearchWorker extends SwingWorker<File[], Void> { public FileSearchWorker() { setControlsEnabled(false); measureComponent.reset(); togPan.setSelected(true); resetMeasureDataLabels(); } @Override protected File[] doInBackground() throws Exception { final File[] result = new File[documentFiles.length]; final Object blattObj = getCidsBean().getProperty("textblatt"); final Object planObj = getCidsBean().getProperty("lageplan"); log.info("Found blatt " + blattObj); log.info("Found plan " + planObj); if (blattObj != null) { final File searchResult = BaulastenPictureFinder.findTextblattPicture(blattObj.toString()); result[TEXTBLATT_DOCUMENT] = searchResult; log.info("Blatt picture " + result[TEXTBLATT_DOCUMENT]); } if (planObj != null) { final File searchResult = BaulastenPictureFinder.findPlanPicture(planObj.toString()); result[LAGEPLAN_DOCUMENT] = searchResult; log.info("Plan picture " + result[LAGEPLAN_DOCUMENT]); } return result; } @Override protected void done() { try { final File[] result = get(); for (int i = 0; i < result.length; ++i) { documentFiles[i] = result[i]; } } catch (InterruptedException ex) { log.warn(ex, ex); } catch (ExecutionException ex) { log.error(ex, ex); } finally { setControlsEnabled(true); for (int i = 0; i < documentFiles.length; ++i) { documentButtons[i].setEnabled(documentFiles[i] != null); } if (btnTextblatt.isEnabled()) { loadTextBlatt(); } else if (btnPlan.isEnabled()) { loadPlan(); } else { lstPictures.setModel(new DefaultListModel()); measureComponent.removeAllFeatures(); } } } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="PictureReaderWorker"> final class PictureReaderWorker extends SwingWorker<ListModel, Void> { public PictureReaderWorker(File pictureFile) { this.pictureFile = pictureFile; log.debug("prepare picture reader for file " + this.pictureFile); lstPictures.setModel(LADEN_MODEL); measureComponent.removeAllFeatures(); setControlsEnabled(false); } private final File pictureFile; private boolean md5OK = false; private void updateMD5() throws Exception { expectedMD5Values[currentDocument] = currentActualDocumentMD5; cidsBean.setProperty(MD5_PROPERTY_NAMES[currentDocument], currentActualDocumentMD5); log.debug("saving md5 value " + currentActualDocumentMD5); persistBean(); } @Override protected ListModel doInBackground() throws Exception { final DefaultListModel model = new DefaultListModel(); currentActualDocumentMD5 = MD5Calculator.generateMD5(pictureFile); if (currentDocument != NO_SELECTION && currentDocument < expectedMD5Values.length) { final String expectedMD5 = expectedMD5Values[currentDocument]; if (expectedMD5 != null && expectedMD5.length() > 0) { if (expectedMD5.equals(currentActualDocumentMD5)) { md5OK = true; } else { md5OK = false; log.warn("MD5 fail. Expected: " + expectedMD5 + ". Found: " + currentActualDocumentMD5); } } else { md5OK = true; updateMD5(); } } if (md5OK) { readPageGeometriesIntoMap(getPages()); } else { FutureTask<Integer> userInput = new FutureTask<Integer>(new Callable<Integer>() { @Override public Integer call() throws Exception { return JOptionPane.showConfirmDialog(measureComponent, "Das Dokument wurde seit dem letzten Kalibrieren geändert. Sollen die Kalibrierungsdaten für das Dokument gelöscht werden?", "Dokument wurde verändert", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); } }); EventQueue.invokeAndWait(userInput); if (userInput.get().equals(JOptionPane.OK_OPTION)) { Collection<CidsBean> pageGeoData = getPages(); if (pageGeoData != null) { for (CidsBean bean : pageGeoData) { bean.delete(); } } } else { updateMD5(); readPageGeometriesIntoMap(getPages()); } } closeReader(); pictureReader = new MultiPagePictureReader(pictureFile); final int numberOfPages = pictureReader.getNumberOfPages(); for (int i = 0; i < numberOfPages; ++i) { model.addElement(i + 1); } return model; } private void readPageGeometriesIntoMap(Collection<CidsBean> pageGeoms) { pageGeometries.clear(); if (pageGeoms != null) { for (CidsBean bean : pageGeoms) { Object pageNumberObj = bean.getProperty("page_number"); Object geometryObj = bean.getProperty("geometry"); if (pageNumberObj instanceof Integer && geometryObj instanceof Geometry) { pageGeometries.put((Integer) pageNumberObj, (Geometry) geometryObj); } } } } @Override protected void done() { try { final ListModel model = get(); lstPictures.setModel(model); if (model.getSize() > 0) { lstPictures.setSelectedIndex(0); } else { lstPictures.setModel(new DefaultListModel()); } } catch (InterruptedException ex) { setCurrentDocumentNull(); lstPictures.setModel(FEHLER_MODEL); log.warn(ex, ex); } catch (ExecutionException ex) { lstPictures.setModel(FEHLER_MODEL); setCurrentDocumentNull(); log.error(ex, ex); } finally { setControlsEnabled(true); } } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="PictureSelectionWorker"> final class PictureSelectWorker extends SwingWorker<BufferedImage, Void> { public PictureSelectWorker(int pageNumber) { this.pageNumber = pageNumber; setCurrentPageNull(); setControlsEnabled(false); measureComponent.reset(); } private final int pageNumber; @Override protected BufferedImage doInBackground() throws Exception { if (pictureReader != null) { return pictureReader.loadPage(pageNumber); } throw new IllegalStateException("PictureReader is null!"); } @Override protected void done() { try { final Geometry pageGeom = pageGeometries.get(pageNumber); currentPage = pageNumber; togPan.setSelected(true); resetMeasureDataLabels(); measureComponent.addImage(get(), pageGeom); measureComponent.zoomToFeatureCollection(); if(pageGeom != null) { rpMessdaten.setBackground(KALIBRIERUNG_VORHANDEN); rpMessdaten.setAlpha(120); } else { rpMessdaten.setBackground(Color.WHITE); rpMessdaten.setAlpha(60); } } catch (InterruptedException ex) { setCurrentPageNull(); log.warn(ex, ex); } catch (Exception ex) { setCurrentPageNull(); log.error(ex, ex); } finally { setControlsEnabled(true); } } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="MessenFeatureCollectionListener"> final class MessenFeatureCollectionListener extends de.cismet.cismap.commons.features.FeatureCollectionAdapter { @Override public void featuresAdded(FeatureCollectionEvent fce) { if (!togCalibrate.isEnabled()) { for (Feature f : measureComponent.getFeatureCollection().getAllFeatures()) { if (f instanceof PureNewFeature && !(f.getGeometry() instanceof Point)) { //messgeometrie gefunden togCalibrate.setEnabled(true); } } } refreshMeasurementsInStatus(fce.getEventFeatures()); } @Override public void featuresRemoved(FeatureCollectionEvent fce) { if (togCalibrate.isEnabled()) { for (Feature f : measureComponent.getFeatureCollection().getAllFeatures()) { if (f instanceof PureNewFeature && !(f.getGeometry() instanceof Point)) { //messgeometrie gefunden. return; } } togCalibrate.setEnabled(false); } } @Override public void allFeaturesRemoved(FeatureCollectionEvent fce) { featuresRemoved(fce); } @Override public void featuresChanged(FeatureCollectionEvent fce) { // if (map.getInteractionMode().equals(MY_MESSEN_MODE)) { refreshMeasurementsInStatus(fce.getEventFeatures()); // } else { // refreshMeasurementsInStatus(); // } } @Override public void featureSelectionChanged(FeatureCollectionEvent fce) { // refreshMeasurementsInStatus(); refreshMeasurementsInStatus(fce.getEventFeatures()); } } private void resetMeasureDataLabels() { lblTxtDistance.setText("Länge/Umfang:"); lblDistance.setText("-"); lblArea.setText("-"); } private void refreshMeasurementsInStatus(Collection<Feature> cf) { double umfang = 0.0; double area = 0.0; for (Feature f : cf) { Geometry geom = f.getGeometry(); if (f instanceof PureNewFeature && geom != null) { area += geom.getArea(); umfang += geom.getLength(); if (umfang != 0.0) { if (area != 0.0) { lblTxtDistance.setText("Umfang:"); lblDistance.setText(StaticDecimalTools.round(umfang) + " m "); lblArea.setText(StaticDecimalTools.round(area) + " m²"); } else { if (MessenGeometryListener.POLYGON.equals(measureComponent.getMessenInputListener().getMode())) { //reduce polygon line length to one way umfang *= 0.5; } lblTxtDistance.setText("Länge:"); lblDistance.setText(StaticDecimalTools.round(umfang) + " m "); lblArea.setText("-"); } } else { resetMeasureDataLabels(); } } } } } // </editor-fold>
false
true
private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; btnGrpDocs = new javax.swing.ButtonGroup(); buttonGrpMode = new javax.swing.ButtonGroup(); panPicNavigation = new javax.swing.JPanel(); spDocuments = new de.cismet.tools.gui.RoundedPanel(); btnPlan = new javax.swing.JButton(); btnTextblatt = new javax.swing.JButton(); semiRoundedPanel2 = new de.cismet.tools.gui.SemiRoundedPanel(); jLabel1 = new javax.swing.JLabel(); rpSeiten = new de.cismet.tools.gui.RoundedPanel(); scpPictureList = new javax.swing.JScrollPane(); lstPictures = new javax.swing.JList(); semiRoundedPanel3 = new de.cismet.tools.gui.SemiRoundedPanel(); jLabel2 = new javax.swing.JLabel(); rpMessdaten = new de.cismet.tools.gui.RoundedPanel(); lblArea = new javax.swing.JLabel(); lblDistance = new javax.swing.JLabel(); lblTxtDistance = new javax.swing.JLabel(); lblTxtArea = new javax.swing.JLabel(); semiRoundedPanel5 = new de.cismet.tools.gui.SemiRoundedPanel(); jLabel6 = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); rpControls = new de.cismet.tools.gui.RoundedPanel(); togPan = new javax.swing.JToggleButton(); togZoom = new javax.swing.JToggleButton(); togMessenLine = new javax.swing.JToggleButton(); togMessenPoly = new javax.swing.JToggleButton(); togCalibrate = new javax.swing.JToggleButton(); btnHome = new javax.swing.JButton(); semiRoundedPanel4 = new de.cismet.tools.gui.SemiRoundedPanel(); jLabel3 = new javax.swing.JLabel(); btnPrint = new javax.swing.JButton(); panCenter = new javax.swing.JPanel(); measureComponent = new de.cismet.cismap.commons.gui.measuring.MeasuringComponent(); semiRoundedPanel1 = new de.cismet.tools.gui.SemiRoundedPanel(); lblCurrentViewTitle = new javax.swing.JLabel(); setOpaque(false); setLayout(new java.awt.BorderLayout()); panPicNavigation.setMinimumSize(new java.awt.Dimension(140, 216)); panPicNavigation.setOpaque(false); panPicNavigation.setPreferredSize(new java.awt.Dimension(140, 216)); panPicNavigation.setLayout(new java.awt.GridBagLayout()); spDocuments.setLayout(new java.awt.GridBagLayout()); btnPlan.setText("Plan"); btnPlan.setToolTipText("Plan"); btnGrpDocs.add(btnPlan); btnPlan.setMaximumSize(new java.awt.Dimension(53, 33)); btnPlan.setMinimumSize(new java.awt.Dimension(53, 33)); btnPlan.setPreferredSize(new java.awt.Dimension(53, 33)); btnPlan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnPlanActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 3, 5); spDocuments.add(btnPlan, gridBagConstraints); btnTextblatt.setText("Textblatt"); btnTextblatt.setToolTipText("Textblatt"); btnGrpDocs.add(btnTextblatt); btnTextblatt.setMaximumSize(new java.awt.Dimension(53, 33)); btnTextblatt.setMinimumSize(new java.awt.Dimension(53, 33)); btnTextblatt.setPreferredSize(new java.awt.Dimension(53, 33)); btnTextblatt.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnTextblattActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(2, 5, 5, 5); spDocuments.add(btnTextblatt, gridBagConstraints); semiRoundedPanel2.setBackground(new java.awt.Color(51, 51, 51)); semiRoundedPanel2.setLayout(new java.awt.FlowLayout()); jLabel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setText("Dokumentauswahl"); semiRoundedPanel2.add(jLabel1); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; spDocuments.add(semiRoundedPanel2, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 5, 7); panPicNavigation.add(spDocuments, gridBagConstraints); scpPictureList.setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 5, 5, 5)); scpPictureList.setMinimumSize(new java.awt.Dimension(100, 150)); scpPictureList.setOpaque(false); scpPictureList.setPreferredSize(new java.awt.Dimension(100, 150)); lstPictures.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); lstPictures.setEnabled(false); lstPictures.setFixedCellWidth(75); lstPictures.addListSelectionListener(new javax.swing.event.ListSelectionListener() { public void valueChanged(javax.swing.event.ListSelectionEvent evt) { lstPicturesValueChanged(evt); } }); scpPictureList.setViewportView(lstPictures); rpSeiten.add(scpPictureList, java.awt.BorderLayout.CENTER); semiRoundedPanel3.setBackground(new java.awt.Color(51, 51, 51)); semiRoundedPanel3.setLayout(new java.awt.FlowLayout()); jLabel2.setForeground(new java.awt.Color(255, 255, 255)); jLabel2.setText("Seitenauswahl"); semiRoundedPanel3.add(jLabel2); rpSeiten.add(semiRoundedPanel3, java.awt.BorderLayout.PAGE_START); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(5, 0, 5, 7); panPicNavigation.add(rpSeiten, gridBagConstraints); rpMessdaten.setLayout(new java.awt.GridBagLayout()); lblArea.setText("-"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(2, 5, 5, 5); rpMessdaten.add(lblArea, gridBagConstraints); lblDistance.setText("-"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(2, 5, 5, 5); rpMessdaten.add(lblDistance, gridBagConstraints); lblTxtDistance.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N lblTxtDistance.setText("Länge/Umfang:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 3, 5); rpMessdaten.add(lblTxtDistance, gridBagConstraints); lblTxtArea.setFont(new java.awt.Font("Tahoma", 1, 11)); lblTxtArea.setText("Fläche:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 3, 5); rpMessdaten.add(lblTxtArea, gridBagConstraints); semiRoundedPanel5.setBackground(new java.awt.Color(51, 51, 51)); semiRoundedPanel5.setLayout(new java.awt.FlowLayout()); jLabel6.setForeground(new java.awt.Color(255, 255, 255)); jLabel6.setText("Messdaten"); semiRoundedPanel5.add(jLabel6); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; rpMessdaten.add(semiRoundedPanel5, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 7); panPicNavigation.add(rpMessdaten, gridBagConstraints); jPanel1.setOpaque(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.weighty = 1.0; panPicNavigation.add(jPanel1, gridBagConstraints); rpControls.setLayout(new java.awt.GridBagLayout()); buttonGrpMode.add(togPan); togPan.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/pan.gif"))); // NOI18N togPan.setSelected(true); togPan.setText("Verschieben"); togPan.setToolTipText("Verschieben"); togPan.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); togPan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { togPanActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(2, 5, 3, 5); rpControls.add(togPan, gridBagConstraints); buttonGrpMode.add(togZoom); togZoom.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/zoom.gif"))); // NOI18N togZoom.setText("Zoomen"); togZoom.setToolTipText("Zoomen"); togZoom.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); togZoom.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { togZoomActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(2, 5, 3, 5); rpControls.add(togZoom, gridBagConstraints); buttonGrpMode.add(togMessenLine); togMessenLine.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/newLinestring.png"))); // NOI18N togMessenLine.setText("Messlinie"); togMessenLine.setToolTipText("Messen (Linie)"); togMessenLine.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); togMessenLine.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { togMessenLineActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(2, 5, 3, 5); rpControls.add(togMessenLine, gridBagConstraints); buttonGrpMode.add(togMessenPoly); togMessenPoly.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/newPolygon.png"))); // NOI18N togMessenPoly.setText("Messfläche"); togMessenPoly.setToolTipText("Messen (Polygon)"); togMessenPoly.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); togMessenPoly.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { togMessenPolyActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(2, 5, 3, 5); rpControls.add(togMessenPoly, gridBagConstraints); buttonGrpMode.add(togCalibrate); togCalibrate.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/screen.gif"))); // NOI18N togCalibrate.setText("Kalibrieren"); togCalibrate.setToolTipText("Kalibrieren"); togCalibrate.setEnabled(false); togCalibrate.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); togCalibrate.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { togCalibrateActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 6; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(2, 5, 3, 5); rpControls.add(togCalibrate, gridBagConstraints); btnHome.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/home.gif"))); // NOI18N btnHome.setText("Übersicht"); btnHome.setToolTipText("Übersicht"); btnHome.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); btnHome.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnHomeActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(5, 5, 3, 5); rpControls.add(btnHome, gridBagConstraints); semiRoundedPanel4.setBackground(new java.awt.Color(51, 51, 51)); semiRoundedPanel4.setLayout(new java.awt.FlowLayout()); jLabel3.setForeground(new java.awt.Color(255, 255, 255)); jLabel3.setText("Steuerung"); semiRoundedPanel4.add(jLabel3); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; rpControls.add(semiRoundedPanel4, gridBagConstraints); btnPrint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/frameprint.png"))); // NOI18N btnPrint.setText("Drucken"); btnPrint.setToolTipText("Übersicht"); btnPrint.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); btnPrint.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnPrintActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 7; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(2, 5, 5, 5); rpControls.add(btnPrint, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(5, 0, 5, 7); panPicNavigation.add(rpControls, gridBagConstraints); add(panPicNavigation, java.awt.BorderLayout.WEST); panCenter.setOpaque(false); panCenter.setLayout(new java.awt.BorderLayout()); panCenter.add(measureComponent, java.awt.BorderLayout.CENTER); semiRoundedPanel1.setBackground(new java.awt.Color(51, 51, 51)); semiRoundedPanel1.setLayout(new java.awt.FlowLayout()); lblCurrentViewTitle.setForeground(new java.awt.Color(255, 255, 255)); lblCurrentViewTitle.setText("Keine Auswahl"); semiRoundedPanel1.add(lblCurrentViewTitle); panCenter.add(semiRoundedPanel1, java.awt.BorderLayout.NORTH); add(panCenter, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents
private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; btnGrpDocs = new javax.swing.ButtonGroup(); buttonGrpMode = new javax.swing.ButtonGroup(); panPicNavigation = new javax.swing.JPanel(); spDocuments = new de.cismet.tools.gui.RoundedPanel(); btnPlan = new javax.swing.JButton(); btnTextblatt = new javax.swing.JButton(); semiRoundedPanel2 = new de.cismet.tools.gui.SemiRoundedPanel(); jLabel1 = new javax.swing.JLabel(); rpSeiten = new de.cismet.tools.gui.RoundedPanel(); scpPictureList = new javax.swing.JScrollPane(); lstPictures = new javax.swing.JList(); semiRoundedPanel3 = new de.cismet.tools.gui.SemiRoundedPanel(); jLabel2 = new javax.swing.JLabel(); rpMessdaten = new de.cismet.tools.gui.RoundedPanel(); lblArea = new javax.swing.JLabel(); lblDistance = new javax.swing.JLabel(); lblTxtDistance = new javax.swing.JLabel(); lblTxtArea = new javax.swing.JLabel(); semiRoundedPanel5 = new de.cismet.tools.gui.SemiRoundedPanel(); jLabel6 = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); rpControls = new de.cismet.tools.gui.RoundedPanel(); togPan = new javax.swing.JToggleButton(); togZoom = new javax.swing.JToggleButton(); togMessenLine = new javax.swing.JToggleButton(); togMessenPoly = new javax.swing.JToggleButton(); togCalibrate = new javax.swing.JToggleButton(); btnHome = new javax.swing.JButton(); semiRoundedPanel4 = new de.cismet.tools.gui.SemiRoundedPanel(); jLabel3 = new javax.swing.JLabel(); btnPrint = new javax.swing.JButton(); panCenter = new javax.swing.JPanel(); measureComponent = new de.cismet.cismap.commons.gui.measuring.MeasuringComponent(); semiRoundedPanel1 = new de.cismet.tools.gui.SemiRoundedPanel(); lblCurrentViewTitle = new javax.swing.JLabel(); setOpaque(false); setLayout(new java.awt.BorderLayout()); panPicNavigation.setMinimumSize(new java.awt.Dimension(140, 216)); panPicNavigation.setOpaque(false); panPicNavigation.setPreferredSize(new java.awt.Dimension(140, 216)); panPicNavigation.setLayout(new java.awt.GridBagLayout()); spDocuments.setLayout(new java.awt.GridBagLayout()); btnPlan.setText("Plan"); btnPlan.setToolTipText("Plan"); btnGrpDocs.add(btnPlan); btnPlan.setMaximumSize(new java.awt.Dimension(53, 33)); btnPlan.setMinimumSize(new java.awt.Dimension(53, 33)); btnPlan.setPreferredSize(new java.awt.Dimension(53, 33)); btnPlan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnPlanActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 3, 5); spDocuments.add(btnPlan, gridBagConstraints); btnTextblatt.setText("Textblatt"); btnTextblatt.setToolTipText("Textblatt"); btnGrpDocs.add(btnTextblatt); btnTextblatt.setMaximumSize(new java.awt.Dimension(53, 33)); btnTextblatt.setMinimumSize(new java.awt.Dimension(53, 33)); btnTextblatt.setPreferredSize(new java.awt.Dimension(53, 33)); btnTextblatt.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnTextblattActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(2, 5, 5, 5); spDocuments.add(btnTextblatt, gridBagConstraints); semiRoundedPanel2.setBackground(new java.awt.Color(51, 51, 51)); semiRoundedPanel2.setLayout(new java.awt.FlowLayout()); jLabel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setText("Dokumentauswahl"); semiRoundedPanel2.add(jLabel1); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; spDocuments.add(semiRoundedPanel2, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 5, 7); panPicNavigation.add(spDocuments, gridBagConstraints); scpPictureList.setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 5, 5, 5)); scpPictureList.setMinimumSize(new java.awt.Dimension(100, 150)); scpPictureList.setOpaque(false); scpPictureList.setPreferredSize(new java.awt.Dimension(100, 150)); lstPictures.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); lstPictures.setEnabled(false); lstPictures.setFixedCellWidth(75); lstPictures.addListSelectionListener(new javax.swing.event.ListSelectionListener() { public void valueChanged(javax.swing.event.ListSelectionEvent evt) { lstPicturesValueChanged(evt); } }); scpPictureList.setViewportView(lstPictures); rpSeiten.add(scpPictureList, java.awt.BorderLayout.CENTER); semiRoundedPanel3.setBackground(new java.awt.Color(51, 51, 51)); semiRoundedPanel3.setLayout(new java.awt.FlowLayout()); jLabel2.setForeground(new java.awt.Color(255, 255, 255)); jLabel2.setText("Seitenauswahl"); semiRoundedPanel3.add(jLabel2); rpSeiten.add(semiRoundedPanel3, java.awt.BorderLayout.PAGE_START); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(5, 0, 5, 7); panPicNavigation.add(rpSeiten, gridBagConstraints); rpMessdaten.setLayout(new java.awt.GridBagLayout()); lblArea.setText("-"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(2, 5, 5, 5); rpMessdaten.add(lblArea, gridBagConstraints); lblDistance.setText("-"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(2, 5, 5, 5); rpMessdaten.add(lblDistance, gridBagConstraints); lblTxtDistance.setFont(new java.awt.Font("Tahoma", 1, 11)); lblTxtDistance.setText("Länge/Umfang:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 3, 5); rpMessdaten.add(lblTxtDistance, gridBagConstraints); lblTxtArea.setFont(new java.awt.Font("Tahoma", 1, 11)); lblTxtArea.setText("Fläche:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 3, 5); rpMessdaten.add(lblTxtArea, gridBagConstraints); semiRoundedPanel5.setBackground(new java.awt.Color(51, 51, 51)); semiRoundedPanel5.setLayout(new java.awt.FlowLayout()); jLabel6.setForeground(new java.awt.Color(255, 255, 255)); jLabel6.setText("Messdaten"); semiRoundedPanel5.add(jLabel6); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; rpMessdaten.add(semiRoundedPanel5, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 7); panPicNavigation.add(rpMessdaten, gridBagConstraints); jPanel1.setOpaque(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.weighty = 1.0; panPicNavigation.add(jPanel1, gridBagConstraints); rpControls.setLayout(new java.awt.GridBagLayout()); buttonGrpMode.add(togPan); togPan.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/pan.gif"))); // NOI18N togPan.setSelected(true); togPan.setText("Verschieben"); togPan.setToolTipText("Verschieben"); togPan.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); togPan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { togPanActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(2, 5, 3, 5); rpControls.add(togPan, gridBagConstraints); buttonGrpMode.add(togZoom); togZoom.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/zoom.gif"))); // NOI18N togZoom.setText("Zoomen"); togZoom.setToolTipText("Zoomen"); togZoom.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); togZoom.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { togZoomActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(2, 5, 3, 5); rpControls.add(togZoom, gridBagConstraints); buttonGrpMode.add(togMessenLine); togMessenLine.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/newLinestring.png"))); // NOI18N togMessenLine.setText("Messlinie"); togMessenLine.setToolTipText("Messen (Linie)"); togMessenLine.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); togMessenLine.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { togMessenLineActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(2, 5, 3, 5); rpControls.add(togMessenLine, gridBagConstraints); buttonGrpMode.add(togMessenPoly); togMessenPoly.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/newPolygon.png"))); // NOI18N togMessenPoly.setText("Messfläche"); togMessenPoly.setToolTipText("Messen (Polygon)"); togMessenPoly.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); togMessenPoly.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { togMessenPolyActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(2, 5, 3, 5); rpControls.add(togMessenPoly, gridBagConstraints); buttonGrpMode.add(togCalibrate); togCalibrate.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/screen.gif"))); // NOI18N togCalibrate.setText("Kalibrieren"); togCalibrate.setToolTipText("Kalibrieren"); togCalibrate.setEnabled(false); togCalibrate.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); togCalibrate.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { togCalibrateActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 6; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(2, 5, 3, 5); rpControls.add(togCalibrate, gridBagConstraints); btnHome.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/home.gif"))); // NOI18N btnHome.setText("Übersicht"); btnHome.setToolTipText("Übersicht"); btnHome.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); btnHome.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnHomeActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(5, 5, 3, 5); rpControls.add(btnHome, gridBagConstraints); semiRoundedPanel4.setBackground(new java.awt.Color(51, 51, 51)); semiRoundedPanel4.setLayout(new java.awt.FlowLayout()); jLabel3.setForeground(new java.awt.Color(255, 255, 255)); jLabel3.setText("Steuerung"); semiRoundedPanel4.add(jLabel3); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; rpControls.add(semiRoundedPanel4, gridBagConstraints); btnPrint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/folder-image.png"))); // NOI18N btnPrint.setText("Öffnen"); btnPrint.setToolTipText("Extern öffnen"); btnPrint.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); btnPrint.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnPrintActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 7; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(2, 5, 5, 5); rpControls.add(btnPrint, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(5, 0, 5, 7); panPicNavigation.add(rpControls, gridBagConstraints); add(panPicNavigation, java.awt.BorderLayout.WEST); panCenter.setOpaque(false); panCenter.setLayout(new java.awt.BorderLayout()); panCenter.add(measureComponent, java.awt.BorderLayout.CENTER); semiRoundedPanel1.setBackground(new java.awt.Color(51, 51, 51)); semiRoundedPanel1.setLayout(new java.awt.FlowLayout()); lblCurrentViewTitle.setForeground(new java.awt.Color(255, 255, 255)); lblCurrentViewTitle.setText("Keine Auswahl"); semiRoundedPanel1.add(lblCurrentViewTitle); panCenter.add(semiRoundedPanel1, java.awt.BorderLayout.NORTH); add(panCenter, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents
diff --git a/webapp/app/gov/nrel/util/TransferBean.java b/webapp/app/gov/nrel/util/TransferBean.java index f48e4189..d785f9d3 100644 --- a/webapp/app/gov/nrel/util/TransferBean.java +++ b/webapp/app/gov/nrel/util/TransferBean.java @@ -1,230 +1,232 @@ package gov.nrel.util; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import javax.persistence.Column; import models.DataTypeEnum; import models.EntityUser; import models.SecureSchema; import models.SecureTable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.alvazan.orm.api.base.Bootstrap; import com.alvazan.orm.api.base.CursorToMany; import com.alvazan.orm.api.base.DbTypeEnum; import com.alvazan.orm.api.base.Indexing; import com.alvazan.orm.api.base.NoSqlEntityManager; import com.alvazan.orm.api.base.NoSqlEntityManagerFactory; import com.alvazan.orm.api.base.anno.NoSqlEmbeddable; import com.alvazan.orm.api.base.anno.NoSqlEntity; import com.alvazan.orm.api.z3api.NoSqlTypedSession; import com.alvazan.orm.api.z3api.QueryResult; import com.alvazan.orm.api.z5api.NoSqlSession; import com.alvazan.orm.api.z8spi.KeyValue; import com.alvazan.orm.api.z8spi.NoSqlRawSession; import com.alvazan.orm.api.z8spi.Row; import com.alvazan.orm.api.z8spi.conv.ByteArray; import com.alvazan.orm.api.z8spi.iter.AbstractCursor; import com.alvazan.orm.api.z8spi.iter.Cursor; import com.alvazan.orm.api.z8spi.meta.DboColumnIdMeta; import com.alvazan.orm.api.z8spi.meta.DboColumnMeta; import com.alvazan.orm.api.z8spi.meta.DboTableMeta; import com.alvazan.orm.api.z8spi.meta.TypedColumn; import com.alvazan.orm.api.z8spi.meta.TypedRow; import com.alvazan.play.NoSql; import play.Play; public class TransferBean extends TransferSuper { private static final Logger log = LoggerFactory.getLogger(TransferBean.class); public void transfer() { String upgradeMode = (String) Play.configuration.get("upgrade.mode"); if(upgradeMode == null || !upgradeMode.startsWith("http")) { log.info("NOT RUNNING PORT DATA scripts since upgrademode does not start with http"); return; //we dont' run unless we are in transfer mode } NoSqlEntityManager mgr2 = initialize(); NoSqlEntityManager mgr = NoSql.em(); //NEXT, we need to check if data has already been ported so we don't port twice List<SecureSchema> schemas = SecureSchema.findAll(mgr2); if(schemas.size() > 0) { log.info("NOT RUNNING PORT DATA scripts to new cassandra since there are existing schemas(this is very bad)"); return; } else log.info("RUNNING PORT DATA scripts to new cassandra since no databases found in new cassandra instance"); String cf = "User"; portTableToNewCassandra(mgr, mgr2, cf); cf = "KeyToTableName"; portTableToNewCassandra(mgr, mgr2, cf); cf = "AppProperty"; portTableToNewCassandra(mgr, mgr2, cf); cf = "EntityGroupXref"; portTableToNewCassandra(mgr, mgr2, cf); cf = "SdiColumn"; portTableToNewCassandra(mgr, mgr2, cf); cf = "SdiTable"; portTableToNewCassandra(mgr, mgr2, cf); cf = "SecureResourceGroupXref"; portTableToNewCassandra(mgr, mgr2, cf); cf = "DboTableMeta"; portTableToNewCassandra(mgr, mgr2, cf); cf = "DboColumnMeta"; portTableToNewCassandra(mgr, mgr2, cf); //time to port indexes now... buildIndexesOnNewSystem(mgr, mgr2); //Now that we have indexes, we can port cursor to many //need indexes first since we use indexes on new cassandra(and use one on old cassandra as well). portOverCursorToMany(mgr, mgr2); cleanupTimeSeriesMeta(mgr2); } private void cleanupTimeSeriesMeta(NoSqlEntityManager mgr2) { Set<String> timeSeriesNames = new HashSet<String>(); timeSeriesNames.add("time"); timeSeriesNames.add("value"); Cursor<KeyValue<SecureTable>> cursor = SecureTable.findAllCursor(mgr2); int counter = 0; while(cursor.next()) { KeyValue<SecureTable> kv = cursor.getCurrent(); SecureTable table = kv.getValue(); if(table == null) { log.warn("we could not modify table="+kv.getKey(), new RuntimeException().fillInStackTrace()); } DboTableMeta tableMeta = table.getTableMeta(); List<String> names = tableMeta.getColumnNameList(); if(names.size() == 2 && timeSeriesNames.contains(names.get(0)) && timeSeriesNames.contains(names.get(1))) { long partitionSize = TimeUnit.MILLISECONDS.convert(30, TimeUnit.DAYS); tableMeta.setTimeSeries(true); tableMeta.setTimeSeriesPartionSize(partitionSize); table.setTypeOfData(DataTypeEnum.TIME_SERIES); mgr2.put(tableMeta); mgr2.put(table); } else { table.setTypeOfData(DataTypeEnum.RELATIONAL); mgr2.put(table); } if(counter % 50 == 0) { mgr2.flush(); mgr2.clear(); } if(counter % 300 == 0) { log.info("ported "+counter+" records for cf=DboTableMeta time series changes and still porting"); } counter++; } mgr2.clear(); mgr2.flush(); log.info("done porting. count="+counter+" records for cf=DboTableMeta time series changes"); } private void buildIndexesOnNewSystem(NoSqlEntityManager mgr, NoSqlEntityManager mgr2) { String cf = "User"; buildIndexForCf(mgr2, cf); cf = "AppProperty"; buildIndexForCf(mgr2, cf); cf = "SdiTable"; buildIndexForCf(mgr2, cf); } private void buildIndexForCf(NoSqlEntityManager mgr2, String cf) { log.info("building index for CF="+cf); Indexing.setForcedIndexing(true); Cursor<Object> rows = mgr2.allRows(Object.class, cf, 500); int counter = 0; while(rows.next()) { Object obj = rows.getCurrent(); mgr2.put(obj); counter++; if(counter % 50 == 0) { mgr2.clear(); mgr2.flush(); } if(counter % 300 == 0) { log.info("ported "+counter+" records for cf="+cf+" and still porting"); } } mgr2.clear(); mgr2.flush(); Indexing.setForcedIndexing(false); log.info("done indexing. count="+counter+" records for cf="+cf); } private void portOverCursorToMany(NoSqlEntityManager mgr, NoSqlEntityManager mgr2) { log.info("porting over all the CursorToMany of SecureTable entities"); List<SecureSchema> schemas = SecureSchema.findAll(mgr); List<SecureSchema> schemas2 = SecureSchema.findAll(mgr2); Map<String, SecureSchema> map = new HashMap<String, SecureSchema>(); for(SecureSchema s : schemas) { map.put(s.getName(), s); } int counter = 0; //form the row key for CursorToMany for(SecureSchema s: schemas2) { log.info("porting over database="+s.getName()+" id="+s.getId()); SecureSchema oldSchema = map.get(s.getName()); if(oldSchema == null) throw new RuntimeException("bug, all the same schemas should exist in both systems. s="+s.getName()+" does not exist. id="+s.getId()); int tableCount = 0; CursorToMany<SecureTable> tables = oldSchema.getTablesCursor(); while(tables.next()) { SecureTable table = tables.getCurrent(); SecureTable tb = mgr2.find(SecureTable.class, table.getId()); - if(tb == null) - throw new RuntimeException("Table="+table.getName()+" does not exist for some reason. id looked up="+table.getId()); + if(tb == null) { + log.warn("Table='"+table.getName()+"' does not exist for some reason. id looked up='"+table.getId()+"'"); + continue; + } s.getTablesCursor().addElement(tb); tableCount++; counter++; if(counter % 50 == 0) { mgr2.put(s); mgr.clear(); mgr2.flush(); mgr2.clear(); } if(counter % 500 == 0) { log.info("For db="+s.getName()+" ported over table count="+tableCount); } } mgr2.put(s); log.info("ported total tables="+tableCount+" for schema="+s.getName()); } mgr.clear(); mgr2.flush(); log.info("counter is at="+counter+" for all tables CursorToMany port"); } }
true
true
private void portOverCursorToMany(NoSqlEntityManager mgr, NoSqlEntityManager mgr2) { log.info("porting over all the CursorToMany of SecureTable entities"); List<SecureSchema> schemas = SecureSchema.findAll(mgr); List<SecureSchema> schemas2 = SecureSchema.findAll(mgr2); Map<String, SecureSchema> map = new HashMap<String, SecureSchema>(); for(SecureSchema s : schemas) { map.put(s.getName(), s); } int counter = 0; //form the row key for CursorToMany for(SecureSchema s: schemas2) { log.info("porting over database="+s.getName()+" id="+s.getId()); SecureSchema oldSchema = map.get(s.getName()); if(oldSchema == null) throw new RuntimeException("bug, all the same schemas should exist in both systems. s="+s.getName()+" does not exist. id="+s.getId()); int tableCount = 0; CursorToMany<SecureTable> tables = oldSchema.getTablesCursor(); while(tables.next()) { SecureTable table = tables.getCurrent(); SecureTable tb = mgr2.find(SecureTable.class, table.getId()); if(tb == null) throw new RuntimeException("Table="+table.getName()+" does not exist for some reason. id looked up="+table.getId()); s.getTablesCursor().addElement(tb); tableCount++; counter++; if(counter % 50 == 0) { mgr2.put(s); mgr.clear(); mgr2.flush(); mgr2.clear(); } if(counter % 500 == 0) { log.info("For db="+s.getName()+" ported over table count="+tableCount); } } mgr2.put(s); log.info("ported total tables="+tableCount+" for schema="+s.getName()); } mgr.clear(); mgr2.flush(); log.info("counter is at="+counter+" for all tables CursorToMany port"); }
private void portOverCursorToMany(NoSqlEntityManager mgr, NoSqlEntityManager mgr2) { log.info("porting over all the CursorToMany of SecureTable entities"); List<SecureSchema> schemas = SecureSchema.findAll(mgr); List<SecureSchema> schemas2 = SecureSchema.findAll(mgr2); Map<String, SecureSchema> map = new HashMap<String, SecureSchema>(); for(SecureSchema s : schemas) { map.put(s.getName(), s); } int counter = 0; //form the row key for CursorToMany for(SecureSchema s: schemas2) { log.info("porting over database="+s.getName()+" id="+s.getId()); SecureSchema oldSchema = map.get(s.getName()); if(oldSchema == null) throw new RuntimeException("bug, all the same schemas should exist in both systems. s="+s.getName()+" does not exist. id="+s.getId()); int tableCount = 0; CursorToMany<SecureTable> tables = oldSchema.getTablesCursor(); while(tables.next()) { SecureTable table = tables.getCurrent(); SecureTable tb = mgr2.find(SecureTable.class, table.getId()); if(tb == null) { log.warn("Table='"+table.getName()+"' does not exist for some reason. id looked up='"+table.getId()+"'"); continue; } s.getTablesCursor().addElement(tb); tableCount++; counter++; if(counter % 50 == 0) { mgr2.put(s); mgr.clear(); mgr2.flush(); mgr2.clear(); } if(counter % 500 == 0) { log.info("For db="+s.getName()+" ported over table count="+tableCount); } } mgr2.put(s); log.info("ported total tables="+tableCount+" for schema="+s.getName()); } mgr.clear(); mgr2.flush(); log.info("counter is at="+counter+" for all tables CursorToMany port"); }
diff --git a/PVUgame/src/no/hist/gruppe5/pvu/PVU.java b/PVUgame/src/no/hist/gruppe5/pvu/PVU.java index 99856fd..013bb82 100644 --- a/PVUgame/src/no/hist/gruppe5/pvu/PVU.java +++ b/PVUgame/src/no/hist/gruppe5/pvu/PVU.java @@ -1,74 +1,74 @@ package no.hist.gruppe5.pvu; import aurelienribon.tweenengine.Tween; import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import com.badlogic.gdx.backends.lwjgl.LwjglApplication; import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.utils.TimeUtils; import no.hist.gruppe5.pvu.intro.IntroScreen; import no.hist.gruppe5.pvu.intro.SpriteAccessor; import no.hist.gruppe5.pvu.mainroom.MainScreen; public class PVU extends Game { public static Screen MAIN_SCREEN; public static float SCREEN_WIDTH = 960f; public static float SCREEN_HEIGHT = 580f; public static float GAME_WIDTH = 192f; public static float GAME_HEIGHT = 116f; @Override public void create() { long gameStart = TimeUtils.millis(); ScoreHandler.load(); Assets.load(); //Sounds.playMusic(); float loadTook = (TimeUtils.millis() - gameStart) / 1000f; Gdx.app.log(this.getClass().toString(), "Loading took: " + loadTook + " seconds."); Tween.registerAccessor(Sprite.class, new SpriteAccessor()); MAIN_SCREEN = new MainScreen(this); - setScreen(new JumperScreen(this)); + setScreen(new IntroScreen(this)); } @Override public void dispose() { } @Override public void render() { super.render(); } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } public static void main(String[] args) { LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration(); cfg.width = (int) PVU.SCREEN_WIDTH; cfg.height = (int) PVU.SCREEN_HEIGHT; cfg.fullscreen = false; cfg.resizable = false; new LwjglApplication(new PVU(), cfg); } }
true
true
public void create() { long gameStart = TimeUtils.millis(); ScoreHandler.load(); Assets.load(); //Sounds.playMusic(); float loadTook = (TimeUtils.millis() - gameStart) / 1000f; Gdx.app.log(this.getClass().toString(), "Loading took: " + loadTook + " seconds."); Tween.registerAccessor(Sprite.class, new SpriteAccessor()); MAIN_SCREEN = new MainScreen(this); setScreen(new JumperScreen(this)); }
public void create() { long gameStart = TimeUtils.millis(); ScoreHandler.load(); Assets.load(); //Sounds.playMusic(); float loadTook = (TimeUtils.millis() - gameStart) / 1000f; Gdx.app.log(this.getClass().toString(), "Loading took: " + loadTook + " seconds."); Tween.registerAccessor(Sprite.class, new SpriteAccessor()); MAIN_SCREEN = new MainScreen(this); setScreen(new IntroScreen(this)); }
diff --git a/runtime/src/org/zaluum/runtime/LoopBox.java b/runtime/src/org/zaluum/runtime/LoopBox.java index 7e02d6b..cc3cf47 100644 --- a/runtime/src/org/zaluum/runtime/LoopBox.java +++ b/runtime/src/org/zaluum/runtime/LoopBox.java @@ -1,12 +1,18 @@ package org.zaluum.runtime; @Box public abstract class LoopBox extends RunnableBox{ @Out(x=0,y=48) public boolean cond; @Override public void apply() { do{ contents(); + try { + Thread.sleep(10); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } }while(cond); } }
true
true
public void apply() { do{ contents(); }while(cond); }
public void apply() { do{ contents(); try { Thread.sleep(10); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }while(cond); }
diff --git a/src/main/java/jade/tree/NexsonReader.java b/src/main/java/jade/tree/NexsonReader.java index 3eb73fa..3e33d66 100644 --- a/src/main/java/jade/tree/NexsonReader.java +++ b/src/main/java/jade/tree/NexsonReader.java @@ -1,372 +1,375 @@ /* * Read in a Nexml/JSON study file, returning a list of JadeTrees. * The file is assumed to be in the form produced by the * JSON generator in Phylografter; in particular, XML namespace * declarations are not processed, so particular namespace prefix * bindings, and a default namespace of "http://www.nexml.org/2009", * are assumed. * * @about is ignored, etc. * Ill-formed nexson files will lead to random runtime exceptions, such as bad * casts and null pointer exceptions. Should be cleaned up eventually, but not * high priority. */ package jade.tree; import jade.tree.JadeNode; import jade.tree.JadeTree; import jade.MessageLogger; import org.json.simple.JSONValue; import org.json.simple.JSONObject; import org.json.simple.JSONArray; import java.io.Reader; import java.io.FileReader; import java.io.BufferedReader; import java.util.Map; import java.util.HashMap; import java.util.List; import java.util.ArrayList; public class NexsonReader { /* main method for testing - just dumps out Newick */ public static void main(String argv[]) throws Exception { String filename = "study15.json"; if (argv.length == 1) { filename = argv[0]; } MessageLogger msgLogger = new MessageLogger("nexsonReader:"); int treeIndex = 0; for (JadeTree tree : readNexson(filename, true, msgLogger)) { if (tree == null) { msgLogger.messageInt("Null tree indicating unparseable NexSON", "index", treeIndex); } else { msgLogger.messageInt("tree", "index", treeIndex); msgLogger.indentMessageStr(1, "annotation", "Curator", (String)tree.getObject("ot:curatorName")); msgLogger.indentMessageStr(1, "annotation", "Reference", (String)tree.getObject("ot:studyPublicationReference")); msgLogger.indentMessageStr(1, "representation", "newick", tree.getRoot().getNewick(false)); int i = 0; for (JadeNode node : tree.iterateExternalNodes()) { Object o = node.getObject("ot:ottolid"); msgLogger.indentMessageStr(2, "node", "name", node.getName()); msgLogger.indentMessageStr(2, "node", "OTT ID", o.toString()); msgLogger.indentMessageStr(2, "node", "ID class", o.getClass().toString()); if (++i > 10) { break; } } } ++treeIndex; } } /* Read Nexson study from a file, given file name */ public static List<JadeTree> readNexson(String filename, Boolean verbose, MessageLogger msgLogger) throws java.io.IOException { Reader r = new BufferedReader(new FileReader(filename)); List<JadeTree> result = readNexson(r, verbose, msgLogger); r.close(); return result; } /* Read Nexson study from a Reader */ // TODO: tree(s) may be deprecated. Need to check this. May result in no trees to return. public static List<JadeTree> readNexson(Reader r, Boolean verbose, MessageLogger msgLogger) throws java.io.IOException { JSONObject all = (JSONObject)JSONValue.parse(r); /* The format of the file, roughly speaking (some noise omitted): {"nexml": { "@xmlns": ..., "@nexmljson": "http:\/\/www.somewhere.org", "meta": [...], "otus": { "otu": [...] }, "trees": { "tree": [...] }}} See http://www.nexml.org/manual for NexML documentation. */ // the desired result: a list of valid trees List<JadeTree> result = new ArrayList<JadeTree>(); // The XML root element JSONObject root = (JSONObject)all.get("nexml"); // All of the <meta> elements from root (i.e. study-wide). Trees may have their own meta elements (e.g. inGroupClade) List<Object> studyMetaList = getMetaList(root); //System.out.println("studyMetaList = " + studyMetaList); // check if study is flagged as deprecated. if so, skip. if (studyMetaList != null && checkDeprecated(studyMetaList)) { msgLogger.message("Study tagged as deprecated. Ignore."); return result; } // All of the <otu> elements JSONObject otus = (JSONObject)root.get("otus"); JSONArray otuList = (JSONArray)otus.get("otu"); msgLogger.messageInt("OTUs", "number", otuList.size()); // Make an index by id of the OTUs. We'll need to be able to find them when we built the trees. Map<String,JSONObject> otuMap = new HashMap<String,JSONObject>(); for (Object otu : otuList) { JSONObject j = (JSONObject)otu; // j = {"@label": "Platanus", "@id": "otu192"} maybe other data too otuMap.put((String)j.get("@id"), j); } // Get the trees. Each one has nodes and edges JSONObject trees = (JSONObject)root.get("trees"); JSONArray treeList = (JSONArray)trees.get("tree"); // Process each tree in turn, yielding a JadeTree for (Object tree : treeList) { JSONObject tree2 = (JSONObject)tree; String treeID = (String)tree2.get("@id"); if (treeID.startsWith("tree")) { // phylografter tree ids are #'s, but in the Nexson export, they'll have the word tree prepended treeID = treeID.substring(4); // chop off 0-3 to chop off "tree" } msgLogger.messageStr("Processing tree", "@id", treeID); // trees can have their own specific metadata e.g. [{"@property":"ot:branchLengthMode","@xsi:type":"nex:LiteralMeta","$":"ot:substitutionCount"},{"@property":"ot:inGroupClade","$":"node208482","xsi:type":"nex:LiteralMeta"}] List<Object> treeMetaList = getMetaList(tree2); //System.out.println("treeMetaList = " + treeMetaList); // check if tree is deprecated. will be a tree-specific tag (ot:tag). if so, abort. if (treeMetaList != null && checkDeprecated(treeMetaList)) { msgLogger.messageStr("Tree tagged as deprecated. Ignoring.", "@id", treeID); } else { // tree2 = {"node": [...], "edge": [...]} result.add(importTree(otuMap, (JSONArray)tree2.get("node"), (JSONArray)tree2.get("edge"), studyMetaList, treeMetaList, treeID, verbose, msgLogger)); } } return result; } /* Process a single tree (subroutine of above) */ private static JadeTree importTree(Map<String,JSONObject> otuMap, JSONArray nodeList, JSONArray edgeList, List<Object> studyMetaList, List<Object> treeMetaList, String treeID, Boolean verbose, MessageLogger msgLogger) { msgLogger.indentMessageInt(1, "tree info", "number nodes", nodeList.size()); msgLogger.indentMessageInt(1, "tree info", "number edges", edgeList.size()); Map<String, JadeNode> nodeMap = new HashMap<String, JadeNode>(); JadeNode root = null; // check if an ingroup is defined. if so, discard outgroup(s). String ingroup = null; if (treeMetaList != null) { for (Object meta : treeMetaList) { JSONObject j = (JSONObject)meta; if (((String)j.get("@property")).compareTo("ot:inGroupClade") == 0) { if ((j.get("$")) != null) { ingroup = (String)j.get("$"); msgLogger.indentMessageStr(1, "tree info", "ingroup", ingroup); } else { throw new RuntimeException("missing property value for name: " + j); } } } } // arbitraryNode is for finding the root later on (if not specified), see below JadeNode arbitraryNode = null; // For each node as specified in the Nexson file, create a JadeNode, and squirrel it away for (Object node : nodeList) { // {"@otu": "otu221", "@id": "node692"} JSONObject j = (JSONObject)node; // System.out.println(j); JadeNode jn = new JadeNode(); String id = (String)j.get("@id"); nodeMap.put(id, jn); arbitraryNode = jn; jn.assocObject("nexsonid", id); // Set the root node if (ingroup != null && id.compareTo(ingroup) == 0) { msgLogger.indentMessage(1, "Setting ingroup root node."); root = jn; } // Some nodes have associated OTUs, others don't String otuId = (String)j.get("@otu"); if (otuId != null) { JSONObject otu = otuMap.get(otuId); if (otu == null) { msgLogger.indentMessageStr(2, "Error. Node with otuID of unknown OTU", "@otu", otuId); return null; } String label = (String)otu.get("@label"); jn.setName(label); // Get taxon id (usually present) and maybe other metadata (rarely present) List<Object> metaList2 = getMetaList(otu); if (metaList2 != null) { for (Object meta : metaList2) { JSONObject m = (JSONObject)meta; String propname = (String)m.get("@property"); Object value = m.get("$"); + if (propname.equals("ot:ottId")) { + propname = "ot:ottolid"; + } if (propname.equals("ot:ottolid")) { // Kludge! For important special case if (value instanceof String) { value = Long.parseLong((String)value); } else if (value instanceof Long) { ; // what is this about? } else if (value instanceof Integer) { value = new Long((((Integer)value).intValue())); } else if (value == null) { msgLogger.indentMessageStr(1, "Warning: dealing with null ot:ottolid here.", "nexsonid", id); } else { System.err.println("Error with: " + m); throw new RuntimeException("Invalid ottolid value: " + value); } - } else if(propname.equals("ot:originalLabel")){ + } else if (propname.equals("ot:originalLabel")){ // ignoring originalLabel, but not emitting the unknown property warning } else { msgLogger.indentMessageStrStr(1, "Warning: dealing with unknown property. Don't know what to do...", "property name", propname, "nexsonid", id); } jn.assocObject(propname, value); } } } } // For each specified edge, hook up the two corresponding JadeNodes for (Object edge : edgeList) { JSONObject j = (JSONObject)edge; // {"@source": "node830", "@target": "node834", "@length": 0.000241603, "@id": "edge834"} // source is parent, target is child JadeNode source = nodeMap.get(j.get("@source")); if (source == null) { msgLogger.indentMessageStr(2, "Error. Edge with source property not found in map", "@source", (String)j.get("@source")); return null; } JadeNode target = nodeMap.get(j.get("@target")); if (target == null) { msgLogger.indentMessageStr(2, "Error. Edge with target property not found in map", "@target", (String)j.get("@target")); return null; } Double length = (Double)j.get("@length"); if (length != null) { target.setBL(length); } source.addChild(target); } // Find the root (the node without a parent) so we can return it. // If the input file is malicious this might loop forever. if (root == null) { for (JadeNode jn = arbitraryNode; jn != null; jn = jn.getParent()) { root = jn; } } else { // a pruned tree. GraphImporter looks for root as node with no parents. root.setParent(null); } JadeTree tree = new JadeTree(root); int nc = tree.getExternalNodeCount(); msgLogger.indentMessageInt(1, "Ingested tree", "number of external nodes", nc); // Copy STUDY-level metadata into the JadeTree // See https://github.com/nexml/nexml/wiki/NeXML-Manual#wiki-Metadata_annotations_and_NeXML if (studyMetaList != null) { associateMetadata(tree, studyMetaList, (verbose ? msgLogger : null)); } // Copy TREE-level metadata into the JadeTree if (treeMetaList != null) { associateMetadata(tree, treeMetaList, (verbose ? msgLogger : null)); } tree.assocObject("id", treeID); return tree; } // check through metadata information for ot:tag del* // works for both study-wide and tree-specific metadata private static Boolean checkDeprecated (List<Object> metaData) { Boolean deprecated = false; for (Object meta : metaData) { JSONObject j = (JSONObject)meta; if (((String)j.get("@property")).compareTo("ot:tag") == 0) { if ((j.get("$")) != null) { String currentTag = (String)j.get("$"); if (currentTag.startsWith("del")) { return true; } } else { throw new RuntimeException("missing property value for name: " + j); } } } return deprecated; } private static void associateMetadata (JadeTree tree, List<Object> metaData, MessageLogger msgLogger) { for (Object meta : metaData) { JSONObject j = (JSONObject)meta; // {"@property": "ot:curatorName", "@xsi:type": "nex:LiteralMeta", "$": "Rick Ree"}, String propname = (String)j.get("@property"); if (propname != null) { // String propkind = (String)j.get("@xsi:type"); = nex:LiteralMeta // looking for either "$" or "@href" (former is more frequent) if ((j.get("$")) != null) { Object value = j.get("$"); if (value == null) { throw new RuntimeException("missing value for " + propname); } tree.assocObject(propname, value); if (msgLogger != null) { msgLogger.indentMessageStr(1, "property added", propname, value.toString()); } } else if ((j.get("@href")) != null) { Object value = j.get("@href"); if (value == null) { throw new RuntimeException("missing value for " + propname); } tree.assocObject(propname, value); if (msgLogger != null) { msgLogger.indentMessageStr(1, "property added", propname, value.toString()); } } else { throw new RuntimeException("missing property value for name: " + j); } } else { throw new RuntimeException("missing property name: " + j); } } } private static List<Object> getMetaList(JSONObject obj) { //System.out.println("looking up meta for: " + obj); Object meta = obj.get("meta"); if (meta == null) { //System.out.println("meta == NULL"); return null; } //System.out.println("meta != NULL: " + meta); if (meta instanceof JSONObject) { List l = new ArrayList(1); l.add(meta); return l; } else { return (JSONArray) meta; } } }
false
true
private static JadeTree importTree(Map<String,JSONObject> otuMap, JSONArray nodeList, JSONArray edgeList, List<Object> studyMetaList, List<Object> treeMetaList, String treeID, Boolean verbose, MessageLogger msgLogger) { msgLogger.indentMessageInt(1, "tree info", "number nodes", nodeList.size()); msgLogger.indentMessageInt(1, "tree info", "number edges", edgeList.size()); Map<String, JadeNode> nodeMap = new HashMap<String, JadeNode>(); JadeNode root = null; // check if an ingroup is defined. if so, discard outgroup(s). String ingroup = null; if (treeMetaList != null) { for (Object meta : treeMetaList) { JSONObject j = (JSONObject)meta; if (((String)j.get("@property")).compareTo("ot:inGroupClade") == 0) { if ((j.get("$")) != null) { ingroup = (String)j.get("$"); msgLogger.indentMessageStr(1, "tree info", "ingroup", ingroup); } else { throw new RuntimeException("missing property value for name: " + j); } } } } // arbitraryNode is for finding the root later on (if not specified), see below JadeNode arbitraryNode = null; // For each node as specified in the Nexson file, create a JadeNode, and squirrel it away for (Object node : nodeList) { // {"@otu": "otu221", "@id": "node692"} JSONObject j = (JSONObject)node; // System.out.println(j); JadeNode jn = new JadeNode(); String id = (String)j.get("@id"); nodeMap.put(id, jn); arbitraryNode = jn; jn.assocObject("nexsonid", id); // Set the root node if (ingroup != null && id.compareTo(ingroup) == 0) { msgLogger.indentMessage(1, "Setting ingroup root node."); root = jn; } // Some nodes have associated OTUs, others don't String otuId = (String)j.get("@otu"); if (otuId != null) { JSONObject otu = otuMap.get(otuId); if (otu == null) { msgLogger.indentMessageStr(2, "Error. Node with otuID of unknown OTU", "@otu", otuId); return null; } String label = (String)otu.get("@label"); jn.setName(label); // Get taxon id (usually present) and maybe other metadata (rarely present) List<Object> metaList2 = getMetaList(otu); if (metaList2 != null) { for (Object meta : metaList2) { JSONObject m = (JSONObject)meta; String propname = (String)m.get("@property"); Object value = m.get("$"); if (propname.equals("ot:ottolid")) { // Kludge! For important special case if (value instanceof String) { value = Long.parseLong((String)value); } else if (value instanceof Long) { ; // what is this about? } else if (value instanceof Integer) { value = new Long((((Integer)value).intValue())); } else if (value == null) { msgLogger.indentMessageStr(1, "Warning: dealing with null ot:ottolid here.", "nexsonid", id); } else { System.err.println("Error with: " + m); throw new RuntimeException("Invalid ottolid value: " + value); } } else if(propname.equals("ot:originalLabel")){ // ignoring originalLabel, but not emitting the unknown property warning } else { msgLogger.indentMessageStrStr(1, "Warning: dealing with unknown property. Don't know what to do...", "property name", propname, "nexsonid", id); } jn.assocObject(propname, value); } } } } // For each specified edge, hook up the two corresponding JadeNodes for (Object edge : edgeList) { JSONObject j = (JSONObject)edge; // {"@source": "node830", "@target": "node834", "@length": 0.000241603, "@id": "edge834"} // source is parent, target is child JadeNode source = nodeMap.get(j.get("@source")); if (source == null) { msgLogger.indentMessageStr(2, "Error. Edge with source property not found in map", "@source", (String)j.get("@source")); return null; } JadeNode target = nodeMap.get(j.get("@target")); if (target == null) { msgLogger.indentMessageStr(2, "Error. Edge with target property not found in map", "@target", (String)j.get("@target")); return null; } Double length = (Double)j.get("@length"); if (length != null) { target.setBL(length); } source.addChild(target); } // Find the root (the node without a parent) so we can return it. // If the input file is malicious this might loop forever. if (root == null) { for (JadeNode jn = arbitraryNode; jn != null; jn = jn.getParent()) { root = jn; } } else { // a pruned tree. GraphImporter looks for root as node with no parents. root.setParent(null); } JadeTree tree = new JadeTree(root); int nc = tree.getExternalNodeCount(); msgLogger.indentMessageInt(1, "Ingested tree", "number of external nodes", nc); // Copy STUDY-level metadata into the JadeTree // See https://github.com/nexml/nexml/wiki/NeXML-Manual#wiki-Metadata_annotations_and_NeXML if (studyMetaList != null) { associateMetadata(tree, studyMetaList, (verbose ? msgLogger : null)); } // Copy TREE-level metadata into the JadeTree if (treeMetaList != null) { associateMetadata(tree, treeMetaList, (verbose ? msgLogger : null)); } tree.assocObject("id", treeID); return tree; }
private static JadeTree importTree(Map<String,JSONObject> otuMap, JSONArray nodeList, JSONArray edgeList, List<Object> studyMetaList, List<Object> treeMetaList, String treeID, Boolean verbose, MessageLogger msgLogger) { msgLogger.indentMessageInt(1, "tree info", "number nodes", nodeList.size()); msgLogger.indentMessageInt(1, "tree info", "number edges", edgeList.size()); Map<String, JadeNode> nodeMap = new HashMap<String, JadeNode>(); JadeNode root = null; // check if an ingroup is defined. if so, discard outgroup(s). String ingroup = null; if (treeMetaList != null) { for (Object meta : treeMetaList) { JSONObject j = (JSONObject)meta; if (((String)j.get("@property")).compareTo("ot:inGroupClade") == 0) { if ((j.get("$")) != null) { ingroup = (String)j.get("$"); msgLogger.indentMessageStr(1, "tree info", "ingroup", ingroup); } else { throw new RuntimeException("missing property value for name: " + j); } } } } // arbitraryNode is for finding the root later on (if not specified), see below JadeNode arbitraryNode = null; // For each node as specified in the Nexson file, create a JadeNode, and squirrel it away for (Object node : nodeList) { // {"@otu": "otu221", "@id": "node692"} JSONObject j = (JSONObject)node; // System.out.println(j); JadeNode jn = new JadeNode(); String id = (String)j.get("@id"); nodeMap.put(id, jn); arbitraryNode = jn; jn.assocObject("nexsonid", id); // Set the root node if (ingroup != null && id.compareTo(ingroup) == 0) { msgLogger.indentMessage(1, "Setting ingroup root node."); root = jn; } // Some nodes have associated OTUs, others don't String otuId = (String)j.get("@otu"); if (otuId != null) { JSONObject otu = otuMap.get(otuId); if (otu == null) { msgLogger.indentMessageStr(2, "Error. Node with otuID of unknown OTU", "@otu", otuId); return null; } String label = (String)otu.get("@label"); jn.setName(label); // Get taxon id (usually present) and maybe other metadata (rarely present) List<Object> metaList2 = getMetaList(otu); if (metaList2 != null) { for (Object meta : metaList2) { JSONObject m = (JSONObject)meta; String propname = (String)m.get("@property"); Object value = m.get("$"); if (propname.equals("ot:ottId")) { propname = "ot:ottolid"; } if (propname.equals("ot:ottolid")) { // Kludge! For important special case if (value instanceof String) { value = Long.parseLong((String)value); } else if (value instanceof Long) { ; // what is this about? } else if (value instanceof Integer) { value = new Long((((Integer)value).intValue())); } else if (value == null) { msgLogger.indentMessageStr(1, "Warning: dealing with null ot:ottolid here.", "nexsonid", id); } else { System.err.println("Error with: " + m); throw new RuntimeException("Invalid ottolid value: " + value); } } else if (propname.equals("ot:originalLabel")){ // ignoring originalLabel, but not emitting the unknown property warning } else { msgLogger.indentMessageStrStr(1, "Warning: dealing with unknown property. Don't know what to do...", "property name", propname, "nexsonid", id); } jn.assocObject(propname, value); } } } } // For each specified edge, hook up the two corresponding JadeNodes for (Object edge : edgeList) { JSONObject j = (JSONObject)edge; // {"@source": "node830", "@target": "node834", "@length": 0.000241603, "@id": "edge834"} // source is parent, target is child JadeNode source = nodeMap.get(j.get("@source")); if (source == null) { msgLogger.indentMessageStr(2, "Error. Edge with source property not found in map", "@source", (String)j.get("@source")); return null; } JadeNode target = nodeMap.get(j.get("@target")); if (target == null) { msgLogger.indentMessageStr(2, "Error. Edge with target property not found in map", "@target", (String)j.get("@target")); return null; } Double length = (Double)j.get("@length"); if (length != null) { target.setBL(length); } source.addChild(target); } // Find the root (the node without a parent) so we can return it. // If the input file is malicious this might loop forever. if (root == null) { for (JadeNode jn = arbitraryNode; jn != null; jn = jn.getParent()) { root = jn; } } else { // a pruned tree. GraphImporter looks for root as node with no parents. root.setParent(null); } JadeTree tree = new JadeTree(root); int nc = tree.getExternalNodeCount(); msgLogger.indentMessageInt(1, "Ingested tree", "number of external nodes", nc); // Copy STUDY-level metadata into the JadeTree // See https://github.com/nexml/nexml/wiki/NeXML-Manual#wiki-Metadata_annotations_and_NeXML if (studyMetaList != null) { associateMetadata(tree, studyMetaList, (verbose ? msgLogger : null)); } // Copy TREE-level metadata into the JadeTree if (treeMetaList != null) { associateMetadata(tree, treeMetaList, (verbose ? msgLogger : null)); } tree.assocObject("id", treeID); return tree; }
diff --git a/src/main/java/com/yetanotherx/xbot/bots/aiv/RemoveNameJob.java b/src/main/java/com/yetanotherx/xbot/bots/aiv/RemoveNameJob.java index 071e8e4..31fe2ad 100644 --- a/src/main/java/com/yetanotherx/xbot/bots/aiv/RemoveNameJob.java +++ b/src/main/java/com/yetanotherx/xbot/bots/aiv/RemoveNameJob.java @@ -1,140 +1,140 @@ package com.yetanotherx.xbot.bots.aiv; import java.util.Calendar; import java.util.ArrayList; import com.yetanotherx.xbot.util.Util; import java.util.Arrays; import com.yetanotherx.xbot.NewWiki.User; import com.yetanotherx.xbot.XBotDebug; import com.yetanotherx.xbot.bots.BotJob; import com.yetanotherx.xbot.console.ChatColor; import java.io.IOException; import java.util.LinkedList; import java.util.List; import java.util.regex.Pattern; import static com.yetanotherx.xbot.util.RegexUtil.*; public class RemoveNameJob extends BotJob<AIVBot> { private String user; private User blocker; private String duration; private String blockType; private String page; public RemoveNameJob(AIVBot bot, String user, User blocker, String duration, String blockType, String page) { super(bot); this.user = user; this.blocker = blocker; this.duration = duration; this.blockType = blockType; this.page = page; } @Override public void doRun() { try { String content = bot.getParent().getWiki().getPageText(page); String originalContent = content.toString(); Calendar time = bot.getParent().getWiki().getTimestamp(); if (!content.isEmpty()) { int ipsLeft = 0; int usersLeft = 0; boolean found = false; int linesSkipped = 0; List<String> newContent = new LinkedList<String>(); boolean inComment = false; List<String> contentList = new ArrayList<String>(Arrays.asList(content.split("\n"))); while (contentList.size() > 0) { String line = contentList.remove(0); String[] comment = AIVBot.parseComment(line, inComment); inComment = Boolean.parseBoolean(comment[0]); String bareLine = comment[1]; String remainder = comment[2]; if (inComment || !matches("\\{\\{((?:ip)?vandal|userlinks|user-uaa)\\|\\s*(?:1=|user=)?\\Q" + user + "\\E\\s*\\}\\}", line, Pattern.CASE_INSENSITIVE)) { newContent.add(line); if (inComment && line.equals(bareLine)) { continue; } if (bareLine.contains("{{IPvandal|")) { ipsLeft++; } if (matches("\\{\\{(vandal|userlinks|user-uaa)\\|", bareLine, Pattern.CASE_INSENSITIVE)) { usersLeft++; } } else { found = true; if (!remainder.isEmpty()) { newContent.add(remainder); } while (contentList.size() > 0 && !matches("\\{\\{((?:ip)?vandal|userlinks|user-uaa)\\|", contentList.get(0), Pattern.CASE_INSENSITIVE) && !contentList.get(0).startsWith("<!--") && !contentList.get(0).startsWith("=")) { String removed = contentList.remove(0); if (!removed.isEmpty()) { linesSkipped++; inComment = Boolean.parseBoolean(AIVBot.parseComment(removed, inComment)[0]); } } } } content = Util.join("\n", newContent); if (!found || content.isEmpty()) { return; } String length = " "; if (!duration.isEmpty()) { if (duration.equals("indef")) { length = " indef "; } else { length = " " + duration; } } String tally = "Empty."; if (ipsLeft != 0 || usersLeft != 0) { String ipNote = ipsLeft + " IP" + ((ipsLeft != 1) ? "s" : ""); String userNote = usersLeft + " user" + ((usersLeft != 1) ? "s" : ""); if (usersLeft == 0) { // Only IPs left tally = ipNote + " left."; } else if (ipsLeft == 0) { // Only users left tally = userNote + " left."; } else { // Users and ips left tally = ipNote + " & " + userNote + " left."; } } String skipped = ""; if (linesSkipped > 0) { skipped = " " + linesSkipped + " comment(s) removed."; } String summary = tally + " rm [[Special:Contributions/" + user + "|" + user + "]] (blocked" + length + "by [[User:" + blocker.getUsername() + "|" + blocker.getUsername() + "]] " + blockType + "). " + skipped; if (!originalContent.equals(bot.getParent().getWiki().getPageText(page))) { - XBotDebug.warn("AIV", ChatColor.BLUE + page + ChatColor.YELLOW + " has changed since we read it, not changing.", time); + XBotDebug.warn("AIV", ChatColor.BLUE + page + ChatColor.YELLOW + " has changed since we read it, not changing."); return; } else { - bot.getParent().getWiki().doEdit(page, content, summary, false); + bot.getParent().getWiki().doEdit(page, content, summary, false, time); } XBotDebug.info("AIV", ChatColor.GOLD + "Removed " + ChatColor.YELLOW + user + ChatColor.GOLD + " on " + ChatColor.BLUE + page); } } catch (IOException ex) { XBotDebug.error("AIV", "Could not read from wiki.", ex); } } @Override public void doShutdown() { } }
false
true
public void doRun() { try { String content = bot.getParent().getWiki().getPageText(page); String originalContent = content.toString(); Calendar time = bot.getParent().getWiki().getTimestamp(); if (!content.isEmpty()) { int ipsLeft = 0; int usersLeft = 0; boolean found = false; int linesSkipped = 0; List<String> newContent = new LinkedList<String>(); boolean inComment = false; List<String> contentList = new ArrayList<String>(Arrays.asList(content.split("\n"))); while (contentList.size() > 0) { String line = contentList.remove(0); String[] comment = AIVBot.parseComment(line, inComment); inComment = Boolean.parseBoolean(comment[0]); String bareLine = comment[1]; String remainder = comment[2]; if (inComment || !matches("\\{\\{((?:ip)?vandal|userlinks|user-uaa)\\|\\s*(?:1=|user=)?\\Q" + user + "\\E\\s*\\}\\}", line, Pattern.CASE_INSENSITIVE)) { newContent.add(line); if (inComment && line.equals(bareLine)) { continue; } if (bareLine.contains("{{IPvandal|")) { ipsLeft++; } if (matches("\\{\\{(vandal|userlinks|user-uaa)\\|", bareLine, Pattern.CASE_INSENSITIVE)) { usersLeft++; } } else { found = true; if (!remainder.isEmpty()) { newContent.add(remainder); } while (contentList.size() > 0 && !matches("\\{\\{((?:ip)?vandal|userlinks|user-uaa)\\|", contentList.get(0), Pattern.CASE_INSENSITIVE) && !contentList.get(0).startsWith("<!--") && !contentList.get(0).startsWith("=")) { String removed = contentList.remove(0); if (!removed.isEmpty()) { linesSkipped++; inComment = Boolean.parseBoolean(AIVBot.parseComment(removed, inComment)[0]); } } } } content = Util.join("\n", newContent); if (!found || content.isEmpty()) { return; } String length = " "; if (!duration.isEmpty()) { if (duration.equals("indef")) { length = " indef "; } else { length = " " + duration; } } String tally = "Empty."; if (ipsLeft != 0 || usersLeft != 0) { String ipNote = ipsLeft + " IP" + ((ipsLeft != 1) ? "s" : ""); String userNote = usersLeft + " user" + ((usersLeft != 1) ? "s" : ""); if (usersLeft == 0) { // Only IPs left tally = ipNote + " left."; } else if (ipsLeft == 0) { // Only users left tally = userNote + " left."; } else { // Users and ips left tally = ipNote + " & " + userNote + " left."; } } String skipped = ""; if (linesSkipped > 0) { skipped = " " + linesSkipped + " comment(s) removed."; } String summary = tally + " rm [[Special:Contributions/" + user + "|" + user + "]] (blocked" + length + "by [[User:" + blocker.getUsername() + "|" + blocker.getUsername() + "]] " + blockType + "). " + skipped; if (!originalContent.equals(bot.getParent().getWiki().getPageText(page))) { XBotDebug.warn("AIV", ChatColor.BLUE + page + ChatColor.YELLOW + " has changed since we read it, not changing.", time); return; } else { bot.getParent().getWiki().doEdit(page, content, summary, false); } XBotDebug.info("AIV", ChatColor.GOLD + "Removed " + ChatColor.YELLOW + user + ChatColor.GOLD + " on " + ChatColor.BLUE + page); } } catch (IOException ex) { XBotDebug.error("AIV", "Could not read from wiki.", ex); } }
public void doRun() { try { String content = bot.getParent().getWiki().getPageText(page); String originalContent = content.toString(); Calendar time = bot.getParent().getWiki().getTimestamp(); if (!content.isEmpty()) { int ipsLeft = 0; int usersLeft = 0; boolean found = false; int linesSkipped = 0; List<String> newContent = new LinkedList<String>(); boolean inComment = false; List<String> contentList = new ArrayList<String>(Arrays.asList(content.split("\n"))); while (contentList.size() > 0) { String line = contentList.remove(0); String[] comment = AIVBot.parseComment(line, inComment); inComment = Boolean.parseBoolean(comment[0]); String bareLine = comment[1]; String remainder = comment[2]; if (inComment || !matches("\\{\\{((?:ip)?vandal|userlinks|user-uaa)\\|\\s*(?:1=|user=)?\\Q" + user + "\\E\\s*\\}\\}", line, Pattern.CASE_INSENSITIVE)) { newContent.add(line); if (inComment && line.equals(bareLine)) { continue; } if (bareLine.contains("{{IPvandal|")) { ipsLeft++; } if (matches("\\{\\{(vandal|userlinks|user-uaa)\\|", bareLine, Pattern.CASE_INSENSITIVE)) { usersLeft++; } } else { found = true; if (!remainder.isEmpty()) { newContent.add(remainder); } while (contentList.size() > 0 && !matches("\\{\\{((?:ip)?vandal|userlinks|user-uaa)\\|", contentList.get(0), Pattern.CASE_INSENSITIVE) && !contentList.get(0).startsWith("<!--") && !contentList.get(0).startsWith("=")) { String removed = contentList.remove(0); if (!removed.isEmpty()) { linesSkipped++; inComment = Boolean.parseBoolean(AIVBot.parseComment(removed, inComment)[0]); } } } } content = Util.join("\n", newContent); if (!found || content.isEmpty()) { return; } String length = " "; if (!duration.isEmpty()) { if (duration.equals("indef")) { length = " indef "; } else { length = " " + duration; } } String tally = "Empty."; if (ipsLeft != 0 || usersLeft != 0) { String ipNote = ipsLeft + " IP" + ((ipsLeft != 1) ? "s" : ""); String userNote = usersLeft + " user" + ((usersLeft != 1) ? "s" : ""); if (usersLeft == 0) { // Only IPs left tally = ipNote + " left."; } else if (ipsLeft == 0) { // Only users left tally = userNote + " left."; } else { // Users and ips left tally = ipNote + " & " + userNote + " left."; } } String skipped = ""; if (linesSkipped > 0) { skipped = " " + linesSkipped + " comment(s) removed."; } String summary = tally + " rm [[Special:Contributions/" + user + "|" + user + "]] (blocked" + length + "by [[User:" + blocker.getUsername() + "|" + blocker.getUsername() + "]] " + blockType + "). " + skipped; if (!originalContent.equals(bot.getParent().getWiki().getPageText(page))) { XBotDebug.warn("AIV", ChatColor.BLUE + page + ChatColor.YELLOW + " has changed since we read it, not changing."); return; } else { bot.getParent().getWiki().doEdit(page, content, summary, false, time); } XBotDebug.info("AIV", ChatColor.GOLD + "Removed " + ChatColor.YELLOW + user + ChatColor.GOLD + " on " + ChatColor.BLUE + page); } } catch (IOException ex) { XBotDebug.error("AIV", "Could not read from wiki.", ex); } }
diff --git a/adapters/postgres-adapter/src/main/java/org/atomhopper/postgres/adapter/PostgresFeedSource.java b/adapters/postgres-adapter/src/main/java/org/atomhopper/postgres/adapter/PostgresFeedSource.java index eb7c584a..54f3675f 100644 --- a/adapters/postgres-adapter/src/main/java/org/atomhopper/postgres/adapter/PostgresFeedSource.java +++ b/adapters/postgres-adapter/src/main/java/org/atomhopper/postgres/adapter/PostgresFeedSource.java @@ -1,416 +1,416 @@ package org.atomhopper.postgres.adapter; import org.apache.abdera.Abdera; import org.apache.abdera.model.Document; import org.apache.abdera.model.Entry; import org.apache.abdera.model.Feed; import org.apache.abdera.model.Link; import org.apache.commons.lang.StringUtils; import org.atomhopper.adapter.FeedInformation; import org.atomhopper.adapter.FeedSource; import org.atomhopper.adapter.NotImplemented; import org.atomhopper.adapter.ResponseBuilder; import org.atomhopper.adapter.request.adapter.GetEntryRequest; import org.atomhopper.adapter.request.adapter.GetFeedRequest; import org.atomhopper.dbal.PageDirection; import org.atomhopper.postgres.model.PersistedEntry; import org.atomhopper.postgres.query.CategoryStringGenerator; import org.atomhopper.postgres.query.EntryRowMapper; import org.atomhopper.response.AdapterResponse; import org.atomhopper.util.uri.template.EnumKeyedTemplateParameters; import org.atomhopper.util.uri.template.URITemplate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.core.JdbcTemplate; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.*; import static org.apache.abdera.i18n.text.UrlEncoding.decode; import static org.apache.abdera.i18n.text.UrlEncoding.encode; public class PostgresFeedSource implements FeedSource { private static final Logger LOG = LoggerFactory.getLogger( PostgresFeedSource.class); private static final String MARKER_EQ = "?marker="; private static final String LIMIT_EQ = "?limit="; private static final String AND_SEARCH_EQ = "&search="; private static final String AND_LIMIT_EQ = "&limit="; private static final String AND_MARKER_EQ = "&marker="; private static final String AND_DIRECTION_EQ = "&direction="; private static final String AND_DIRECTION_EQ_BACKWARD = "&direction=backward"; private static final String AND_DIRECTION_EQ_FORWARD = "&direction=forward"; private static final int PAGE_SIZE = 25; private JdbcTemplate jdbcTemplate; public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @Override @NotImplemented public void setParameters(Map<String, String> params) { throw new UnsupportedOperationException("Not supported yet."); } private void addFeedSelfLink(Feed feed, final String baseFeedUri, final GetFeedRequest getFeedRequest, final int pageSize, final String searchString) { StringBuilder queryParams = new StringBuilder(); boolean markerIsSet = false; queryParams.append(baseFeedUri).append(LIMIT_EQ).append( String.valueOf(pageSize)); if (searchString.length() > 0) { queryParams.append(AND_SEARCH_EQ).append(encode(searchString)); } if (getFeedRequest.getPageMarker() != null && getFeedRequest.getPageMarker().length() > 0) { queryParams.append(AND_MARKER_EQ).append(getFeedRequest.getPageMarker()); markerIsSet = true; } if (markerIsSet) { queryParams.append(AND_DIRECTION_EQ).append(getFeedRequest.getDirection()); } else { queryParams.append(AND_DIRECTION_EQ_BACKWARD); if (queryParams.toString().equalsIgnoreCase( baseFeedUri + LIMIT_EQ + "25" + AND_DIRECTION_EQ_BACKWARD)) { // They are calling the feedhead, just use the base feed uri // This keeps the validator at http://validator.w3.org/ happy queryParams.delete(0, queryParams.toString().length()).append( baseFeedUri); } } feed.addLink(queryParams.toString()).setRel(Link.REL_SELF); } private void addFeedCurrentLink(Feed hyrdatedFeed, final String baseFeedUri) { hyrdatedFeed.addLink(baseFeedUri, Link.REL_CURRENT); } private Feed hydrateFeed(Abdera abdera, List<PersistedEntry> persistedEntries, GetFeedRequest getFeedRequest, final int pageSize) { final Feed hyrdatedFeed = abdera.newFeed(); final String uuidUriScheme = "urn:uuid:"; final String baseFeedUri = decode(getFeedRequest.urlFor( new EnumKeyedTemplateParameters<URITemplate>(URITemplate.FEED))); final String searchString = getFeedRequest.getSearchQuery() != null ? getFeedRequest.getSearchQuery() : ""; // Set the feed links addFeedCurrentLink(hyrdatedFeed, baseFeedUri); addFeedSelfLink(hyrdatedFeed, baseFeedUri, getFeedRequest, pageSize, searchString); // TODO: We should have a link builder method for these if (!(persistedEntries.isEmpty())) { hyrdatedFeed.setId(uuidUriScheme + UUID.randomUUID().toString()); hyrdatedFeed.setTitle(persistedEntries.get(0).getFeed()); // Set the previous link hyrdatedFeed.addLink(new StringBuilder() .append(baseFeedUri).append(MARKER_EQ) .append(persistedEntries.get(0).getEntryId()) .append(AND_LIMIT_EQ).append(String.valueOf(pageSize)) .append(AND_SEARCH_EQ).append(urlEncode(searchString)) .append(AND_DIRECTION_EQ_FORWARD).toString()) .setRel(Link.REL_PREVIOUS); final PersistedEntry lastEntryInCollection = persistedEntries.get(persistedEntries.size() - 1); PersistedEntry nextEntry = getNextMarker(lastEntryInCollection, getFeedRequest.getFeedName(), searchString); if (nextEntry != null) { // Set the next link hyrdatedFeed.addLink(new StringBuilder().append(baseFeedUri) .append(MARKER_EQ).append(nextEntry.getEntryId()) .append(AND_LIMIT_EQ).append(String.valueOf(pageSize)) .append(AND_SEARCH_EQ).append(urlEncode(searchString)) .append(AND_DIRECTION_EQ_BACKWARD).toString()) .setRel(Link.REL_NEXT); } } for (PersistedEntry persistedFeedEntry : persistedEntries) { hyrdatedFeed.addEntry(hydrateEntry(persistedFeedEntry, abdera)); } return hyrdatedFeed; } private Entry hydrateEntry(PersistedEntry persistedEntry, Abdera abderaReference) { final Document<Entry> hydratedEntryDocument = abderaReference.getParser().parse( new StringReader(persistedEntry.getEntryBody())); Entry entry = null; if (hydratedEntryDocument != null) { entry = hydratedEntryDocument.getRoot(); entry.setUpdated(persistedEntry.getDateLastUpdated()); entry.setPublished(persistedEntry.getCreationDate()); } return entry; } @Override public AdapterResponse<Entry> getEntry(GetEntryRequest getEntryRequest) { final PersistedEntry entry = getEntry(getEntryRequest.getEntryId(), getEntryRequest.getFeedName()); AdapterResponse<Entry> response = ResponseBuilder.notFound(); if (entry != null) { response = ResponseBuilder.found(hydrateEntry(entry, getEntryRequest.getAbdera())); } return response; } @Override public AdapterResponse<Feed> getFeed(GetFeedRequest getFeedRequest) { AdapterResponse<Feed> response; int pageSize = PAGE_SIZE; final String pageSizeString = getFeedRequest.getPageSize(); if (StringUtils.isNotBlank(pageSizeString)) { pageSize = Integer.parseInt(pageSizeString); } final String marker = getFeedRequest.getPageMarker(); if (StringUtils.isNotBlank(marker)) { response = getFeedPage(getFeedRequest, marker, pageSize); } else { response = getFeedHead(getFeedRequest, pageSize); } return response; } private AdapterResponse<Feed> getFeedHead(GetFeedRequest getFeedRequest, int pageSize) { final Abdera abdera = getFeedRequest.getAbdera(); final String searchString = getFeedRequest.getSearchQuery() != null ? getFeedRequest.getSearchQuery() : ""; List<PersistedEntry> persistedEntries = getFeedHead(getFeedRequest.getFeedName(), pageSize, searchString); Feed hyrdatedFeed = hydrateFeed(abdera, persistedEntries, getFeedRequest, pageSize); // Set the last link in the feed head final String baseFeedUri = decode(getFeedRequest.urlFor( new EnumKeyedTemplateParameters<URITemplate>(URITemplate.FEED))); int totalFeedEntryCount = getFeedCount(getFeedRequest.getFeedName(), searchString); int lastPageSize = totalFeedEntryCount % pageSize; if (lastPageSize == 0) { lastPageSize = pageSize; } List<PersistedEntry> lastPersistedEntries = getLastPage(getFeedRequest.getFeedName(), lastPageSize, searchString); if (lastPersistedEntries != null && !(lastPersistedEntries.isEmpty())) { hyrdatedFeed.addLink( new StringBuilder().append(baseFeedUri) .append(MARKER_EQ).append( lastPersistedEntries.get(lastPersistedEntries.size() - 1).getEntryId()) .append(AND_LIMIT_EQ).append(String.valueOf(pageSize)) .append(AND_SEARCH_EQ).append(urlEncode(searchString)) .append(AND_DIRECTION_EQ_BACKWARD).toString()) .setRel(Link.REL_LAST); } return ResponseBuilder.found(hyrdatedFeed); } private AdapterResponse<Feed> getFeedPage(GetFeedRequest getFeedRequest, String marker, int pageSize) { AdapterResponse<Feed> response; PageDirection pageDirection; try { final String pageDirectionValue = getFeedRequest.getDirection(); pageDirection = PageDirection.valueOf(pageDirectionValue.toUpperCase()); } catch (Exception iae) { LOG.warn("Marker must have a page direction specified as either \"forward\" or \"backward\""); return ResponseBuilder.badRequest( "Marker must have a page direction specified as either \"forward\" or \"backward\""); } final PersistedEntry markerEntry = getEntry(marker, getFeedRequest.getFeedName()); if (markerEntry != null) { final String searchString = getFeedRequest.getSearchQuery() != null ? getFeedRequest.getSearchQuery() : ""; final Feed feed = hydrateFeed(getFeedRequest.getAbdera(), enhancedGetFeedPage(getFeedRequest.getFeedName(), markerEntry, pageDirection, searchString, pageSize), getFeedRequest, pageSize); response = ResponseBuilder.found(feed); } else { response = ResponseBuilder.notFound( "No entry with specified marker found"); } return response; } @Override public FeedInformation getFeedInformation() { throw new UnsupportedOperationException("Not supported yet."); } private List<PersistedEntry> enhancedGetFeedPage(final String feedName, final PersistedEntry markerEntry, final PageDirection direction, final String searchString, final int pageSize) { List<PersistedEntry> feedPage = new LinkedList<PersistedEntry>(); switch (direction) { case FORWARD: final String forwardSQL = "SELECT * FROM entries WHERE feed = ? AND datelastupdated >= ? ORDER BY datelastupdated ASC, entryid ASC LIMIT ? OFFSET 1"; final String forwardWithCatsSQL = "SELECT * FROM entries WHERE feed = ? AND datelastupdated >= ? AND categories && ?::varchar[] ORDER BY datelastupdated ASC, entryid ASC LIMIT ? OFFSET 1"; if (searchString.length() > 0) { feedPage = jdbcTemplate .query(forwardWithCatsSQL, - new Object[]{feedName, markerEntry.getCreationDate(), + new Object[]{feedName, markerEntry.getDateLastUpdated(), CategoryStringGenerator.getPostgresCategoryString(searchString), pageSize}, new EntryRowMapper()); } else { feedPage = jdbcTemplate .query(forwardSQL, - new Object[]{feedName, markerEntry.getCreationDate(), pageSize}, + new Object[]{feedName, markerEntry.getDateLastUpdated(), pageSize}, new EntryRowMapper()); } Collections.reverse(feedPage); break; case BACKWARD: final String backwardSQL = "SELECT * FROM entries WHERE feed = ? AND datelastupdated <= ? ORDER BY datelastupdated DESC, entryid DESC LIMIT ?"; final String backwardWithCatsSQL = "SELECT * FROM entries WHERE feed = ? AND datelastupdated <= ? AND categories && ?::varchar[] ORDER BY datelastupdated DESC, entryid DESC LIMIT ?"; if (searchString.length() > 0) { feedPage = jdbcTemplate .query(backwardWithCatsSQL, - new Object[]{feedName, markerEntry.getCreationDate(), + new Object[]{feedName, markerEntry.getDateLastUpdated(), CategoryStringGenerator.getPostgresCategoryString(searchString), pageSize}, new EntryRowMapper()); } else { feedPage = jdbcTemplate .query(backwardSQL, - new Object[]{feedName, markerEntry.getCreationDate(), pageSize}, + new Object[]{feedName, markerEntry.getDateLastUpdated(), pageSize}, new EntryRowMapper()); } break; } return feedPage; } private PersistedEntry getEntry(final String entryId, final String feedName) { final String entrySQL = "SELECT * FROM entries WHERE feed = ? AND entryid = ?"; List<PersistedEntry> entry = jdbcTemplate .query(entrySQL, new Object[]{feedName, entryId}, new EntryRowMapper()); return entry.size() > 0 ? entry.get(0) : null; } private Integer getFeedCount(final String feedName, final String searchString) { final String totalFeedEntryCountSQL = "SELECT COUNT(*) FROM entries WHERE feed = ?"; final String totalFeedEntryCountWithCatsSQL = "SELECT COUNT(*) FROM entries WHERE feed = ? AND categories && ?::varchar[]"; int totalFeedEntryCount; if (searchString.length() > 0) { totalFeedEntryCount = jdbcTemplate .queryForInt(totalFeedEntryCountWithCatsSQL, feedName, CategoryStringGenerator.getPostgresCategoryString(searchString)); } else { totalFeedEntryCount = jdbcTemplate .queryForInt(totalFeedEntryCountSQL, feedName); } return totalFeedEntryCount; } private List<PersistedEntry> getFeedHead(final String feedName, final int pageSize, final String searchString) { final String getFeedHeadSQL = "SELECT * FROM entries WHERE feed = ? ORDER BY datelastupdated DESC, entryid DESC LIMIT ?"; final String getFeedHeadWithCatsSQL = "SELECT * FROM entries WHERE feed = ? AND categories && ?::varchar[] ORDER BY datelastupdated DESC, entryid DESC LIMIT ?"; List<PersistedEntry> persistedEntries; if (searchString.length() > 0) { persistedEntries = jdbcTemplate .query(getFeedHeadWithCatsSQL, new Object[]{feedName, CategoryStringGenerator.getPostgresCategoryString(searchString), pageSize}, new EntryRowMapper()); } else { persistedEntries = jdbcTemplate .query(getFeedHeadSQL, new Object[]{feedName, pageSize}, new EntryRowMapper()); } return persistedEntries; } private List<PersistedEntry> getLastPage(final String feedName, final int pageSize, final String searchString) { final String lastLinkQuerySQL = "SELECT * FROM entries WHERE feed = ? ORDER BY datelastupdated ASC, entryid ASC LIMIT ?"; final String lastLinkQueryWithCatsSQL = "SELECT * FROM entries WHERE feed = ? AND categories && ?::varchar[] ORDER BY datelastupdated ASC, entryid ASC LIMIT ?"; List<PersistedEntry> lastPersistedEntries; if (searchString.length() > 0) { lastPersistedEntries = jdbcTemplate .query(lastLinkQueryWithCatsSQL, new Object[]{feedName, CategoryStringGenerator.getPostgresCategoryString(searchString), pageSize}, new EntryRowMapper()); } else { lastPersistedEntries = jdbcTemplate .query(lastLinkQuerySQL, new Object[]{feedName, pageSize}, new EntryRowMapper()); } return lastPersistedEntries; } private PersistedEntry getNextMarker(final PersistedEntry persistedEntry, final String feedName, final String searchString) { final String nextLinkSQL = "SELECT * FROM entries where feed = ? and datelastupdated <= ? ORDER BY datelastupdated DESC, entryid DESC LIMIT 1 OFFSET 1"; final String nextLinkWithCatsSQL = "SELECT * FROM entries where feed = ? and datelastupdated <= ? AND categories && ?::varchar[] ORDER BY datelastupdated DESC, entryid DESC LIMIT 1 OFFSET 1"; List<PersistedEntry> nextEntry; if (searchString.length() > 0) { nextEntry = jdbcTemplate .query(nextLinkWithCatsSQL, new Object[]{feedName, persistedEntry.getDateLastUpdated(), CategoryStringGenerator.getPostgresCategoryString(searchString)}, new EntryRowMapper()); } else { nextEntry = jdbcTemplate .query(nextLinkSQL, new Object[]{feedName, persistedEntry.getDateLastUpdated()}, new EntryRowMapper()); } return nextEntry.size() > 0 ? nextEntry.get(0) : null; } private String urlEncode(String searchString) { try { return URLEncoder.encode(searchString, "UTF-8"); } catch (UnsupportedEncodingException e) { //noop - should never get here return ""; } } }
false
true
private List<PersistedEntry> enhancedGetFeedPage(final String feedName, final PersistedEntry markerEntry, final PageDirection direction, final String searchString, final int pageSize) { List<PersistedEntry> feedPage = new LinkedList<PersistedEntry>(); switch (direction) { case FORWARD: final String forwardSQL = "SELECT * FROM entries WHERE feed = ? AND datelastupdated >= ? ORDER BY datelastupdated ASC, entryid ASC LIMIT ? OFFSET 1"; final String forwardWithCatsSQL = "SELECT * FROM entries WHERE feed = ? AND datelastupdated >= ? AND categories && ?::varchar[] ORDER BY datelastupdated ASC, entryid ASC LIMIT ? OFFSET 1"; if (searchString.length() > 0) { feedPage = jdbcTemplate .query(forwardWithCatsSQL, new Object[]{feedName, markerEntry.getCreationDate(), CategoryStringGenerator.getPostgresCategoryString(searchString), pageSize}, new EntryRowMapper()); } else { feedPage = jdbcTemplate .query(forwardSQL, new Object[]{feedName, markerEntry.getCreationDate(), pageSize}, new EntryRowMapper()); } Collections.reverse(feedPage); break; case BACKWARD: final String backwardSQL = "SELECT * FROM entries WHERE feed = ? AND datelastupdated <= ? ORDER BY datelastupdated DESC, entryid DESC LIMIT ?"; final String backwardWithCatsSQL = "SELECT * FROM entries WHERE feed = ? AND datelastupdated <= ? AND categories && ?::varchar[] ORDER BY datelastupdated DESC, entryid DESC LIMIT ?"; if (searchString.length() > 0) { feedPage = jdbcTemplate .query(backwardWithCatsSQL, new Object[]{feedName, markerEntry.getCreationDate(), CategoryStringGenerator.getPostgresCategoryString(searchString), pageSize}, new EntryRowMapper()); } else { feedPage = jdbcTemplate .query(backwardSQL, new Object[]{feedName, markerEntry.getCreationDate(), pageSize}, new EntryRowMapper()); } break; } return feedPage; }
private List<PersistedEntry> enhancedGetFeedPage(final String feedName, final PersistedEntry markerEntry, final PageDirection direction, final String searchString, final int pageSize) { List<PersistedEntry> feedPage = new LinkedList<PersistedEntry>(); switch (direction) { case FORWARD: final String forwardSQL = "SELECT * FROM entries WHERE feed = ? AND datelastupdated >= ? ORDER BY datelastupdated ASC, entryid ASC LIMIT ? OFFSET 1"; final String forwardWithCatsSQL = "SELECT * FROM entries WHERE feed = ? AND datelastupdated >= ? AND categories && ?::varchar[] ORDER BY datelastupdated ASC, entryid ASC LIMIT ? OFFSET 1"; if (searchString.length() > 0) { feedPage = jdbcTemplate .query(forwardWithCatsSQL, new Object[]{feedName, markerEntry.getDateLastUpdated(), CategoryStringGenerator.getPostgresCategoryString(searchString), pageSize}, new EntryRowMapper()); } else { feedPage = jdbcTemplate .query(forwardSQL, new Object[]{feedName, markerEntry.getDateLastUpdated(), pageSize}, new EntryRowMapper()); } Collections.reverse(feedPage); break; case BACKWARD: final String backwardSQL = "SELECT * FROM entries WHERE feed = ? AND datelastupdated <= ? ORDER BY datelastupdated DESC, entryid DESC LIMIT ?"; final String backwardWithCatsSQL = "SELECT * FROM entries WHERE feed = ? AND datelastupdated <= ? AND categories && ?::varchar[] ORDER BY datelastupdated DESC, entryid DESC LIMIT ?"; if (searchString.length() > 0) { feedPage = jdbcTemplate .query(backwardWithCatsSQL, new Object[]{feedName, markerEntry.getDateLastUpdated(), CategoryStringGenerator.getPostgresCategoryString(searchString), pageSize}, new EntryRowMapper()); } else { feedPage = jdbcTemplate .query(backwardSQL, new Object[]{feedName, markerEntry.getDateLastUpdated(), pageSize}, new EntryRowMapper()); } break; } return feedPage; }
diff --git a/src/main/java/net/canarymod/commandsys/CommandManager.java b/src/main/java/net/canarymod/commandsys/CommandManager.java index 9a1247a..ac33e8a 100644 --- a/src/main/java/net/canarymod/commandsys/CommandManager.java +++ b/src/main/java/net/canarymod/commandsys/CommandManager.java @@ -1,473 +1,474 @@ package net.canarymod.commandsys; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import net.canarymod.Canary; import net.canarymod.Translator; import net.canarymod.chat.MessageReceiver; import net.visualillusionsent.utils.LocaleHelper; /** * Manages all commands. * Add commands using one of the methods below. * * @author Willem (l4mRh4X0r) * @author Chris (damagefilter) */ public class CommandManager { HashMap<String, CanaryCommand> commands = new HashMap<String, CanaryCommand>(); /** * Remove a command from the command list. * * @param name * the name of the command * * @return <tt>true</tt> if the command was removed, <tt>false</tt> otherwise. */ public boolean unregisterCommand(String name) { if (name == null) { return false; } String[] commandchain = name.split("\\."); CanaryCommand temp = null; for (int i = 0; i < commandchain.length; i++) { if (i == 0) { temp = commands.get(commandchain[i]); } else { if (temp == null) { break; } if (temp.hasSubCommand(commandchain[i])) { temp = temp.getSubCommand(commandchain[i]); } else { temp = null; break; } } } if (temp == null) { return false; } else { if (!temp.meta.helpLookup().isEmpty() && Canary.help().hasHelp(temp.meta.helpLookup())) { Canary.help().unregisterCommand(temp.owner, temp.meta.helpLookup()); } else { Canary.help().unregisterCommand(temp.owner, temp.meta.aliases()[0]); } if (temp.getParent() != null) { temp.getParent().removeSubCommand(temp); return true; } else { for (int i = 0; i < temp.meta.aliases().length; i++) { commands.remove(temp.meta.aliases()[i].toLowerCase()); } return true; } } } /** * Remove all commands that belong to the specified command owner. * * @param owner * The owner. That can be a plugin or the server */ public void unregisterCommands(CommandOwner owner) { if (owner == null) { return; } Iterator<String> itr = commands.keySet().iterator(); while (itr.hasNext()) { String entry = itr.next(); CanaryCommand cmd = commands.get(entry); if (cmd.owner.getName().equals(owner.getName())) { itr.remove(); } } Canary.help().unregisterCommands(owner); } /** * Checks whether this manager has <tt>command</tt>. * * @param command * The command to search for. * * @return <tt>true</tt> if this manager has <tt>command</tt>, <tt>false</tt> otherwise. */ public boolean hasCommand(String command) { return commands.containsKey(command.toLowerCase()); } public boolean canUseCommand(MessageReceiver user, String command) { CanaryCommand cmd = commands.get(command); return cmd != null && cmd.canUse(user); } /** * Performs a lookup for a command of the given name and executes it if * found. Returns false if the command wasn't found or if the caller doesn't * have the permission to run it. <br> * In Short: Use this to fire commands. * * @param command * The command to run * @param caller * The {@link MessageReceiver} to send messages back to * (assumed to be the caller) * @param args * The arguments to {@code command} (including {@code command}) * * @return true if {@code command} executed successfully, false otherwise */ public boolean parseCommand(MessageReceiver caller, String command, String[] args) { CanaryCommand baseCommand = commands.get(command.toLowerCase()); CanaryCommand subCommand = null; if (baseCommand == null) { return false; } // Parse args to find sub-command if there are any. int argumentIndex = 0; // Index from which we should truncate args array CanaryCommand tmp = null; for (int i = 0; i < args.length; ++i) { if (i + 1 >= args.length) { break; } if (i == 0) { tmp = baseCommand.getSubCommand(args[1]); if (tmp != null) { subCommand = tmp; ++argumentIndex; } continue; } if (tmp != null) { if (tmp.hasSubCommand(args[i + 1])) { tmp = tmp.getSubCommand(args[i + 1]); ++argumentIndex; } if (argumentIndex >= args.length) { // Clearly some invalid crazy thing argumentIndex = args.length - 1; break; } if (subCommand != tmp) { subCommand = tmp; } } } if (subCommand == null) { return baseCommand.parseCommand(caller, args); } return subCommand.parseCommand(caller, Arrays.copyOfRange(args, argumentIndex, args.length)); } public void registerCommands(final CommandListener listener, CommandOwner owner, boolean force) throws CommandDependencyException { registerCommands(listener, owner, Translator.getInstance(), force); } /** * Register an already implemented CanaryCommand to the help system. * This will automatically update the help system as well. * * @param com * the command to register * @param owner * the owner of the command * @param force * force overriding * * @throws CommandDependencyException */ public void registerCommand(CanaryCommand com, CommandOwner owner, boolean force) throws CommandDependencyException { // Check for dependencies if (!com.meta.parent().isEmpty()) { CanaryCommand temp = null; boolean depMissing = true; String[] parentchain = com.meta.parent().split("\\."); for (int i = 0; i < parentchain.length; i++) { if (i == 0) { temp = commands.get(parentchain[i]); } else { if (temp == null) { break; } if (temp.hasSubCommand(parentchain[i])) { temp = temp.getSubCommand(parentchain[i]); } else { temp = null; break; } } } if (temp != null) { com.setParent(temp); depMissing = false; } if (depMissing) { throw new CommandDependencyException(com.meta.aliases()[0] + " has an unsatisfied dependency, " + "( " + com.meta.parent() + " )" + "please adjust registration order of your listeners or fix your plugins dependencies"); } } // KDone. Lets update commands list boolean hasDuplicate = false; StringBuilder dupes = new StringBuilder(); for (String alias : com.meta.aliases()) { boolean currentIsDupe = false; if (commands.containsKey(alias.toLowerCase()) && com.meta.parent().isEmpty() && !force) { hasDuplicate = true; currentIsDupe = true; dupes.append(alias).append(" "); } if (!currentIsDupe || (currentIsDupe && force)) { if (com.meta.parent().isEmpty()) { // Only add root commands commands.put(alias.toLowerCase(), com); } if (!com.meta.helpLookup().isEmpty() && !Canary.help().hasHelp(com.meta.helpLookup())) { Canary.help().registerCommand(owner, com, com.meta.helpLookup()); } else { Canary.help().registerCommand(owner, com); } } } if (hasDuplicate && !force) { throw new DuplicateCommandException(dupes.toString()); } } /** * Register your CommandListener. * This will make all annotated commands available to CanaryMod and the help system. * Sub Command relations can only be sorted out after availability. * That means if you try to register a command that is a sub-command of something * that is not registered yet, it will fail. * So make sure you add commands in the correct order. * * @param listener * the {@link CommandListener} * @param owner * the {@link CommandOwner} * @param translator * the {@link LocaleHelper} instance used in Translations * @param force * {@code true} to override existing commands; {@code false} for not * * @throws CommandDependencyException */ public void registerCommands(final CommandListener listener, CommandOwner owner, LocaleHelper translator, boolean force) throws CommandDependencyException { Method[] methods = listener.getClass().getDeclaredMethods(); - ArrayList<CanaryCommand> loadedCommands = new ArrayList<CanaryCommand>(); + ArrayList<CanaryCommand> newCommands = new ArrayList<CanaryCommand>(); for (final Method method : methods) { if (!method.isAnnotationPresent(Command.class)) { continue; } Class<?>[] params = method.getParameterTypes(); if (params.length != 2) { Canary.logWarning("You have a Command method with invalid number of arguments! - " + method.getName()); continue; } if (!(MessageReceiver.class.isAssignableFrom(params[0]) && String[].class.isAssignableFrom(params[1]))) { Canary.logWarning("You have a Command method with invalid argument types! - " + method.getName()); continue; } Command meta = method.getAnnotation(Command.class); CanaryCommand command = new CanaryCommand(meta, owner, translator) { @Override protected void execute(MessageReceiver caller, String[] parameters) { try { method.invoke(listener, new Object[]{ caller, parameters }); } catch (Exception ex) { Canary.logStacktrace("Could not execute command...", ex.getCause()); } } }; - loadedCommands.add(command); + newCommands.add(command); } // Sort load order so dependencies can be resolved properly - Collections.sort(loadedCommands); + Collections.sort(newCommands); // Take care of parenting - for (CanaryCommand cmd : loadedCommands) { + for (CanaryCommand cmd : newCommands) { if (cmd.meta.parent().isEmpty()) { continue; } String[] cmdp = cmd.meta.parent().split("\\."); boolean depMissing = true; // Check for local dependencies - for (CanaryCommand parent : loadedCommands) { + for (CanaryCommand parent : newCommands) { CanaryCommand tmp = null; for (int i = 0; i < cmdp.length; i++) { if (i == 0) { for (String palias : parent.meta.aliases()) { if (palias.equals(cmdp[i])) { tmp = parent; } } } else { + //First element wasn't found. Get out. if (tmp == null) { break; } if (tmp.hasSubCommand(cmdp[i])) { tmp = tmp.getSubCommand(cmdp[i]); } else { tmp = null; break; } } } if (tmp != null) { cmd.setParent(tmp); depMissing = false; } } // Check for remote dependencies - if (!depMissing) { // checking if it had found a local first + if (depMissing) { // checking if it had found a local first CanaryCommand temp = null; for (int i = 0; i < cmdp.length; i++) { if (i == 0) { temp = commands.get(cmdp); } else { if (temp == null) { break; } if (temp.hasSubCommand(cmdp[i])) { temp = temp.getSubCommand(cmdp[i]); } else { temp = null; break; } } } if (temp != null) { cmd.setParent(temp); depMissing = false; } } // Throw Error if we did not find the Dependency if (depMissing) { throw new CommandDependencyException(cmd.meta.aliases()[0] + " has an unsatisfied dependency, " + "( " + cmd.meta.parent() + " )" + "please adjust registration order of your listeners or fix your plugins dependencies"); } } // KDone. Lets update commands list boolean hasDuplicate = false; StringBuilder dupes = new StringBuilder(); - for (CanaryCommand cmd : loadedCommands) { + for (CanaryCommand cmd : newCommands) { for (String alias : cmd.meta.aliases()) { boolean currentIsDupe = false; if (commands.containsKey(alias.toLowerCase()) && cmd.meta.parent().isEmpty() && !force) { hasDuplicate = true; currentIsDupe = true; dupes.append(alias).append(" "); } if (!currentIsDupe || (currentIsDupe && force)) { if (cmd.meta.parent().isEmpty()) { // Only add root commands commands.put(alias.toLowerCase(), cmd); } if (!cmd.meta.helpLookup().isEmpty() && !Canary.help().hasHelp(cmd.meta.helpLookup())) { Canary.help().registerCommand(owner, cmd, cmd.meta.helpLookup()); } else { Canary.help().registerCommand(owner, cmd); } } } } if (hasDuplicate && !force) { throw new DuplicateCommandException(dupes.toString()); } } /** * Build a list of commands matching the given string. * * @param caller * the {@link MessageReceiver} * @param command * the command name * * @return nullchar separated stringbuilder */ public StringBuilder matchCommand(MessageReceiver caller, String command, boolean onlySubcommands) { int matches = 0; int maxMatches = 4; StringBuilder matching = new StringBuilder(); command = command.toLowerCase(); // Match base commands for (String key : commands.keySet()) { if (!onlySubcommands) { if (key.toLowerCase().equals(command)) { // Perfect match if (matching.indexOf("/".concat(key)) == -1) { if (commands.get(key).canUse(caller) && matches <= maxMatches) { ++matches; matching.append("/").append(key).append("\u0000"); } } } else if (key.toLowerCase().startsWith(command)) { // Partial match if (matching.indexOf("/".concat(key)) == -1) { if (commands.get(key).canUse(caller) && matches <= maxMatches) { ++matches; matching.append("/").append(key).append("\u0000"); } } } } // Match sub commands for (CanaryCommand cmd : commands.get(key).getSubCommands(new ArrayList<CanaryCommand>())) { for (String alias : cmd.meta.aliases()) { if (alias.toLowerCase().equals(command)) { // full match if (matching.indexOf(alias) == -1) { if (cmd.canUse(caller) && matches <= maxMatches) { ++matches; matching.append(alias).append("\u0000"); } } } else if (alias.toLowerCase().startsWith(command)) { // partial match if (matching.indexOf(alias) == -1) { if (cmd.canUse(caller) && matches <= maxMatches) { ++matches; matching.append(alias).append("\u0000"); } } } } } } return matching; } }
false
true
public void registerCommands(final CommandListener listener, CommandOwner owner, LocaleHelper translator, boolean force) throws CommandDependencyException { Method[] methods = listener.getClass().getDeclaredMethods(); ArrayList<CanaryCommand> loadedCommands = new ArrayList<CanaryCommand>(); for (final Method method : methods) { if (!method.isAnnotationPresent(Command.class)) { continue; } Class<?>[] params = method.getParameterTypes(); if (params.length != 2) { Canary.logWarning("You have a Command method with invalid number of arguments! - " + method.getName()); continue; } if (!(MessageReceiver.class.isAssignableFrom(params[0]) && String[].class.isAssignableFrom(params[1]))) { Canary.logWarning("You have a Command method with invalid argument types! - " + method.getName()); continue; } Command meta = method.getAnnotation(Command.class); CanaryCommand command = new CanaryCommand(meta, owner, translator) { @Override protected void execute(MessageReceiver caller, String[] parameters) { try { method.invoke(listener, new Object[]{ caller, parameters }); } catch (Exception ex) { Canary.logStacktrace("Could not execute command...", ex.getCause()); } } }; loadedCommands.add(command); } // Sort load order so dependencies can be resolved properly Collections.sort(loadedCommands); // Take care of parenting for (CanaryCommand cmd : loadedCommands) { if (cmd.meta.parent().isEmpty()) { continue; } String[] cmdp = cmd.meta.parent().split("\\."); boolean depMissing = true; // Check for local dependencies for (CanaryCommand parent : loadedCommands) { CanaryCommand tmp = null; for (int i = 0; i < cmdp.length; i++) { if (i == 0) { for (String palias : parent.meta.aliases()) { if (palias.equals(cmdp[i])) { tmp = parent; } } } else { if (tmp == null) { break; } if (tmp.hasSubCommand(cmdp[i])) { tmp = tmp.getSubCommand(cmdp[i]); } else { tmp = null; break; } } } if (tmp != null) { cmd.setParent(tmp); depMissing = false; } } // Check for remote dependencies if (!depMissing) { // checking if it had found a local first CanaryCommand temp = null; for (int i = 0; i < cmdp.length; i++) { if (i == 0) { temp = commands.get(cmdp); } else { if (temp == null) { break; } if (temp.hasSubCommand(cmdp[i])) { temp = temp.getSubCommand(cmdp[i]); } else { temp = null; break; } } } if (temp != null) { cmd.setParent(temp); depMissing = false; } } // Throw Error if we did not find the Dependency if (depMissing) { throw new CommandDependencyException(cmd.meta.aliases()[0] + " has an unsatisfied dependency, " + "( " + cmd.meta.parent() + " )" + "please adjust registration order of your listeners or fix your plugins dependencies"); } } // KDone. Lets update commands list boolean hasDuplicate = false; StringBuilder dupes = new StringBuilder(); for (CanaryCommand cmd : loadedCommands) { for (String alias : cmd.meta.aliases()) { boolean currentIsDupe = false; if (commands.containsKey(alias.toLowerCase()) && cmd.meta.parent().isEmpty() && !force) { hasDuplicate = true; currentIsDupe = true; dupes.append(alias).append(" "); } if (!currentIsDupe || (currentIsDupe && force)) { if (cmd.meta.parent().isEmpty()) { // Only add root commands commands.put(alias.toLowerCase(), cmd); } if (!cmd.meta.helpLookup().isEmpty() && !Canary.help().hasHelp(cmd.meta.helpLookup())) { Canary.help().registerCommand(owner, cmd, cmd.meta.helpLookup()); } else { Canary.help().registerCommand(owner, cmd); } } } } if (hasDuplicate && !force) { throw new DuplicateCommandException(dupes.toString()); } }
public void registerCommands(final CommandListener listener, CommandOwner owner, LocaleHelper translator, boolean force) throws CommandDependencyException { Method[] methods = listener.getClass().getDeclaredMethods(); ArrayList<CanaryCommand> newCommands = new ArrayList<CanaryCommand>(); for (final Method method : methods) { if (!method.isAnnotationPresent(Command.class)) { continue; } Class<?>[] params = method.getParameterTypes(); if (params.length != 2) { Canary.logWarning("You have a Command method with invalid number of arguments! - " + method.getName()); continue; } if (!(MessageReceiver.class.isAssignableFrom(params[0]) && String[].class.isAssignableFrom(params[1]))) { Canary.logWarning("You have a Command method with invalid argument types! - " + method.getName()); continue; } Command meta = method.getAnnotation(Command.class); CanaryCommand command = new CanaryCommand(meta, owner, translator) { @Override protected void execute(MessageReceiver caller, String[] parameters) { try { method.invoke(listener, new Object[]{ caller, parameters }); } catch (Exception ex) { Canary.logStacktrace("Could not execute command...", ex.getCause()); } } }; newCommands.add(command); } // Sort load order so dependencies can be resolved properly Collections.sort(newCommands); // Take care of parenting for (CanaryCommand cmd : newCommands) { if (cmd.meta.parent().isEmpty()) { continue; } String[] cmdp = cmd.meta.parent().split("\\."); boolean depMissing = true; // Check for local dependencies for (CanaryCommand parent : newCommands) { CanaryCommand tmp = null; for (int i = 0; i < cmdp.length; i++) { if (i == 0) { for (String palias : parent.meta.aliases()) { if (palias.equals(cmdp[i])) { tmp = parent; } } } else { //First element wasn't found. Get out. if (tmp == null) { break; } if (tmp.hasSubCommand(cmdp[i])) { tmp = tmp.getSubCommand(cmdp[i]); } else { tmp = null; break; } } } if (tmp != null) { cmd.setParent(tmp); depMissing = false; } } // Check for remote dependencies if (depMissing) { // checking if it had found a local first CanaryCommand temp = null; for (int i = 0; i < cmdp.length; i++) { if (i == 0) { temp = commands.get(cmdp); } else { if (temp == null) { break; } if (temp.hasSubCommand(cmdp[i])) { temp = temp.getSubCommand(cmdp[i]); } else { temp = null; break; } } } if (temp != null) { cmd.setParent(temp); depMissing = false; } } // Throw Error if we did not find the Dependency if (depMissing) { throw new CommandDependencyException(cmd.meta.aliases()[0] + " has an unsatisfied dependency, " + "( " + cmd.meta.parent() + " )" + "please adjust registration order of your listeners or fix your plugins dependencies"); } } // KDone. Lets update commands list boolean hasDuplicate = false; StringBuilder dupes = new StringBuilder(); for (CanaryCommand cmd : newCommands) { for (String alias : cmd.meta.aliases()) { boolean currentIsDupe = false; if (commands.containsKey(alias.toLowerCase()) && cmd.meta.parent().isEmpty() && !force) { hasDuplicate = true; currentIsDupe = true; dupes.append(alias).append(" "); } if (!currentIsDupe || (currentIsDupe && force)) { if (cmd.meta.parent().isEmpty()) { // Only add root commands commands.put(alias.toLowerCase(), cmd); } if (!cmd.meta.helpLookup().isEmpty() && !Canary.help().hasHelp(cmd.meta.helpLookup())) { Canary.help().registerCommand(owner, cmd, cmd.meta.helpLookup()); } else { Canary.help().registerCommand(owner, cmd); } } } } if (hasDuplicate && !force) { throw new DuplicateCommandException(dupes.toString()); } }
diff --git a/src/main/java/hudson/plugins/jwsdp_sqe/SQETestResultPublisher.java b/src/main/java/hudson/plugins/jwsdp_sqe/SQETestResultPublisher.java index eb0d0e0..0cd159b 100644 --- a/src/main/java/hudson/plugins/jwsdp_sqe/SQETestResultPublisher.java +++ b/src/main/java/hudson/plugins/jwsdp_sqe/SQETestResultPublisher.java @@ -1,91 +1,91 @@ package hudson.plugins.jwsdp_sqe; import hudson.Launcher; import hudson.model.Action; import hudson.model.Build; import hudson.model.BuildListener; import hudson.model.Descriptor; import hudson.model.Project; import hudson.model.Result; import hudson.tasks.Publisher; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.types.FileSet; import org.kohsuke.stapler.StaplerRequest; /** * Collects SQE test reports and convert them into JUnit format. * * @author Kohsuke Kawaguchi */ public class SQETestResultPublisher extends Publisher { private final String includes; /** * Flag to capture if test should be considered as executable TestObject */ boolean considerTestAsTestObject = false; public SQETestResultPublisher(String includes, boolean considerTestAsTestObject) { this.includes = includes; this.considerTestAsTestObject = considerTestAsTestObject; } /** * Ant "&lt;fileset @includes="..." /> pattern to specify SQE XML files */ public String getIncludes() { return includes; } public boolean getConsiderTestAsTestObject() { return considerTestAsTestObject; } public boolean perform(Build build, Launcher launcher, BuildListener listener) { FileSet fs = new FileSet(); org.apache.tools.ant.Project p = new org.apache.tools.ant.Project(); fs.setProject(p); fs.setDir(build.getProject().getWorkspace().getLocal()); fs.setIncludes(includes); DirectoryScanner ds = fs.getDirectoryScanner(p); if(ds.getIncludedFiles().length==0) { - listener.getLogger().println("No SQE test report files wer efound. Configuration error?"); + listener.getLogger().println("No SQE test report files were found. Configuration error?"); // no test result. Most likely a configuration error or fatal problem build.setResult(Result.FAILURE); } SQETestAction action = new SQETestAction(build, ds, listener, considerTestAsTestObject); build.getActions().add(action); Report r = action.getResult(); if(r.getTotalCount()==0) { listener.getLogger().println("Test reports were found but none of them are new. Did tests run?"); // no test result. Most likely a configuration error or fatal problem build.setResult(Result.FAILURE); } if(r.getFailCount()>0) build.setResult(Result.UNSTABLE); return true; } public Descriptor<Publisher> getDescriptor() { return DESCRIPTOR; } public static final Descriptor<Publisher> DESCRIPTOR = new Descriptor<Publisher>(SQETestResultPublisher.class) { public String getDisplayName() { return "Publish SQE test result report"; } public String getHelpFile() { return "/plugin/jwsdp-sqe/help.html"; } public Publisher newInstance(StaplerRequest req) { return new SQETestResultPublisher(req.getParameter("sqetest_includes"),(req.getParameter("sqetest_testobject")!=null)); } }; }
true
true
public boolean perform(Build build, Launcher launcher, BuildListener listener) { FileSet fs = new FileSet(); org.apache.tools.ant.Project p = new org.apache.tools.ant.Project(); fs.setProject(p); fs.setDir(build.getProject().getWorkspace().getLocal()); fs.setIncludes(includes); DirectoryScanner ds = fs.getDirectoryScanner(p); if(ds.getIncludedFiles().length==0) { listener.getLogger().println("No SQE test report files wer efound. Configuration error?"); // no test result. Most likely a configuration error or fatal problem build.setResult(Result.FAILURE); } SQETestAction action = new SQETestAction(build, ds, listener, considerTestAsTestObject); build.getActions().add(action); Report r = action.getResult(); if(r.getTotalCount()==0) { listener.getLogger().println("Test reports were found but none of them are new. Did tests run?"); // no test result. Most likely a configuration error or fatal problem build.setResult(Result.FAILURE); } if(r.getFailCount()>0) build.setResult(Result.UNSTABLE); return true; }
public boolean perform(Build build, Launcher launcher, BuildListener listener) { FileSet fs = new FileSet(); org.apache.tools.ant.Project p = new org.apache.tools.ant.Project(); fs.setProject(p); fs.setDir(build.getProject().getWorkspace().getLocal()); fs.setIncludes(includes); DirectoryScanner ds = fs.getDirectoryScanner(p); if(ds.getIncludedFiles().length==0) { listener.getLogger().println("No SQE test report files were found. Configuration error?"); // no test result. Most likely a configuration error or fatal problem build.setResult(Result.FAILURE); } SQETestAction action = new SQETestAction(build, ds, listener, considerTestAsTestObject); build.getActions().add(action); Report r = action.getResult(); if(r.getTotalCount()==0) { listener.getLogger().println("Test reports were found but none of them are new. Did tests run?"); // no test result. Most likely a configuration error or fatal problem build.setResult(Result.FAILURE); } if(r.getFailCount()>0) build.setResult(Result.UNSTABLE); return true; }
diff --git a/src/ucbang/core/Card.java b/src/ucbang/core/Card.java index 9ed965f..b6d8853 100644 --- a/src/ucbang/core/Card.java +++ b/src/ucbang/core/Card.java @@ -1,306 +1,306 @@ package ucbang.core; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; public class Card { public static enum play { DAMAGE, HEAL, MISS, DRAW, STEAL, DISCARD, DUEL, JAIL }; // played cards public static enum field { DAMAGE, HEAL, MISS, DRAW, STEAL, DISCARD, BARREL, DYNAMITE, GUN, HORSE_RUN, HORSE_CHASE }; // field cards public Card(Enum e) { this.e = e; ordinal = e.ordinal(); name = e.toString(); if (e instanceof Deck.Characters) { type = 1; int[] threehp = new int[] { 3, 6, 8, 16, 21, 27, 28, 30 }; if (Arrays.binarySearch(threehp, ordinal) >= 0 && ordinal == threehp[Arrays.binarySearch(threehp, ordinal)]) { // awkward // way // of // doing // contains special = 3; } else special = 4; } else { // TODO: find out what kind of card it is switch ((Deck.CardName) e) { // put all direct damage cards here case BANG: type = 2; special = 1; range = 1; target = 2; effect = play.DAMAGE.ordinal(); break; case PUNCH: type = 2; target = 2; range = 1; effect = play.DAMAGE.ordinal(); break; case GATLING: type = 2; target = 4; effect = play.DAMAGE.ordinal(); break; case HOWITZER: type = 3; target = 4; effect = play.DAMAGE.ordinal(); break; case INDIANS: type = 2; special = 2; target = 4; effect = play.DAMAGE.ordinal(); break; case KNIFE: type = 2; target = 2; range = 1; effect = play.DAMAGE.ordinal(); break; case BUFFALO_RIFLE: type = 3; target = 2; range = -1; effect = play.DAMAGE.ordinal(); break; case SPRINGFIELD: type = 2; target = 2; discardToPlay = true; range = -1; effect = play.DAMAGE.ordinal(); break; case PEPPERBOX: type = 3; target = 2; range = 1; effect = play.DAMAGE.ordinal(); break; // TODO: make same range as bang case DERRINGER: type = 3; target = 2; range = 1; effect = play.DAMAGE.ordinal(); effect2 = play.DRAW.ordinal(); break; case DUEL: type = 2; target = 2; range = -1; effect = play.DUEL.ordinal(); break; case DYNAMITE: type = 3; target = 1; effect = field.DYNAMITE.ordinal(); break; case MISS: type = 4; special = 1; effect = play.MISS.ordinal(); break; case DODGE: type = 4; effect = play.MISS.ordinal(); break; case BIBLE: - type = 4; + type = 3; effect = play.MISS.ordinal(); break; case IRON_PLATE: type = 3; effect = play.MISS.ordinal(); break; case SOMBRERO: type = 3; effect = play.MISS.ordinal(); break; case TEN_GALLON_HAT: type = 3; effect = play.MISS.ordinal(); break; case BARREL: type = 3; effect = field.BARREL.ordinal(); break; case WELLS_FARGO: type = 2; range = 3; effect = play.DRAW.ordinal(); break; case STAGECOACH: type = 2; range = 2; effect = play.DRAW.ordinal(); break; case CONESTOGA: type = 3; range = 2; effect = play.DRAW.ordinal(); break; case PONY_EXPRESS: type = 3; range = 3; effect = play.DRAW.ordinal(); break; case GENERAL_STORE: type = 2; target = 3; range = 1; effect = play.DRAW.ordinal(); break; // fix general store case JAIL: type = 2; range = -1; effect = play.JAIL.ordinal(); break; // special case: even though jail remains on the field of // a player, it is "played" case APPALOOSA: type = 3; effect = field.HORSE_CHASE.ordinal(); break; case SILVER: type = 3; effect = field.HORSE_CHASE.ordinal(); break; case MUSTANG: type = 3; effect = field.HORSE_RUN.ordinal(); break; case HIDEOUT: type = 3; effect = field.HORSE_RUN.ordinal(); break; // you heard me: a hideout is a horse. case BEER: type = 2; target = 1; special = 1; effect = play.HEAL.ordinal(); break; case TEQUILA: type = 2; target = 2; discardToPlay = true; effect = play.HEAL.ordinal(); break; case WHISKY: type = 2; target = 1; range = 1; discardToPlay = true; effect = play.HEAL.ordinal(); break; // special case: heals 2 hp, so i guess i'll use "range" case CANTEEN: type = 3; target = 1; effect = play.HEAL.ordinal(); break; case SALOON: type = 2; target = 3; effect = play.HEAL.ordinal(); break; case BRAWL: type = 2; target = 4; discardToPlay = true; play.DISCARD.ordinal(); break; case CAN_CAN: type = 3; target = 2; range = -1; effect = play.STEAL.ordinal(); break; case RAG_TIME: type = 2; target = 2; range = -1; discardToPlay = true; effect = play.STEAL.ordinal(); break; case PANIC: type = 2; target = 2; range = 1; effect = play.STEAL.ordinal(); break; case CAT_BALLOU: type = 2; target = 2; range = -1; effect = play.DISCARD.ordinal(); break; case VOLCANIC: type = 3; special = 1; range = 1; effect = field.GUN.ordinal(); break; case SCHOFIELD: type = 3; range = 2; effect = field.GUN.ordinal(); break; case REMINGTON: type = 3; range = 3; effect = field.GUN.ordinal(); break; case REV_CARBINE: type = 3; range = 4; effect = field.GUN.ordinal(); break; case WINCHESTER: type = 3; range = 5; effect = field.GUN.ordinal(); break; default: break; // special = 1; type = 2; effect = play.DAMAGE.ordinal(); // break; //all cards left untreated are treated as // bangs } } } public Enum e; public String name; public int ordinal; public int type; // 1 = char, 2 = play, 3 = field, 4 = miss public int target; // 1 = self, 2 = choose 1 player, 3 = all, 4 = all others public int effect; // 1 = deal damage, 2 = heal, 3 = miss, 4 = draw public int effect2; // secondary effects only affect player public int special; // HP for char cards, ???? for other cards, 1 for beer // and bangs, 1 for miss, 2 for dodge public boolean discardToPlay; // cards that need a discard to play public int range; // used for guns and panic and #cards drawn public String toString(){ return name; } }
true
true
public Card(Enum e) { this.e = e; ordinal = e.ordinal(); name = e.toString(); if (e instanceof Deck.Characters) { type = 1; int[] threehp = new int[] { 3, 6, 8, 16, 21, 27, 28, 30 }; if (Arrays.binarySearch(threehp, ordinal) >= 0 && ordinal == threehp[Arrays.binarySearch(threehp, ordinal)]) { // awkward // way // of // doing // contains special = 3; } else special = 4; } else { // TODO: find out what kind of card it is switch ((Deck.CardName) e) { // put all direct damage cards here case BANG: type = 2; special = 1; range = 1; target = 2; effect = play.DAMAGE.ordinal(); break; case PUNCH: type = 2; target = 2; range = 1; effect = play.DAMAGE.ordinal(); break; case GATLING: type = 2; target = 4; effect = play.DAMAGE.ordinal(); break; case HOWITZER: type = 3; target = 4; effect = play.DAMAGE.ordinal(); break; case INDIANS: type = 2; special = 2; target = 4; effect = play.DAMAGE.ordinal(); break; case KNIFE: type = 2; target = 2; range = 1; effect = play.DAMAGE.ordinal(); break; case BUFFALO_RIFLE: type = 3; target = 2; range = -1; effect = play.DAMAGE.ordinal(); break; case SPRINGFIELD: type = 2; target = 2; discardToPlay = true; range = -1; effect = play.DAMAGE.ordinal(); break; case PEPPERBOX: type = 3; target = 2; range = 1; effect = play.DAMAGE.ordinal(); break; // TODO: make same range as bang case DERRINGER: type = 3; target = 2; range = 1; effect = play.DAMAGE.ordinal(); effect2 = play.DRAW.ordinal(); break; case DUEL: type = 2; target = 2; range = -1; effect = play.DUEL.ordinal(); break; case DYNAMITE: type = 3; target = 1; effect = field.DYNAMITE.ordinal(); break; case MISS: type = 4; special = 1; effect = play.MISS.ordinal(); break; case DODGE: type = 4; effect = play.MISS.ordinal(); break; case BIBLE: type = 4; effect = play.MISS.ordinal(); break; case IRON_PLATE: type = 3; effect = play.MISS.ordinal(); break; case SOMBRERO: type = 3; effect = play.MISS.ordinal(); break; case TEN_GALLON_HAT: type = 3; effect = play.MISS.ordinal(); break; case BARREL: type = 3; effect = field.BARREL.ordinal(); break; case WELLS_FARGO: type = 2; range = 3; effect = play.DRAW.ordinal(); break; case STAGECOACH: type = 2; range = 2; effect = play.DRAW.ordinal(); break; case CONESTOGA: type = 3; range = 2; effect = play.DRAW.ordinal(); break; case PONY_EXPRESS: type = 3; range = 3; effect = play.DRAW.ordinal(); break; case GENERAL_STORE: type = 2; target = 3; range = 1; effect = play.DRAW.ordinal(); break; // fix general store case JAIL: type = 2; range = -1; effect = play.JAIL.ordinal(); break; // special case: even though jail remains on the field of // a player, it is "played" case APPALOOSA: type = 3; effect = field.HORSE_CHASE.ordinal(); break; case SILVER: type = 3; effect = field.HORSE_CHASE.ordinal(); break; case MUSTANG: type = 3; effect = field.HORSE_RUN.ordinal(); break; case HIDEOUT: type = 3; effect = field.HORSE_RUN.ordinal(); break; // you heard me: a hideout is a horse. case BEER: type = 2; target = 1; special = 1; effect = play.HEAL.ordinal(); break; case TEQUILA: type = 2; target = 2; discardToPlay = true; effect = play.HEAL.ordinal(); break; case WHISKY: type = 2; target = 1; range = 1; discardToPlay = true; effect = play.HEAL.ordinal(); break; // special case: heals 2 hp, so i guess i'll use "range" case CANTEEN: type = 3; target = 1; effect = play.HEAL.ordinal(); break; case SALOON: type = 2; target = 3; effect = play.HEAL.ordinal(); break; case BRAWL: type = 2; target = 4; discardToPlay = true; play.DISCARD.ordinal(); break; case CAN_CAN: type = 3; target = 2; range = -1; effect = play.STEAL.ordinal(); break; case RAG_TIME: type = 2; target = 2; range = -1; discardToPlay = true; effect = play.STEAL.ordinal(); break; case PANIC: type = 2; target = 2; range = 1; effect = play.STEAL.ordinal(); break; case CAT_BALLOU: type = 2; target = 2; range = -1; effect = play.DISCARD.ordinal(); break; case VOLCANIC: type = 3; special = 1; range = 1; effect = field.GUN.ordinal(); break; case SCHOFIELD: type = 3; range = 2; effect = field.GUN.ordinal(); break; case REMINGTON: type = 3; range = 3; effect = field.GUN.ordinal(); break; case REV_CARBINE: type = 3; range = 4; effect = field.GUN.ordinal(); break; case WINCHESTER: type = 3; range = 5; effect = field.GUN.ordinal(); break; default: break; // special = 1; type = 2; effect = play.DAMAGE.ordinal(); // break; //all cards left untreated are treated as // bangs } } }
public Card(Enum e) { this.e = e; ordinal = e.ordinal(); name = e.toString(); if (e instanceof Deck.Characters) { type = 1; int[] threehp = new int[] { 3, 6, 8, 16, 21, 27, 28, 30 }; if (Arrays.binarySearch(threehp, ordinal) >= 0 && ordinal == threehp[Arrays.binarySearch(threehp, ordinal)]) { // awkward // way // of // doing // contains special = 3; } else special = 4; } else { // TODO: find out what kind of card it is switch ((Deck.CardName) e) { // put all direct damage cards here case BANG: type = 2; special = 1; range = 1; target = 2; effect = play.DAMAGE.ordinal(); break; case PUNCH: type = 2; target = 2; range = 1; effect = play.DAMAGE.ordinal(); break; case GATLING: type = 2; target = 4; effect = play.DAMAGE.ordinal(); break; case HOWITZER: type = 3; target = 4; effect = play.DAMAGE.ordinal(); break; case INDIANS: type = 2; special = 2; target = 4; effect = play.DAMAGE.ordinal(); break; case KNIFE: type = 2; target = 2; range = 1; effect = play.DAMAGE.ordinal(); break; case BUFFALO_RIFLE: type = 3; target = 2; range = -1; effect = play.DAMAGE.ordinal(); break; case SPRINGFIELD: type = 2; target = 2; discardToPlay = true; range = -1; effect = play.DAMAGE.ordinal(); break; case PEPPERBOX: type = 3; target = 2; range = 1; effect = play.DAMAGE.ordinal(); break; // TODO: make same range as bang case DERRINGER: type = 3; target = 2; range = 1; effect = play.DAMAGE.ordinal(); effect2 = play.DRAW.ordinal(); break; case DUEL: type = 2; target = 2; range = -1; effect = play.DUEL.ordinal(); break; case DYNAMITE: type = 3; target = 1; effect = field.DYNAMITE.ordinal(); break; case MISS: type = 4; special = 1; effect = play.MISS.ordinal(); break; case DODGE: type = 4; effect = play.MISS.ordinal(); break; case BIBLE: type = 3; effect = play.MISS.ordinal(); break; case IRON_PLATE: type = 3; effect = play.MISS.ordinal(); break; case SOMBRERO: type = 3; effect = play.MISS.ordinal(); break; case TEN_GALLON_HAT: type = 3; effect = play.MISS.ordinal(); break; case BARREL: type = 3; effect = field.BARREL.ordinal(); break; case WELLS_FARGO: type = 2; range = 3; effect = play.DRAW.ordinal(); break; case STAGECOACH: type = 2; range = 2; effect = play.DRAW.ordinal(); break; case CONESTOGA: type = 3; range = 2; effect = play.DRAW.ordinal(); break; case PONY_EXPRESS: type = 3; range = 3; effect = play.DRAW.ordinal(); break; case GENERAL_STORE: type = 2; target = 3; range = 1; effect = play.DRAW.ordinal(); break; // fix general store case JAIL: type = 2; range = -1; effect = play.JAIL.ordinal(); break; // special case: even though jail remains on the field of // a player, it is "played" case APPALOOSA: type = 3; effect = field.HORSE_CHASE.ordinal(); break; case SILVER: type = 3; effect = field.HORSE_CHASE.ordinal(); break; case MUSTANG: type = 3; effect = field.HORSE_RUN.ordinal(); break; case HIDEOUT: type = 3; effect = field.HORSE_RUN.ordinal(); break; // you heard me: a hideout is a horse. case BEER: type = 2; target = 1; special = 1; effect = play.HEAL.ordinal(); break; case TEQUILA: type = 2; target = 2; discardToPlay = true; effect = play.HEAL.ordinal(); break; case WHISKY: type = 2; target = 1; range = 1; discardToPlay = true; effect = play.HEAL.ordinal(); break; // special case: heals 2 hp, so i guess i'll use "range" case CANTEEN: type = 3; target = 1; effect = play.HEAL.ordinal(); break; case SALOON: type = 2; target = 3; effect = play.HEAL.ordinal(); break; case BRAWL: type = 2; target = 4; discardToPlay = true; play.DISCARD.ordinal(); break; case CAN_CAN: type = 3; target = 2; range = -1; effect = play.STEAL.ordinal(); break; case RAG_TIME: type = 2; target = 2; range = -1; discardToPlay = true; effect = play.STEAL.ordinal(); break; case PANIC: type = 2; target = 2; range = 1; effect = play.STEAL.ordinal(); break; case CAT_BALLOU: type = 2; target = 2; range = -1; effect = play.DISCARD.ordinal(); break; case VOLCANIC: type = 3; special = 1; range = 1; effect = field.GUN.ordinal(); break; case SCHOFIELD: type = 3; range = 2; effect = field.GUN.ordinal(); break; case REMINGTON: type = 3; range = 3; effect = field.GUN.ordinal(); break; case REV_CARBINE: type = 3; range = 4; effect = field.GUN.ordinal(); break; case WINCHESTER: type = 3; range = 5; effect = field.GUN.ordinal(); break; default: break; // special = 1; type = 2; effect = play.DAMAGE.ordinal(); // break; //all cards left untreated are treated as // bangs } } }
diff --git a/src/com/ichi2/anki/CardBrowser.java b/src/com/ichi2/anki/CardBrowser.java index 166830bf..766b5569 100644 --- a/src/com/ichi2/anki/CardBrowser.java +++ b/src/com/ichi2/anki/CardBrowser.java @@ -1,1055 +1,1059 @@ /**************************************************************************************** * Copyright (c) 2010 Norbert Nagold <[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.anki; import android.app.Activity; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Resources; import android.os.Bundle; import android.os.Handler; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.util.TypedValue; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.EditText; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import com.ichi2.anim.ActivityTransitionAnimation; import com.ichi2.themes.StyledDialog; import com.ichi2.themes.Themes; import com.tomgibara.android.veecheck.util.PrefSettings; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import org.amr.arabic.ArabicUtilities; public class CardBrowser extends Activity { private ArrayList<HashMap<String, String>> mCards; private ArrayList<HashMap<String, String>> mAllCards; private ArrayList<HashMap<String, String>> mDeletedCards; private ListView mCardsListView; private SimpleAdapter mCardsAdapter; private EditText mSearchEditText; private ProgressDialog mProgressDialog; private boolean mUndoRedoDialogShowing = false; private Card mSelectedCard; private Card mUndoRedoCard; private long mUndoRedoCardId; private static Card sEditorCard; private boolean mIsSuspended; private boolean mIsMarked; private Deck mDeck; private int mPositionInCardsList; /** Modifier of percentage of the font size of the card browser */ private int mrelativeBrowserFontSize = CardModel.DEFAULT_FONT_SIZE_RATIO; public static final int LOAD_CHUNK = 200; private static final int CONTEXT_MENU_MARK = 0; private static final int CONTEXT_MENU_SUSPEND = 1; private static final int CONTEXT_MENU_DELETE = 2; private static final int CONTEXT_MENU_DETAILS = 3; private static final int DIALOG_ORDER = 0; private static final int DIALOG_CONTEXT_MENU = 1; private static final int BACKGROUND_NORMAL = 0; private static final int BACKGROUND_MARKED = 1; private static final int BACKGROUND_SUSPENDED = 2; private static final int BACKGROUND_MARKED_SUSPENDED = 3; private static final int MENU_UNDO = 0; private static final int MENU_REDO = 1; private static final int MENU_ADD_FACT = 2; private static final int MENU_SHOW_MARKED = 3; private static final int MENU_SELECT = 4; private static final int MENU_SELECT_SUSPENDED = 41; private static final int MENU_SELECT_TAG = 42; private static final int MENU_CHANGE_ORDER = 5; private static final int EDIT_CARD = 0; private static final int ADD_FACT = 1; private static final int DEFAULT_FONT_SIZE_RATIO = 100; private static final int CARD_ORDER_ANSWER = 0; private static final int CARD_ORDER_QUESTION = 1; private static final int CARD_ORDER_DUE = 2; private static final int CARD_ORDER_INTERVAL = 3; private static final int CARD_ORDER_FACTOR = 4; private static final int CARD_ORDER_CREATED = 5; private int[] mBackground; private boolean mShowOnlyMarSus = false; private int mSelectedOrder = CARD_ORDER_CREATED; private String[] allTags; private HashSet<String> mSelectedTags; private StyledDialog mTagsDialog; private boolean mPrefFixArabic; private Handler mTimerHandler = new Handler(); private static final int WAIT_TIME_UNTIL_UPDATE = 500; private Runnable updateList = new Runnable() { public void run() { updateCardsList(); } }; private DialogInterface.OnClickListener mContextMenuListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case CONTEXT_MENU_MARK: DeckTask.launchDeckTask(DeckTask.TASK_TYPE_MARK_CARD, mMarkCardHandler, new DeckTask.TaskData(0, mDeck, mSelectedCard)); return; case CONTEXT_MENU_SUSPEND: DeckTask.launchDeckTask(DeckTask.TASK_TYPE_SUSPEND_CARD, mSuspendCardHandler, new DeckTask.TaskData(0, mDeck, mSelectedCard)); return; case CONTEXT_MENU_DELETE: Resources res = getResources(); StyledDialog.Builder builder = new StyledDialog.Builder(CardBrowser.this); builder.setTitle(res.getString(R.string.delete_card_title)); builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setMessage(String.format(res .getString(R.string.delete_card_message), mCards.get( mPositionInCardsList).get("question"), mCards.get( mPositionInCardsList).get("answer"))); builder.setPositiveButton(res.getString(R.string.yes), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { DeckTask.launchDeckTask( DeckTask.TASK_TYPE_DELETE_CARD, mDeleteCardHandler, new DeckTask.TaskData( 0, mDeck, mSelectedCard)); } }); builder.setNegativeButton(res.getString(R.string.no), null); builder.create().show(); return; case CONTEXT_MENU_DETAILS: Themes.htmlOkDialog(CardBrowser.this, getResources().getString(R.string.card_browser_card_details), mSelectedCard.getCardDetails(CardBrowser.this, true)).show(); return; } } }; @Override protected void onCreate(Bundle savedInstanceState) { Themes.applyTheme(this); super.onCreate(savedInstanceState); View mainView = getLayoutInflater().inflate(R.layout.card_browser, null); setContentView(mainView); Themes.setContentStyle(mainView, Themes.CALLER_CARDBROWSER); mDeck = AnkiDroidApp.deck(); + if (mDeck == null) { + finish(); + return; + } mDeck.resetUndo(); mBackground = Themes.getCardBrowserBackground(); SharedPreferences preferences = PrefSettings .getSharedPrefs(getBaseContext()); mrelativeBrowserFontSize = preferences.getInt( "relativeCardBrowserFontSize", DEFAULT_FONT_SIZE_RATIO); mPrefFixArabic = preferences.getBoolean("fixArabicText", false); mCards = new ArrayList<HashMap<String, String>>(); mAllCards = new ArrayList<HashMap<String, String>>(); mCardsListView = (ListView) findViewById(R.id.card_browser_list); mCardsAdapter = new SizeControlledListAdapter(this, mCards, R.layout.card_item, new String[] { "question", "answer", "flags" }, new int[] { R.id.card_question, R.id.card_answer, R.id.card_item }, mrelativeBrowserFontSize); mCardsAdapter.setViewBinder(new SimpleAdapter.ViewBinder() { @Override public boolean setViewValue(View view, Object arg1, String text) { if (view.getId() == R.id.card_item) { int which = BACKGROUND_NORMAL; if (text.equals("11")) { which = BACKGROUND_MARKED_SUSPENDED; } else if (text.substring(1, 2).equals("1")) { which = BACKGROUND_SUSPENDED; } else if (text.substring(0, 1).equals("1")) { which = BACKGROUND_MARKED; } view.setBackgroundResource(mBackground[which]); return true; } return false; } }); mCardsListView.setAdapter(mCardsAdapter); mCardsListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent editCard = new Intent(CardBrowser.this, CardEditor.class); editCard.putExtra(CardEditor.CARD_EDITOR_ACTION, CardEditor.EDIT_BROWSER_CARD); mPositionInCardsList = position; mSelectedCard = mDeck.cardFromId(Long.parseLong(mCards.get( mPositionInCardsList).get("id"))); sEditorCard = mSelectedCard; editCard.putExtra("callfromcardbrowser", true); startActivityForResult(editCard, EDIT_CARD); if (Integer.valueOf(android.os.Build.VERSION.SDK) > 4) { ActivityTransitionAnimation.slide(CardBrowser.this, ActivityTransitionAnimation.LEFT); } } }); registerForContextMenu(mCardsListView); mSearchEditText = (EditText) findViewById(R.id.card_browser_search); mSearchEditText.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { mTimerHandler.removeCallbacks(updateList); mTimerHandler.postDelayed(updateList, WAIT_TIME_UNTIL_UPDATE); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { } }); getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); setTitle(mDeck.getDeckName()); allTags = null; mSelectedTags = new HashSet<String>(); getCards(); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { mPositionInCardsList = ((AdapterView.AdapterContextMenuInfo) menuInfo).position; showDialog(DIALOG_CONTEXT_MENU); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { Log.i(AnkiDroidApp.TAG, "CardBrowser - onBackPressed()"); if (mSearchEditText.getText().length() == 0 && !mShowOnlyMarSus && mSelectedTags.size() == 0) { setResult(RESULT_OK); finish(); if (Integer.valueOf(android.os.Build.VERSION.SDK) > 4) { ActivityTransitionAnimation.slide(CardBrowser.this, ActivityTransitionAnimation.RIGHT); } } else { mSearchEditText.setText(""); mSearchEditText.setHint(R.string.downloaddeck_search); mSelectedTags.clear(); mCards.clear(); mCards.addAll(mAllCards); updateList(); } return true; } return super.onKeyDown(keyCode, event); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuItem item; item = menu.add(Menu.NONE, MENU_UNDO, Menu.NONE, R.string.undo); item.setIcon(R.drawable.ic_menu_revert); item = menu.add(Menu.NONE, MENU_REDO, Menu.NONE, R.string.redo); item.setIcon(R.drawable.ic_menu_redo); item = menu.add(Menu.NONE, MENU_ADD_FACT, Menu.NONE, R.string.add); item.setIcon(R.drawable.ic_menu_add); item = menu.add(Menu.NONE, MENU_CHANGE_ORDER, Menu.NONE, R.string.card_browser_change_display_order); item.setIcon(R.drawable.ic_menu_sort_by_size); item = menu.add(Menu.NONE, MENU_SHOW_MARKED, Menu.NONE, R.string.card_browser_show_marked); item.setIcon(R.drawable.ic_menu_star_on); SubMenu selectSubMenu = menu.addSubMenu(Menu.NONE, MENU_SELECT, Menu.NONE, R.string.card_browser_search); selectSubMenu.setIcon(R.drawable.ic_menu_search); selectSubMenu.add(Menu.NONE, MENU_SELECT_SUSPENDED, Menu.NONE, R.string.card_browser_search_suspended); selectSubMenu.add(Menu.NONE, MENU_SELECT_TAG, Menu.NONE, R.string.card_browser_search_by_tag); item.setIcon(R.drawable.ic_menu_close_clear_cancel); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { menu.findItem(MENU_UNDO).setEnabled(mDeck.undoAvailable()); menu.findItem(MENU_REDO).setEnabled(mDeck.redoAvailable()); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_UNDO: DeckTask.launchDeckTask(DeckTask.TASK_TYPE_UNDO, mUndoRedoHandler, new DeckTask.TaskData(0, mDeck, 0, true)); return true; case MENU_REDO: DeckTask.launchDeckTask(DeckTask.TASK_TYPE_REDO, mUndoRedoHandler, new DeckTask.TaskData(0, mDeck, 0, true)); return true; case MENU_ADD_FACT: Intent intent = new Intent(CardBrowser.this, CardEditor.class); intent.putExtra(CardEditor.CARD_EDITOR_ACTION, CardEditor.ADD_CARD); startActivityForResult(intent, ADD_FACT); if (Integer.valueOf(android.os.Build.VERSION.SDK) > 4) { ActivityTransitionAnimation.slide(CardBrowser.this, ActivityTransitionAnimation.LEFT); } return true; case MENU_SHOW_MARKED: mShowOnlyMarSus = true; mSearchEditText.setHint(R.string.card_browser_show_marked); mCards.clear(); for (int i = 0; i < mAllCards.size(); i++) { if ((mAllCards.get(i).get("question").toLowerCase().indexOf( mSearchEditText.getText().toString().toLowerCase()) != -1 || mAllCards .get(i).get("answer").toLowerCase().indexOf( mSearchEditText.getText().toString() .toLowerCase()) != -1) && mAllCards.get(i).get("flags").subSequence(0, 1) .equals("1")) { mCards.add(mAllCards.get(i)); } } updateList(); return true; case MENU_SELECT_SUSPENDED: mShowOnlyMarSus = true; mSearchEditText.setHint(R.string.card_browser_show_suspended); mCards.clear(); for (int i = 0; i < mAllCards.size(); i++) { if ((mAllCards.get(i).get("question").toLowerCase().indexOf( mSearchEditText.getText().toString().toLowerCase()) != -1 || mAllCards .get(i).get("answer").toLowerCase().indexOf( mSearchEditText.getText().toString() .toLowerCase()) != -1) && mAllCards.get(i).get("flags").subSequence(1, 2) .equals("1")) { mCards.add(mAllCards.get(i)); } } updateList(); return true; case MENU_SELECT_TAG: recreateTagsDialog(); mTagsDialog.show(); return true; case MENU_CHANGE_ORDER: showDialog(DIALOG_ORDER); return true; } return false; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == EDIT_CARD && resultCode == RESULT_OK) { Log.i(AnkiDroidApp.TAG, "Saving card..."); DeckTask.launchDeckTask(DeckTask.TASK_TYPE_UPDATE_FACT, mUpdateCardHandler, new DeckTask.TaskData(0, mDeck, mSelectedCard)); } else if (requestCode == ADD_FACT && resultCode == RESULT_OK) { getCards(); } } @Override protected Dialog onCreateDialog(int id) { StyledDialog dialog = null; Resources res = getResources(); StyledDialog.Builder builder = new StyledDialog.Builder(this); switch (id) { case DIALOG_ORDER: builder.setTitle(res .getString(R.string.card_browser_change_display_order_title)); builder.setIcon(android.R.drawable.ic_menu_sort_by_size); builder.setSingleChoiceItems(getResources().getStringArray(R.array.card_browser_order_labels), mSelectedOrder, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int which) { if (which != mSelectedOrder) { mSelectedOrder = which; DeckTask.launchDeckTask(DeckTask.TASK_TYPE_SORT_CARDS, mSortCardsHandler, new DeckTask.TaskData(mAllCards, new HashMapCompare())); } } }); dialog = builder.create(); break; case DIALOG_CONTEXT_MENU: String[] entries = new String[4]; @SuppressWarnings("unused") MenuItem item; entries[CONTEXT_MENU_MARK] = res.getString(R.string.card_browser_mark_card); entries[CONTEXT_MENU_SUSPEND] = res.getString(R.string.card_browser_suspend_card); entries[CONTEXT_MENU_DELETE] = res.getString(R.string.card_browser_delete_card); entries[CONTEXT_MENU_DETAILS] = res.getString(R.string.card_browser_card_details); builder.setTitle("contextmenu"); builder.setIcon(R.drawable.ic_menu_manage); builder.setItems(entries, mContextMenuListener); dialog = builder.create(); break; } return dialog; } @Override protected void onPrepareDialog(int id, Dialog dialog) { Resources res = getResources(); StyledDialog ad = (StyledDialog)dialog; switch (id) { case DIALOG_CONTEXT_MENU: mSelectedCard = mDeck.cardFromId(Long.parseLong(mCards.get(mPositionInCardsList).get("id"))); if (mSelectedCard.isMarked()) { ad.changeListItem(CONTEXT_MENU_MARK, res.getString(R.string.card_browser_unmark_card)); mIsMarked = true; Log.i(AnkiDroidApp.TAG, "Selected Card is currently marked"); } else { ad.changeListItem(CONTEXT_MENU_MARK, res.getString(R.string.card_browser_mark_card)); mIsMarked = false; } if (mSelectedCard.getSuspendedState()) { ad.changeListItem(CONTEXT_MENU_SUSPEND, res.getString(R.string.card_browser_unsuspend_card)); mIsSuspended = true; Log.i(AnkiDroidApp.TAG, "Selected Card is currently suspended"); } else { ad.changeListItem(CONTEXT_MENU_SUSPEND, res.getString(R.string.card_browser_suspend_card)); mIsSuspended = false; } ad.setTitle(mCards.get(mPositionInCardsList).get("question")); break; } } private void recreateTagsDialog() { Resources res = getResources(); if (allTags == null) { String[] oldTags = AnkiDroidApp.deck().allTags_(); Log.i(AnkiDroidApp.TAG, "all tags: " + Arrays.toString(oldTags)); allTags = new String[oldTags.length]; for (int i = 0; i < oldTags.length; i++) { allTags[i] = oldTags[i]; } } mSelectedTags.clear(); StyledDialog.Builder builder = new StyledDialog.Builder(this); builder.setTitle(R.string.studyoptions_limit_select_tags); builder.setMultiChoiceItems(allTags, new boolean[0], new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String tag = allTags[which]; if (mSelectedTags.contains(tag)) { Log.i(AnkiDroidApp.TAG, "unchecked tag: " + tag); mSelectedTags.remove(tag); } else { Log.i(AnkiDroidApp.TAG, "checked tag: " + tag); mSelectedTags.add(tag); } } }); builder.setPositiveButton(res.getString(R.string.select), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { updateCardsList(); } }); builder.setNegativeButton(res.getString(R.string.cancel), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mSelectedTags.clear(); } }); builder.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { mSelectedTags.clear(); } }); mTagsDialog = builder.create(); } private void updateCardsList() { mShowOnlyMarSus = false; if (mSelectedTags.size() == 0) { mSearchEditText.setHint(R.string.downloaddeck_search); } else { String tags = mSelectedTags.toString(); mSearchEditText.setHint(getResources().getString( R.string.card_browser_tags_shown, tags.substring(1, tags.length() - 1))); } mCards.clear(); if (mSearchEditText.getText().length() == 0 && mSelectedTags.size() == 0 && mSelectedTags.size() == 0) { mCards.addAll(mAllCards); } else { for (int i = 0; i < mAllCards.size(); i++) { if ((mAllCards.get(i).get("question").toLowerCase().indexOf( mSearchEditText.getText().toString().toLowerCase()) != -1 || mAllCards .get(i).get("answer").toLowerCase().indexOf( mSearchEditText.getText().toString() .toLowerCase()) != -1) && Arrays.asList( Utils.parseTags(mAllCards.get(i).get("tags"))) .containsAll(mSelectedTags)) { mCards.add(mAllCards.get(i)); } } } updateList(); } private void getCards() { DeckTask.launchDeckTask(DeckTask.TASK_TYPE_LOAD_CARDS, mLoadCardsHandler, new DeckTask.TaskData(mDeck, LOAD_CHUNK)); } public static Card getEditorCard() { return sEditorCard; } private void updateList() { mCardsAdapter.notifyDataSetChanged(); int count = mCards.size(); setTitle(getResources().getQuantityString(R.plurals.card_browser_title, count, mDeck.getDeckName(), count, mAllCards.size())); } private int getPosition(ArrayList<HashMap<String, String>> list, long cardId) { String cardid = Long.toString(cardId); for (int i = 0; i < list.size(); i++) { if (list.get(i).get("id").equals(cardid)) { return i; } } return -1; } private void updateCard(Card card, ArrayList<HashMap<String, String>> list, int position) { list.get(position).put("question", Utils.stripHTML(card.getQuestion().replaceAll("<br(\\s*\\/*)>","\n"))); list.get(position).put("answer", Utils.stripHTML(card.getAnswer().replaceAll("<br(\\s*\\/*)>","\n"))); for (long cardId : mDeck.getCardsFromFactId(card.getFactId())) { if (cardId != card.getId()) { int positionC = getPosition(mCards, cardId); int positionA = getPosition(mAllCards, cardId); Card c = mDeck.cardFromId(cardId); String question = Utils.stripHTML(c.getQuestion().replaceAll("<br(\\s*\\/*)>","\n")); String answer = Utils.stripHTML(c.getAnswer().replaceAll("<br(\\s*\\/*)>","\n")); if (positionC != -1) { mCards.get(positionC).put("question", question); mCards.get(positionC).put("answer", answer); } mAllCards.get(positionA).put("question", question); mAllCards.get(positionA).put("answer", answer); } } } private void markCards(long factId, boolean mark) { for (long cardId : mDeck.getCardsFromFactId(factId)) { int positionC = getPosition(mCards, cardId); int positionA = getPosition(mAllCards, cardId); String marSus = mAllCards.get(positionA).get("flags"); if (mark) { marSus = "1" + marSus.substring(1, 2); if (positionC != -1) { mCards.get(positionC).put("flags", marSus); } mAllCards.get(positionA).put("flags", marSus); } else { marSus = "0" + marSus.substring(1, 2); if (positionC != -1) { mCards.get(positionC).put("flags", marSus); } mAllCards.get(positionA).put("flags", marSus); } } updateList(); } private void suspendCard(Card card, int position, boolean suspend) { int posA = getPosition(mAllCards, card.getId()); String marSus = mAllCards.get(posA).remove("flags"); if (suspend) { marSus = marSus.substring(0, 1) + "1"; if (position != -1) { mCards.get(position).put("flags", marSus); } mAllCards.get(posA).put("flags", marSus); } else { marSus = marSus.substring(0, 1) + "0"; if (position != -1) { mCards.get(position).put("flags", marSus); } mAllCards.get(posA).put("flags", marSus); } updateList(); } private void deleteCard(String cardId, int position) { if (mDeletedCards == null) { mDeletedCards = new ArrayList<HashMap<String, String>>(); } HashMap<String, String> data = new HashMap<String, String>(); for (int i = 0; i < mAllCards.size(); i++) { if (mAllCards.get(i).get("id").equals(cardId)) { data.put("id", mAllCards.get(i).get("id")); data.put("question", mAllCards.get(i).get("question")); data.put("answer", mAllCards.get(i).get("answer")); data.put("flags", mAllCards.get(i).get("flags")); data.put("allCardPos", Integer.toString(i)); mDeletedCards.add(data); mAllCards.remove(i); Log.i(AnkiDroidApp.TAG, "Remove card from list"); break; } } mCards.remove(position); updateList(); } private DeckTask.TaskListener mLoadCardsHandler = new DeckTask.TaskListener() { @Override public void onPreExecute() { if (!mUndoRedoDialogShowing) { mProgressDialog = ProgressDialog.show(CardBrowser.this, "", getResources().getString(R.string.card_browser_load), true); } else { mProgressDialog.setMessage(getResources().getString( R.string.card_browser_load)); mUndoRedoDialogShowing = false; } } @Override public void onPostExecute(DeckTask.TaskData result) { // This verification would not be necessary if // onConfigurationChanged it's executed correctly (which seems // that emulator does not do) // DeckTask.launchDeckTask(DeckTask.TASK_TYPE_SORT_CARDS, mSortCardsHandler, new DeckTask.TaskData(mAllCards, new HashMapCompare())); if (mProgressDialog.isShowing()) { try { mProgressDialog.dismiss(); } catch (Exception e) { Log.e(AnkiDroidApp.TAG, "onPostExecute - Dialog dismiss Exception = " + e.getMessage()); } } } @Override public void onProgressUpdate(DeckTask.TaskData... values) { ArrayList<HashMap<String, String>> cards = values[0].getCards(); if (cards == null) { Resources res = getResources(); StyledDialog.Builder builder = new StyledDialog.Builder( CardBrowser.this); builder.setTitle(res.getString(R.string.error)); builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setMessage(res .getString(R.string.card_browser_cardloading_error)); builder.setPositiveButton(res.getString(R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { CardBrowser.this.finish(); } }); builder.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { CardBrowser.this.finish(); } }); builder.create().show(); } else { if (mPrefFixArabic) { for (HashMap<String, String> entry : cards) { entry.put("question", ArabicUtilities.reshapeSentence(entry.get("question"))); entry.put("answer", ArabicUtilities.reshapeSentence(entry.get("answer"))); } } try { mAllCards.addAll(cards); mCards.addAll(cards); } catch (OutOfMemoryError e) { Log.e(AnkiDroidApp.TAG, "CardBrowser: mLoadCardsHandler: OutOfMemoryError: " + e); Themes.showThemedToast(CardBrowser.this, getResources().getString(R.string.error_insufficient_memory), false); finish(); } updateList(); } } }; private DeckTask.TaskListener mMarkCardHandler = new DeckTask.TaskListener() { @Override public void onPreExecute() { Resources res = getResources(); mProgressDialog = ProgressDialog.show(CardBrowser.this, "", res .getString(R.string.saving_changes), true); } @Override public void onProgressUpdate(DeckTask.TaskData... values) { mSelectedCard = values[0].getCard(); markCards(mSelectedCard.getFactId(), !mIsMarked); } @Override public void onPostExecute(DeckTask.TaskData result) { mProgressDialog.dismiss(); } }; private DeckTask.TaskListener mSuspendCardHandler = new DeckTask.TaskListener() { @Override public void onPreExecute() { Resources res = getResources(); mProgressDialog = ProgressDialog.show(CardBrowser.this, "", res .getString(R.string.saving_changes), true); } @Override public void onProgressUpdate(DeckTask.TaskData... values) { suspendCard(mSelectedCard, mPositionInCardsList, !mIsSuspended); } @Override public void onPostExecute(DeckTask.TaskData result) { mProgressDialog.dismiss(); } }; private DeckTask.TaskListener mDeleteCardHandler = new DeckTask.TaskListener() { @Override public void onPreExecute() { Resources res = getResources(); mProgressDialog = ProgressDialog.show(CardBrowser.this, "", res .getString(R.string.saving_changes), true); } @Override public void onProgressUpdate(DeckTask.TaskData... values) { } @Override public void onPostExecute(DeckTask.TaskData result) { deleteCard(result.getString(), mPositionInCardsList); mProgressDialog.dismiss(); } }; private DeckTask.TaskListener mSortCardsHandler = new DeckTask.TaskListener() { @Override public void onPreExecute() { Resources res = getResources(); if (mProgressDialog != null && mProgressDialog.isShowing()) { mProgressDialog.setMessage(res.getString(R.string.card_browser_sorting_cards)); } else { mProgressDialog = ProgressDialog.show(CardBrowser.this, "", res .getString(R.string.card_browser_sorting_cards), true); } } @Override public void onProgressUpdate(DeckTask.TaskData... values) { } @Override public void onPostExecute(DeckTask.TaskData result) { updateCardsList(); if (mProgressDialog != null && mProgressDialog.isShowing()) { mProgressDialog.dismiss(); } } }; private DeckTask.TaskListener mUndoRedoHandler = new DeckTask.TaskListener() { @Override public void onPreExecute() { Resources res = getResources(); mProgressDialog = ProgressDialog.show(CardBrowser.this, "", res .getString(R.string.saving_changes), true); } @Override public void onProgressUpdate(DeckTask.TaskData... values) { } @Override public void onPostExecute(DeckTask.TaskData result) { mUndoRedoCardId = result.getLong(); String undoType = result.getString(); if (undoType.equals(Deck.UNDO_TYPE_DELETE_CARD)) { int position = getPosition(mDeletedCards, mUndoRedoCardId); if (position != -1) { HashMap<String, String> data = new HashMap<String, String>(); data.put("id", mDeletedCards.get(position).get("id")); data.put("question", mDeletedCards.get(position).get( "question")); data.put("answer", mDeletedCards.get(position) .get("answer")); data.put("flags", mDeletedCards.get(position) .get("flags")); mAllCards.add(Integer.parseInt(mDeletedCards.get(position) .get("allCardPos")), data); mDeletedCards.remove(position); updateCardsList(); } else { deleteCard(Long.toString(mUndoRedoCardId), getPosition( mCards, mUndoRedoCardId)); } mProgressDialog.dismiss(); } else { mUndoRedoCard = mDeck.cardFromId(mUndoRedoCardId); if (undoType.equals(Deck.UNDO_TYPE_EDIT_CARD)) { mUndoRedoCard.fromDB(mUndoRedoCardId); int pos = getPosition(mAllCards, mUndoRedoCardId); updateCard(mUndoRedoCard, mAllCards, pos); pos = getPosition(mCards, mUndoRedoCardId); if (pos != -1) { updateCard(mUndoRedoCard, mCards, pos); } updateList(); mProgressDialog.dismiss(); } else if (undoType.equals(Deck.UNDO_TYPE_MARK_CARD)) { markCards(mUndoRedoCard.getFactId(), mUndoRedoCard .isMarked()); mProgressDialog.dismiss(); } else if (undoType.equals(Deck.UNDO_TYPE_SUSPEND_CARD)) { suspendCard(mUndoRedoCard, getPosition(mCards, mUndoRedoCardId), mUndoRedoCard.getSuspendedState()); mProgressDialog.dismiss(); } else { mUndoRedoDialogShowing = true; getCards(); } } } }; private DeckTask.TaskListener mUpdateCardHandler = new DeckTask.TaskListener() { @Override public void onPreExecute() { mProgressDialog = ProgressDialog.show(CardBrowser.this, "", getResources().getString(R.string.saving_changes), true); } @Override public void onProgressUpdate(DeckTask.TaskData... values) { mSelectedCard.fromDB(mSelectedCard.getId()); int pos = getPosition(mAllCards, mSelectedCard.getId()); updateCard(mSelectedCard, mAllCards, pos); pos = getPosition(mCards, mSelectedCard.getId()); if (pos != -1) { updateCard(mSelectedCard, mCards, pos); } updateList(); } @Override public void onPostExecute(DeckTask.TaskData result) { mProgressDialog.dismiss(); } }; public class SizeControlledListAdapter extends SimpleAdapter { private int fontSizeScalePcent; private float originalTextSize = -1.0f; public SizeControlledListAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to, int fontSizeScalePcent) { super(context, data, resource, from, to); this.fontSizeScalePcent = fontSizeScalePcent; } public View getView(int position, View convertView, ViewGroup parent) { View view = super.getView(position, convertView, parent); // Iterate on all first level children if (view instanceof ViewGroup) { ViewGroup group = ((ViewGroup) view); View child; for (int i = 0; i < group.getChildCount(); i++) { child = group.getChildAt(i); // and set text size on all TextViews found if (child instanceof TextView) { // mBrowserFontSize float currentSize = ((TextView) child).getTextSize(); if (originalTextSize < 0) { originalTextSize = ((TextView) child).getTextSize(); } // do nothing when pref is 100% and apply scaling only // once if ((fontSizeScalePcent < 99 || fontSizeScalePcent > 101) && (Math.abs(originalTextSize - currentSize) < 0.1)) { ((TextView) child).setTextSize( TypedValue.COMPLEX_UNIT_SP, originalTextSize * (fontSizeScalePcent / 100.0f)); } } } } return view; } } private class HashMapCompare implements Comparator<HashMap<String, String>> { @Override public int compare(HashMap<String, String> object1, HashMap<String, String> object2) { try { int result; switch (mSelectedOrder) { case CARD_ORDER_ANSWER: result = object1.get("answer").compareToIgnoreCase(object2.get("answer")); if (result == 0) { result = object1.get("question").compareToIgnoreCase(object2.get("question")); } return result; case CARD_ORDER_QUESTION: result = object1.get("question").compareToIgnoreCase(object2.get("question")); if (result == 0) { result = object1.get("answer").compareToIgnoreCase(object2.get("answer")); } return result; case CARD_ORDER_DUE: result = Double.valueOf(object1.get("due")).compareTo(Double.valueOf(object2.get("due"))); if (result == 0) { Long.valueOf(object1.get("id")).compareTo(Long.valueOf(object2.get("id"))); } return result; case CARD_ORDER_INTERVAL: result = Double.valueOf(object1.get("interval")).compareTo(Double.valueOf(object2.get("interval"))); if (result == 0) { Long.valueOf(object1.get("id")).compareTo(Long.valueOf(object2.get("id"))); } return result; case CARD_ORDER_FACTOR: result = Double.valueOf(object1.get("factor")).compareTo(Double.valueOf(object2.get("factor"))); if (result == 0) { Long.valueOf(object1.get("id")).compareTo(Long.valueOf(object2.get("id"))); } return result; case CARD_ORDER_CREATED: result = Double.valueOf(object1.get("created")).compareTo(Double.valueOf(object2.get("created"))); if (result == 0) { Long.valueOf(object1.get("id")).compareTo(Long.valueOf(object2.get("id"))); } return result; } return 0; } catch (Exception e) { Log.e(AnkiDroidApp.TAG, "Error on sorting cards: " + e); return 0; } } } }
true
true
protected void onCreate(Bundle savedInstanceState) { Themes.applyTheme(this); super.onCreate(savedInstanceState); View mainView = getLayoutInflater().inflate(R.layout.card_browser, null); setContentView(mainView); Themes.setContentStyle(mainView, Themes.CALLER_CARDBROWSER); mDeck = AnkiDroidApp.deck(); mDeck.resetUndo(); mBackground = Themes.getCardBrowserBackground(); SharedPreferences preferences = PrefSettings .getSharedPrefs(getBaseContext()); mrelativeBrowserFontSize = preferences.getInt( "relativeCardBrowserFontSize", DEFAULT_FONT_SIZE_RATIO); mPrefFixArabic = preferences.getBoolean("fixArabicText", false); mCards = new ArrayList<HashMap<String, String>>(); mAllCards = new ArrayList<HashMap<String, String>>(); mCardsListView = (ListView) findViewById(R.id.card_browser_list); mCardsAdapter = new SizeControlledListAdapter(this, mCards, R.layout.card_item, new String[] { "question", "answer", "flags" }, new int[] { R.id.card_question, R.id.card_answer, R.id.card_item }, mrelativeBrowserFontSize); mCardsAdapter.setViewBinder(new SimpleAdapter.ViewBinder() { @Override public boolean setViewValue(View view, Object arg1, String text) { if (view.getId() == R.id.card_item) { int which = BACKGROUND_NORMAL; if (text.equals("11")) { which = BACKGROUND_MARKED_SUSPENDED; } else if (text.substring(1, 2).equals("1")) { which = BACKGROUND_SUSPENDED; } else if (text.substring(0, 1).equals("1")) { which = BACKGROUND_MARKED; } view.setBackgroundResource(mBackground[which]); return true; } return false; } }); mCardsListView.setAdapter(mCardsAdapter); mCardsListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent editCard = new Intent(CardBrowser.this, CardEditor.class); editCard.putExtra(CardEditor.CARD_EDITOR_ACTION, CardEditor.EDIT_BROWSER_CARD); mPositionInCardsList = position; mSelectedCard = mDeck.cardFromId(Long.parseLong(mCards.get( mPositionInCardsList).get("id"))); sEditorCard = mSelectedCard; editCard.putExtra("callfromcardbrowser", true); startActivityForResult(editCard, EDIT_CARD); if (Integer.valueOf(android.os.Build.VERSION.SDK) > 4) { ActivityTransitionAnimation.slide(CardBrowser.this, ActivityTransitionAnimation.LEFT); } } }); registerForContextMenu(mCardsListView); mSearchEditText = (EditText) findViewById(R.id.card_browser_search); mSearchEditText.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { mTimerHandler.removeCallbacks(updateList); mTimerHandler.postDelayed(updateList, WAIT_TIME_UNTIL_UPDATE); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { } }); getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); setTitle(mDeck.getDeckName()); allTags = null; mSelectedTags = new HashSet<String>(); getCards(); }
protected void onCreate(Bundle savedInstanceState) { Themes.applyTheme(this); super.onCreate(savedInstanceState); View mainView = getLayoutInflater().inflate(R.layout.card_browser, null); setContentView(mainView); Themes.setContentStyle(mainView, Themes.CALLER_CARDBROWSER); mDeck = AnkiDroidApp.deck(); if (mDeck == null) { finish(); return; } mDeck.resetUndo(); mBackground = Themes.getCardBrowserBackground(); SharedPreferences preferences = PrefSettings .getSharedPrefs(getBaseContext()); mrelativeBrowserFontSize = preferences.getInt( "relativeCardBrowserFontSize", DEFAULT_FONT_SIZE_RATIO); mPrefFixArabic = preferences.getBoolean("fixArabicText", false); mCards = new ArrayList<HashMap<String, String>>(); mAllCards = new ArrayList<HashMap<String, String>>(); mCardsListView = (ListView) findViewById(R.id.card_browser_list); mCardsAdapter = new SizeControlledListAdapter(this, mCards, R.layout.card_item, new String[] { "question", "answer", "flags" }, new int[] { R.id.card_question, R.id.card_answer, R.id.card_item }, mrelativeBrowserFontSize); mCardsAdapter.setViewBinder(new SimpleAdapter.ViewBinder() { @Override public boolean setViewValue(View view, Object arg1, String text) { if (view.getId() == R.id.card_item) { int which = BACKGROUND_NORMAL; if (text.equals("11")) { which = BACKGROUND_MARKED_SUSPENDED; } else if (text.substring(1, 2).equals("1")) { which = BACKGROUND_SUSPENDED; } else if (text.substring(0, 1).equals("1")) { which = BACKGROUND_MARKED; } view.setBackgroundResource(mBackground[which]); return true; } return false; } }); mCardsListView.setAdapter(mCardsAdapter); mCardsListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent editCard = new Intent(CardBrowser.this, CardEditor.class); editCard.putExtra(CardEditor.CARD_EDITOR_ACTION, CardEditor.EDIT_BROWSER_CARD); mPositionInCardsList = position; mSelectedCard = mDeck.cardFromId(Long.parseLong(mCards.get( mPositionInCardsList).get("id"))); sEditorCard = mSelectedCard; editCard.putExtra("callfromcardbrowser", true); startActivityForResult(editCard, EDIT_CARD); if (Integer.valueOf(android.os.Build.VERSION.SDK) > 4) { ActivityTransitionAnimation.slide(CardBrowser.this, ActivityTransitionAnimation.LEFT); } } }); registerForContextMenu(mCardsListView); mSearchEditText = (EditText) findViewById(R.id.card_browser_search); mSearchEditText.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { mTimerHandler.removeCallbacks(updateList); mTimerHandler.postDelayed(updateList, WAIT_TIME_UNTIL_UPDATE); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { } }); getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); setTitle(mDeck.getDeckName()); allTags = null; mSelectedTags = new HashSet<String>(); getCards(); }
diff --git a/tests/filesystem/src/test/java/org/apache/manifoldcf/filesystem_tests/NavigationUITester.java b/tests/filesystem/src/test/java/org/apache/manifoldcf/filesystem_tests/NavigationUITester.java index 79ce1206f..5a4f3772a 100644 --- a/tests/filesystem/src/test/java/org/apache/manifoldcf/filesystem_tests/NavigationUITester.java +++ b/tests/filesystem/src/test/java/org/apache/manifoldcf/filesystem_tests/NavigationUITester.java @@ -1,227 +1,227 @@ /* $Id$ */ /** * 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.manifoldcf.filesystem_tests; import org.apache.manifoldcf.core.interfaces.*; import org.apache.manifoldcf.agents.interfaces.*; import org.apache.manifoldcf.crawler.interfaces.*; import org.apache.manifoldcf.crawler.system.ManifoldCF; import java.io.*; import java.util.*; import org.junit.*; import org.apache.manifoldcf.core.tests.HTMLTester; /** Basic UI navigation tests */ public class NavigationUITester { protected final HTMLTester testerInstance; protected final String startURL; public NavigationUITester(HTMLTester tester, String startURL) { this.testerInstance = tester; this.startURL = startURL; } public void createConnectionsAndJob() throws Exception { testerInstance.newTest(Locale.US); HTMLTester.Window window; HTMLTester.Link link; HTMLTester.Form form; HTMLTester.Textarea textarea; HTMLTester.Selectbox selectbox; HTMLTester.Button button; HTMLTester.Radiobutton radiobutton; HTMLTester.Loop loop; window = testerInstance.openMainWindow(startURL); // Define an output connection via the UI link = window.findLink(testerInstance.createStringDescription("List output connections")); link.click(); window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("Add an output connection")); link.click(); // Fill in a name window = testerInstance.findWindow(null); form = window.findForm(testerInstance.createStringDescription("editconnection")); textarea = form.findTextarea(testerInstance.createStringDescription("connname")); textarea.setValue(testerInstance.createStringDescription("MyOutputConnection")); link = window.findLink(testerInstance.createStringDescription("Type tab")); link.click(); // Select a type window = testerInstance.findWindow(null); form = window.findForm(testerInstance.createStringDescription("editconnection")); selectbox = form.findSelectbox(testerInstance.createStringDescription("classname")); selectbox.selectValue(testerInstance.createStringDescription("org.apache.manifoldcf.agents.output.nullconnector.NullConnector")); button = window.findButton(testerInstance.createStringDescription("Continue to next page")); button.click(); // Visit the Throttling tab window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("Throttling tab")); link.click(); // Go back to the Name tab window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("Name tab")); link.click(); // Now save the connection. window = testerInstance.findWindow(null); button = window.findButton(testerInstance.createStringDescription("Save this output connection")); button.click(); // Define a repository connection via the UI window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("List repository connections")); link.click(); window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("Add a connection")); link.click(); // Fill in a name window = testerInstance.findWindow(null); form = window.findForm(testerInstance.createStringDescription("editconnection")); textarea = form.findTextarea(testerInstance.createStringDescription("connname")); textarea.setValue(testerInstance.createStringDescription("MyRepositoryConnection")); link = window.findLink(testerInstance.createStringDescription("Type tab")); link.click(); // Select a type window = testerInstance.findWindow(null); form = window.findForm(testerInstance.createStringDescription("editconnection")); selectbox = form.findSelectbox(testerInstance.createStringDescription("classname")); selectbox.selectValue(testerInstance.createStringDescription("org.apache.manifoldcf.crawler.connectors.filesystem.FileConnector")); button = window.findButton(testerInstance.createStringDescription("Continue to next page")); button.click(); // Visit the Throttling tab window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("Throttling tab")); link.click(); // Go back to the Name tab window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("Name tab")); link.click(); // Now save the connection. window = testerInstance.findWindow(null); button = window.findButton(testerInstance.createStringDescription("Save this connection")); button.click(); // Create a job window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("List jobs")); link.click(); // Add a job window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("Add a job")); link.click(); // Fill in a name window = testerInstance.findWindow(null); form = window.findForm(testerInstance.createStringDescription("editjob")); textarea = form.findTextarea(testerInstance.createStringDescription("description")); textarea.setValue(testerInstance.createStringDescription("MyJob")); link = window.findLink(testerInstance.createStringDescription("Connection tab")); link.click(); // Select the connections window = testerInstance.findWindow(null); form = window.findForm(testerInstance.createStringDescription("editjob")); selectbox = form.findSelectbox(testerInstance.createStringDescription("outputname")); selectbox.selectValue(testerInstance.createStringDescription("MyOutputConnection")); selectbox = form.findSelectbox(testerInstance.createStringDescription("connectionname")); selectbox.selectValue(testerInstance.createStringDescription("MyRepositoryConnection")); button = window.findButton(testerInstance.createStringDescription("Continue to next screen")); button.click(); // Visit all the tabs. Scheduling tab first window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("Scheduling tab")); link.click(); window = testerInstance.findWindow(null); form = window.findForm(testerInstance.createStringDescription("editjob")); selectbox = form.findSelectbox(testerInstance.createStringDescription("dayofweek")); selectbox.selectValue(testerInstance.createStringDescription("0")); selectbox = form.findSelectbox(testerInstance.createStringDescription("hourofday")); selectbox.selectValue(testerInstance.createStringDescription("1")); selectbox = form.findSelectbox(testerInstance.createStringDescription("minutesofhour")); selectbox.selectValue(testerInstance.createStringDescription("30")); selectbox = form.findSelectbox(testerInstance.createStringDescription("monthofyear")); selectbox.selectValue(testerInstance.createStringDescription("11")); selectbox = form.findSelectbox(testerInstance.createStringDescription("dayofmonth")); selectbox.selectValue(testerInstance.createStringDescription("none")); textarea = form.findTextarea(testerInstance.createStringDescription("duration")); textarea.setValue(testerInstance.createStringDescription("120")); button = window.findButton(testerInstance.createStringDescription("Add new schedule record")); button.click(); // Now, HopFilters window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("Hop Filters tab")); link.click(); window = testerInstance.findWindow(null); form = window.findForm(testerInstance.createStringDescription("editjob")); radiobutton = form.findRadiobutton(testerInstance.createStringDescription("hopcountmode"),testerInstance.createStringDescription("2")); radiobutton.select(); - link = window.findLink(testerInstance.createStringDescription("Paths tab")); + link = window.findLink(testerInstance.createStringDescription("Repository Paths tab")); link.click(); // Add a record to the Paths list // MHL // Save the job window = testerInstance.findWindow(null); button = window.findButton(testerInstance.createStringDescription("Save this job")); button.click(); // Delete the job window = testerInstance.findWindow(null); HTMLTester.StringDescription jobID = window.findMatch(testerInstance.createStringDescription("<!--jobid=(.*?)-->"),0); testerInstance.printValue(jobID); link = window.findLink(testerInstance.createStringDescription("Delete this job")); link.click(); // Wait for the job to go away loop = testerInstance.beginLoop(120); window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("Manage jobs")); link.click(); window = testerInstance.findWindow(null); HTMLTester.StringDescription isJobNotPresent = window.isNotPresent(jobID); testerInstance.printValue(isJobNotPresent); loop.breakWhenTrue(isJobNotPresent); loop.endLoop(); // Delete the repository connection window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("List repository connections")); link.click(); window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("Delete MyRepositoryConnection")); link.click(); // Delete the output connection window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("List output connections")); link.click(); window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("Delete MyOutputConnection")); link.click(); testerInstance.executeTest(); } }
true
true
public void createConnectionsAndJob() throws Exception { testerInstance.newTest(Locale.US); HTMLTester.Window window; HTMLTester.Link link; HTMLTester.Form form; HTMLTester.Textarea textarea; HTMLTester.Selectbox selectbox; HTMLTester.Button button; HTMLTester.Radiobutton radiobutton; HTMLTester.Loop loop; window = testerInstance.openMainWindow(startURL); // Define an output connection via the UI link = window.findLink(testerInstance.createStringDescription("List output connections")); link.click(); window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("Add an output connection")); link.click(); // Fill in a name window = testerInstance.findWindow(null); form = window.findForm(testerInstance.createStringDescription("editconnection")); textarea = form.findTextarea(testerInstance.createStringDescription("connname")); textarea.setValue(testerInstance.createStringDescription("MyOutputConnection")); link = window.findLink(testerInstance.createStringDescription("Type tab")); link.click(); // Select a type window = testerInstance.findWindow(null); form = window.findForm(testerInstance.createStringDescription("editconnection")); selectbox = form.findSelectbox(testerInstance.createStringDescription("classname")); selectbox.selectValue(testerInstance.createStringDescription("org.apache.manifoldcf.agents.output.nullconnector.NullConnector")); button = window.findButton(testerInstance.createStringDescription("Continue to next page")); button.click(); // Visit the Throttling tab window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("Throttling tab")); link.click(); // Go back to the Name tab window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("Name tab")); link.click(); // Now save the connection. window = testerInstance.findWindow(null); button = window.findButton(testerInstance.createStringDescription("Save this output connection")); button.click(); // Define a repository connection via the UI window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("List repository connections")); link.click(); window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("Add a connection")); link.click(); // Fill in a name window = testerInstance.findWindow(null); form = window.findForm(testerInstance.createStringDescription("editconnection")); textarea = form.findTextarea(testerInstance.createStringDescription("connname")); textarea.setValue(testerInstance.createStringDescription("MyRepositoryConnection")); link = window.findLink(testerInstance.createStringDescription("Type tab")); link.click(); // Select a type window = testerInstance.findWindow(null); form = window.findForm(testerInstance.createStringDescription("editconnection")); selectbox = form.findSelectbox(testerInstance.createStringDescription("classname")); selectbox.selectValue(testerInstance.createStringDescription("org.apache.manifoldcf.crawler.connectors.filesystem.FileConnector")); button = window.findButton(testerInstance.createStringDescription("Continue to next page")); button.click(); // Visit the Throttling tab window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("Throttling tab")); link.click(); // Go back to the Name tab window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("Name tab")); link.click(); // Now save the connection. window = testerInstance.findWindow(null); button = window.findButton(testerInstance.createStringDescription("Save this connection")); button.click(); // Create a job window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("List jobs")); link.click(); // Add a job window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("Add a job")); link.click(); // Fill in a name window = testerInstance.findWindow(null); form = window.findForm(testerInstance.createStringDescription("editjob")); textarea = form.findTextarea(testerInstance.createStringDescription("description")); textarea.setValue(testerInstance.createStringDescription("MyJob")); link = window.findLink(testerInstance.createStringDescription("Connection tab")); link.click(); // Select the connections window = testerInstance.findWindow(null); form = window.findForm(testerInstance.createStringDescription("editjob")); selectbox = form.findSelectbox(testerInstance.createStringDescription("outputname")); selectbox.selectValue(testerInstance.createStringDescription("MyOutputConnection")); selectbox = form.findSelectbox(testerInstance.createStringDescription("connectionname")); selectbox.selectValue(testerInstance.createStringDescription("MyRepositoryConnection")); button = window.findButton(testerInstance.createStringDescription("Continue to next screen")); button.click(); // Visit all the tabs. Scheduling tab first window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("Scheduling tab")); link.click(); window = testerInstance.findWindow(null); form = window.findForm(testerInstance.createStringDescription("editjob")); selectbox = form.findSelectbox(testerInstance.createStringDescription("dayofweek")); selectbox.selectValue(testerInstance.createStringDescription("0")); selectbox = form.findSelectbox(testerInstance.createStringDescription("hourofday")); selectbox.selectValue(testerInstance.createStringDescription("1")); selectbox = form.findSelectbox(testerInstance.createStringDescription("minutesofhour")); selectbox.selectValue(testerInstance.createStringDescription("30")); selectbox = form.findSelectbox(testerInstance.createStringDescription("monthofyear")); selectbox.selectValue(testerInstance.createStringDescription("11")); selectbox = form.findSelectbox(testerInstance.createStringDescription("dayofmonth")); selectbox.selectValue(testerInstance.createStringDescription("none")); textarea = form.findTextarea(testerInstance.createStringDescription("duration")); textarea.setValue(testerInstance.createStringDescription("120")); button = window.findButton(testerInstance.createStringDescription("Add new schedule record")); button.click(); // Now, HopFilters window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("Hop Filters tab")); link.click(); window = testerInstance.findWindow(null); form = window.findForm(testerInstance.createStringDescription("editjob")); radiobutton = form.findRadiobutton(testerInstance.createStringDescription("hopcountmode"),testerInstance.createStringDescription("2")); radiobutton.select(); link = window.findLink(testerInstance.createStringDescription("Paths tab")); link.click(); // Add a record to the Paths list // MHL // Save the job window = testerInstance.findWindow(null); button = window.findButton(testerInstance.createStringDescription("Save this job")); button.click(); // Delete the job window = testerInstance.findWindow(null); HTMLTester.StringDescription jobID = window.findMatch(testerInstance.createStringDescription("<!--jobid=(.*?)-->"),0); testerInstance.printValue(jobID); link = window.findLink(testerInstance.createStringDescription("Delete this job")); link.click(); // Wait for the job to go away loop = testerInstance.beginLoop(120); window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("Manage jobs")); link.click(); window = testerInstance.findWindow(null); HTMLTester.StringDescription isJobNotPresent = window.isNotPresent(jobID); testerInstance.printValue(isJobNotPresent); loop.breakWhenTrue(isJobNotPresent); loop.endLoop(); // Delete the repository connection window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("List repository connections")); link.click(); window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("Delete MyRepositoryConnection")); link.click(); // Delete the output connection window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("List output connections")); link.click(); window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("Delete MyOutputConnection")); link.click(); testerInstance.executeTest(); }
public void createConnectionsAndJob() throws Exception { testerInstance.newTest(Locale.US); HTMLTester.Window window; HTMLTester.Link link; HTMLTester.Form form; HTMLTester.Textarea textarea; HTMLTester.Selectbox selectbox; HTMLTester.Button button; HTMLTester.Radiobutton radiobutton; HTMLTester.Loop loop; window = testerInstance.openMainWindow(startURL); // Define an output connection via the UI link = window.findLink(testerInstance.createStringDescription("List output connections")); link.click(); window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("Add an output connection")); link.click(); // Fill in a name window = testerInstance.findWindow(null); form = window.findForm(testerInstance.createStringDescription("editconnection")); textarea = form.findTextarea(testerInstance.createStringDescription("connname")); textarea.setValue(testerInstance.createStringDescription("MyOutputConnection")); link = window.findLink(testerInstance.createStringDescription("Type tab")); link.click(); // Select a type window = testerInstance.findWindow(null); form = window.findForm(testerInstance.createStringDescription("editconnection")); selectbox = form.findSelectbox(testerInstance.createStringDescription("classname")); selectbox.selectValue(testerInstance.createStringDescription("org.apache.manifoldcf.agents.output.nullconnector.NullConnector")); button = window.findButton(testerInstance.createStringDescription("Continue to next page")); button.click(); // Visit the Throttling tab window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("Throttling tab")); link.click(); // Go back to the Name tab window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("Name tab")); link.click(); // Now save the connection. window = testerInstance.findWindow(null); button = window.findButton(testerInstance.createStringDescription("Save this output connection")); button.click(); // Define a repository connection via the UI window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("List repository connections")); link.click(); window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("Add a connection")); link.click(); // Fill in a name window = testerInstance.findWindow(null); form = window.findForm(testerInstance.createStringDescription("editconnection")); textarea = form.findTextarea(testerInstance.createStringDescription("connname")); textarea.setValue(testerInstance.createStringDescription("MyRepositoryConnection")); link = window.findLink(testerInstance.createStringDescription("Type tab")); link.click(); // Select a type window = testerInstance.findWindow(null); form = window.findForm(testerInstance.createStringDescription("editconnection")); selectbox = form.findSelectbox(testerInstance.createStringDescription("classname")); selectbox.selectValue(testerInstance.createStringDescription("org.apache.manifoldcf.crawler.connectors.filesystem.FileConnector")); button = window.findButton(testerInstance.createStringDescription("Continue to next page")); button.click(); // Visit the Throttling tab window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("Throttling tab")); link.click(); // Go back to the Name tab window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("Name tab")); link.click(); // Now save the connection. window = testerInstance.findWindow(null); button = window.findButton(testerInstance.createStringDescription("Save this connection")); button.click(); // Create a job window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("List jobs")); link.click(); // Add a job window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("Add a job")); link.click(); // Fill in a name window = testerInstance.findWindow(null); form = window.findForm(testerInstance.createStringDescription("editjob")); textarea = form.findTextarea(testerInstance.createStringDescription("description")); textarea.setValue(testerInstance.createStringDescription("MyJob")); link = window.findLink(testerInstance.createStringDescription("Connection tab")); link.click(); // Select the connections window = testerInstance.findWindow(null); form = window.findForm(testerInstance.createStringDescription("editjob")); selectbox = form.findSelectbox(testerInstance.createStringDescription("outputname")); selectbox.selectValue(testerInstance.createStringDescription("MyOutputConnection")); selectbox = form.findSelectbox(testerInstance.createStringDescription("connectionname")); selectbox.selectValue(testerInstance.createStringDescription("MyRepositoryConnection")); button = window.findButton(testerInstance.createStringDescription("Continue to next screen")); button.click(); // Visit all the tabs. Scheduling tab first window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("Scheduling tab")); link.click(); window = testerInstance.findWindow(null); form = window.findForm(testerInstance.createStringDescription("editjob")); selectbox = form.findSelectbox(testerInstance.createStringDescription("dayofweek")); selectbox.selectValue(testerInstance.createStringDescription("0")); selectbox = form.findSelectbox(testerInstance.createStringDescription("hourofday")); selectbox.selectValue(testerInstance.createStringDescription("1")); selectbox = form.findSelectbox(testerInstance.createStringDescription("minutesofhour")); selectbox.selectValue(testerInstance.createStringDescription("30")); selectbox = form.findSelectbox(testerInstance.createStringDescription("monthofyear")); selectbox.selectValue(testerInstance.createStringDescription("11")); selectbox = form.findSelectbox(testerInstance.createStringDescription("dayofmonth")); selectbox.selectValue(testerInstance.createStringDescription("none")); textarea = form.findTextarea(testerInstance.createStringDescription("duration")); textarea.setValue(testerInstance.createStringDescription("120")); button = window.findButton(testerInstance.createStringDescription("Add new schedule record")); button.click(); // Now, HopFilters window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("Hop Filters tab")); link.click(); window = testerInstance.findWindow(null); form = window.findForm(testerInstance.createStringDescription("editjob")); radiobutton = form.findRadiobutton(testerInstance.createStringDescription("hopcountmode"),testerInstance.createStringDescription("2")); radiobutton.select(); link = window.findLink(testerInstance.createStringDescription("Repository Paths tab")); link.click(); // Add a record to the Paths list // MHL // Save the job window = testerInstance.findWindow(null); button = window.findButton(testerInstance.createStringDescription("Save this job")); button.click(); // Delete the job window = testerInstance.findWindow(null); HTMLTester.StringDescription jobID = window.findMatch(testerInstance.createStringDescription("<!--jobid=(.*?)-->"),0); testerInstance.printValue(jobID); link = window.findLink(testerInstance.createStringDescription("Delete this job")); link.click(); // Wait for the job to go away loop = testerInstance.beginLoop(120); window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("Manage jobs")); link.click(); window = testerInstance.findWindow(null); HTMLTester.StringDescription isJobNotPresent = window.isNotPresent(jobID); testerInstance.printValue(isJobNotPresent); loop.breakWhenTrue(isJobNotPresent); loop.endLoop(); // Delete the repository connection window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("List repository connections")); link.click(); window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("Delete MyRepositoryConnection")); link.click(); // Delete the output connection window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("List output connections")); link.click(); window = testerInstance.findWindow(null); link = window.findLink(testerInstance.createStringDescription("Delete MyOutputConnection")); link.click(); testerInstance.executeTest(); }
diff --git a/src/Checker/Buffer.java b/src/Checker/Buffer.java index 2fed1b4..4284a6d 100644 --- a/src/Checker/Buffer.java +++ b/src/Checker/Buffer.java @@ -1,82 +1,83 @@ package Checker; import java.util.Stack; import Tag.TagCollection; /** * This is the buffer, it reads through the text from one of the windows and * finds all of the tags and validates that it is valid html * @author Eric Majchrzak * */ public class Buffer { //stack of tags Stack<String> theStack = new Stack<String>(); /** * This is the main method of the buffer that reads through the text and identifies all * of the tags, validates them and checks for the ending tag. * @return String */ public String validate(String text,TagCollection tags){ char[] textArray = text.toCharArray(); boolean inTag = false; String temp = ""; //loop through the text for(int i = 0; i<textArray.length;i++){ //If character is the end of a tag if(inTag == true && textArray[i] == '>'){ //convert temp into an array to check if end tag char[] tempArray = temp.toCharArray(); //If it is an end tag if(tempArray[0] == '/'){ //pop / of string temp = temp.substring(1); //pop off of stack and compare tags if(!(theStack.pop().equals(temp))){ //give invalid tag name return "</" + temp + "> may be spelled incorrectly or in the wrong place"; } //if not an end tag } else { //Check to see if the tag is valid if(!tags.checkTag(temp)){ return "<" + temp + "> is an invalid tag"; } //If valid push onto the stack theStack.push(temp); } //no longer in a tag inTag = false; + temp = ""; } //If in a tag and not end append character to temp if(inTag == true && textArray[i] != '>'){ temp = temp + textArray[i]; } //If the character is the start of a tag put us into a tag if(inTag == false && textArray[i] == '<'){ inTag = true; } } //Check to see if stack is empty after checking everything if(theStack.empty()){ return "Valid HTML"; } //if not empty return "<" + theStack.pop() + "> does not have an end tag."; } }
true
true
public String validate(String text,TagCollection tags){ char[] textArray = text.toCharArray(); boolean inTag = false; String temp = ""; //loop through the text for(int i = 0; i<textArray.length;i++){ //If character is the end of a tag if(inTag == true && textArray[i] == '>'){ //convert temp into an array to check if end tag char[] tempArray = temp.toCharArray(); //If it is an end tag if(tempArray[0] == '/'){ //pop / of string temp = temp.substring(1); //pop off of stack and compare tags if(!(theStack.pop().equals(temp))){ //give invalid tag name return "</" + temp + "> may be spelled incorrectly or in the wrong place"; } //if not an end tag } else { //Check to see if the tag is valid if(!tags.checkTag(temp)){ return "<" + temp + "> is an invalid tag"; } //If valid push onto the stack theStack.push(temp); } //no longer in a tag inTag = false; } //If in a tag and not end append character to temp if(inTag == true && textArray[i] != '>'){ temp = temp + textArray[i]; } //If the character is the start of a tag put us into a tag if(inTag == false && textArray[i] == '<'){ inTag = true; } } //Check to see if stack is empty after checking everything if(theStack.empty()){ return "Valid HTML"; } //if not empty return "<" + theStack.pop() + "> does not have an end tag."; }
public String validate(String text,TagCollection tags){ char[] textArray = text.toCharArray(); boolean inTag = false; String temp = ""; //loop through the text for(int i = 0; i<textArray.length;i++){ //If character is the end of a tag if(inTag == true && textArray[i] == '>'){ //convert temp into an array to check if end tag char[] tempArray = temp.toCharArray(); //If it is an end tag if(tempArray[0] == '/'){ //pop / of string temp = temp.substring(1); //pop off of stack and compare tags if(!(theStack.pop().equals(temp))){ //give invalid tag name return "</" + temp + "> may be spelled incorrectly or in the wrong place"; } //if not an end tag } else { //Check to see if the tag is valid if(!tags.checkTag(temp)){ return "<" + temp + "> is an invalid tag"; } //If valid push onto the stack theStack.push(temp); } //no longer in a tag inTag = false; temp = ""; } //If in a tag and not end append character to temp if(inTag == true && textArray[i] != '>'){ temp = temp + textArray[i]; } //If the character is the start of a tag put us into a tag if(inTag == false && textArray[i] == '<'){ inTag = true; } } //Check to see if stack is empty after checking everything if(theStack.empty()){ return "Valid HTML"; } //if not empty return "<" + theStack.pop() + "> does not have an end tag."; }
diff --git a/target_explorer/plugins/org.eclipse.tcf.te.tcf.filesystem/src/org/eclipse/tcf/te/tcf/filesystem/internal/columns/FSTreeElementComparator.java b/target_explorer/plugins/org.eclipse.tcf.te.tcf.filesystem/src/org/eclipse/tcf/te/tcf/filesystem/internal/columns/FSTreeElementComparator.java index 2d95b62e7..e40605986 100644 --- a/target_explorer/plugins/org.eclipse.tcf.te.tcf.filesystem/src/org/eclipse/tcf/te/tcf/filesystem/internal/columns/FSTreeElementComparator.java +++ b/target_explorer/plugins/org.eclipse.tcf.te.tcf.filesystem/src/org/eclipse/tcf/te/tcf/filesystem/internal/columns/FSTreeElementComparator.java @@ -1,33 +1,34 @@ /******************************************************************************* * Copyright (c) 2011 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.tcf.filesystem.internal.columns; import org.eclipse.tcf.te.tcf.filesystem.model.FSTreeNode; /** * The comparator for the tree column "name". */ public class FSTreeElementComparator extends FSTreeNodeComparator { /* * (non-Javadoc) * @see org.eclipse.tcf.te.tcf.filesystem.internal.columns.FSTreeNodeComparator#doCompare(org.eclipse.tcf.te.tcf.filesystem.model.FSTreeNode, org.eclipse.tcf.te.tcf.filesystem.model.FSTreeNode) */ @Override public int doCompare(FSTreeNode node1, FSTreeNode node2) { String name1 = node1.name; String name2 = node2.name; if (name1 != null && name2 != null) { if (name1.startsWith(".") && !name2.startsWith(".")) return -1; //$NON-NLS-1$ //$NON-NLS-2$ if (!name1.startsWith(".") && name2.startsWith(".")) return 1; //$NON-NLS-1$ //$NON-NLS-2$ + return name1.compareTo(name2); } return 0; } }
true
true
public int doCompare(FSTreeNode node1, FSTreeNode node2) { String name1 = node1.name; String name2 = node2.name; if (name1 != null && name2 != null) { if (name1.startsWith(".") && !name2.startsWith(".")) return -1; //$NON-NLS-1$ //$NON-NLS-2$ if (!name1.startsWith(".") && name2.startsWith(".")) return 1; //$NON-NLS-1$ //$NON-NLS-2$ } return 0; }
public int doCompare(FSTreeNode node1, FSTreeNode node2) { String name1 = node1.name; String name2 = node2.name; if (name1 != null && name2 != null) { if (name1.startsWith(".") && !name2.startsWith(".")) return -1; //$NON-NLS-1$ //$NON-NLS-2$ if (!name1.startsWith(".") && name2.startsWith(".")) return 1; //$NON-NLS-1$ //$NON-NLS-2$ return name1.compareTo(name2); } return 0; }
diff --git a/src/powercrystals/minefactoryreloaded/modhelpers/forestry/Forestry.java b/src/powercrystals/minefactoryreloaded/modhelpers/forestry/Forestry.java index 4fe9e344..2fa9ec4c 100644 --- a/src/powercrystals/minefactoryreloaded/modhelpers/forestry/Forestry.java +++ b/src/powercrystals/minefactoryreloaded/modhelpers/forestry/Forestry.java @@ -1,108 +1,107 @@ package powercrystals.minefactoryreloaded.modhelpers.forestry; import java.lang.reflect.Field; import buildcraft.api.recipes.RefineryRecipe; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.block.Block; import net.minecraftforge.liquids.LiquidContainerData; import net.minecraftforge.liquids.LiquidContainerRegistry; import net.minecraftforge.liquids.LiquidDictionary; import net.minecraftforge.liquids.LiquidStack; import powercrystals.minefactoryreloaded.MineFactoryReloadedCore; import powercrystals.minefactoryreloaded.MFRRegistry; import powercrystals.minefactoryreloaded.api.HarvestType; import powercrystals.minefactoryreloaded.farmables.fertilizables.FertilizerStandard; import powercrystals.minefactoryreloaded.farmables.fertilizables.FertilizableSapling; import powercrystals.minefactoryreloaded.farmables.harvestables.HarvestableStandard; import powercrystals.minefactoryreloaded.farmables.harvestables.HarvestableTreeLeaves; import powercrystals.minefactoryreloaded.farmables.plantables.PlantableStandard; import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.Init; import cpw.mods.fml.common.Mod.PostInit; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.network.NetworkMod; @Mod(modid = "MineFactoryReloaded|CompatForestry", name = "MFR Compat: Forestry", version = MineFactoryReloadedCore.version, dependencies = "after:MineFactoryReloaded;after:Forestry") @NetworkMod(clientSideRequired = false, serverSideRequired = false) public class Forestry { @Init public static void load(FMLInitializationEvent e) { if(!Loader.isModLoaded("Forestry")) { FMLLog.warning("Forestry missing - MFR Forestry Compat not loading"); return; } try { Item fertilizer = (Item)Class.forName("forestry.core.config.ForestryItem").getField("fertilizerCompound").get(null); if(fertilizer != null) { MFRRegistry.registerFertilizer(new FertilizerStandard(fertilizer.itemID, 0)); } Class<?> forestryBlocks = Class.forName("forestry.core.config.ForestryBlock"); if(forestryBlocks != null) { MFRRegistry.registerHarvestable(new HarvestableStandard(((Block)forestryBlocks.getField("log1").get(null)).blockID, HarvestType.Tree)); MFRRegistry.registerHarvestable(new HarvestableStandard(((Block)forestryBlocks.getField("log2").get(null)).blockID, HarvestType.Tree)); MFRRegistry.registerHarvestable(new HarvestableStandard(((Block)forestryBlocks.getField("log3").get(null)).blockID, HarvestType.Tree)); MFRRegistry.registerHarvestable(new HarvestableStandard(((Block)forestryBlocks.getField("log4").get(null)).blockID, HarvestType.Tree)); MFRRegistry.registerHarvestable(new HarvestableStandard(((Block)forestryBlocks.getField("log5").get(null)).blockID, HarvestType.Tree)); MFRRegistry.registerHarvestable(new HarvestableStandard(((Block)forestryBlocks.getField("log6").get(null)).blockID, HarvestType.Tree)); MFRRegistry.registerHarvestable(new HarvestableStandard(((Block)forestryBlocks.getField("log7").get(null)).blockID, HarvestType.Tree)); - MFRRegistry.registerHarvestable(new HarvestableStandard(((Block)forestryBlocks.getField("log8").get(null)).blockID, HarvestType.Tree)); MFRRegistry.registerHarvestable(new HarvestableTreeLeaves(((Block)forestryBlocks.getField("leaves").get(null)).blockID)); MFRRegistry.registerPlantable(new PlantableStandard(((Block)forestryBlocks.getField("saplingGE").get(null)).blockID, ((Block)forestryBlocks.getField("saplingGE").get(null)).blockID)); MFRRegistry.registerFertilizable(new FertilizableSapling(((Block)forestryBlocks.getField("saplingGE").get(null)).blockID)); } } catch (Exception x) { x.printStackTrace(); } } @PostInit public static void postInit(FMLPostInitializationEvent e) { if(!Loader.isModLoaded("Forestry")) { return; } LiquidContainerRegistry.registerLiquid(new LiquidContainerData(LiquidDictionary.getOrCreateLiquid("milk", new LiquidStack(MineFactoryReloadedCore.milkLiquid, LiquidContainerRegistry.BUCKET_VOLUME)), new ItemStack(Item.bucketMilk), new ItemStack(Item.bucketEmpty))); LiquidContainerRegistry.registerLiquid(new LiquidContainerData(LiquidDictionary.getOrCreateLiquid("sludge", new LiquidStack(MineFactoryReloadedCore.sludgeLiquid, LiquidContainerRegistry.BUCKET_VOLUME)), new ItemStack(MineFactoryReloadedCore.sludgeBucketItem), new ItemStack(Item.bucketEmpty))); LiquidContainerRegistry.registerLiquid(new LiquidContainerData(LiquidDictionary.getOrCreateLiquid("sewage", new LiquidStack(MineFactoryReloadedCore.sewageLiquid, LiquidContainerRegistry.BUCKET_VOLUME)), new ItemStack(MineFactoryReloadedCore.sewageBucketItem), new ItemStack(Item.bucketEmpty))); LiquidContainerRegistry.registerLiquid(new LiquidContainerData(LiquidDictionary.getOrCreateLiquid("mobEssence", new LiquidStack(MineFactoryReloadedCore.essenceLiquid, LiquidContainerRegistry.BUCKET_VOLUME)), new ItemStack(MineFactoryReloadedCore.mobEssenceBucketItem), new ItemStack(Item.bucketEmpty))); LiquidContainerRegistry.registerLiquid(new LiquidContainerData(LiquidDictionary.getOrCreateLiquid("biofuel", new LiquidStack(MineFactoryReloadedCore.biofuelLiquid, LiquidContainerRegistry.BUCKET_VOLUME)), new ItemStack(MineFactoryReloadedCore.bioFuelBucketItem), new ItemStack(Item.bucketEmpty))); try { Class<?> forestryItems = Class.forName("forestry.core.config.ForestryItem"); int forestryBiofuelId = ((Item)forestryItems.getField("liquidBiofuel").get(null)).itemID; for(RefineryRecipe rr : RefineryRecipe.getRecipes()) { if(rr.result.itemID == forestryBiofuelId) { LiquidStack newResult = new LiquidStack(LiquidDictionary.getCanonicalLiquid("biofuel").itemID, rr.result.amount, LiquidDictionary.getCanonicalLiquid("biofuel").itemMeta); Field result = RefineryRecipe.class.getField("result"); result.setAccessible(true); result.set(rr, newResult); } } } catch(Exception x) { x.printStackTrace(); } } }
true
true
public static void load(FMLInitializationEvent e) { if(!Loader.isModLoaded("Forestry")) { FMLLog.warning("Forestry missing - MFR Forestry Compat not loading"); return; } try { Item fertilizer = (Item)Class.forName("forestry.core.config.ForestryItem").getField("fertilizerCompound").get(null); if(fertilizer != null) { MFRRegistry.registerFertilizer(new FertilizerStandard(fertilizer.itemID, 0)); } Class<?> forestryBlocks = Class.forName("forestry.core.config.ForestryBlock"); if(forestryBlocks != null) { MFRRegistry.registerHarvestable(new HarvestableStandard(((Block)forestryBlocks.getField("log1").get(null)).blockID, HarvestType.Tree)); MFRRegistry.registerHarvestable(new HarvestableStandard(((Block)forestryBlocks.getField("log2").get(null)).blockID, HarvestType.Tree)); MFRRegistry.registerHarvestable(new HarvestableStandard(((Block)forestryBlocks.getField("log3").get(null)).blockID, HarvestType.Tree)); MFRRegistry.registerHarvestable(new HarvestableStandard(((Block)forestryBlocks.getField("log4").get(null)).blockID, HarvestType.Tree)); MFRRegistry.registerHarvestable(new HarvestableStandard(((Block)forestryBlocks.getField("log5").get(null)).blockID, HarvestType.Tree)); MFRRegistry.registerHarvestable(new HarvestableStandard(((Block)forestryBlocks.getField("log6").get(null)).blockID, HarvestType.Tree)); MFRRegistry.registerHarvestable(new HarvestableStandard(((Block)forestryBlocks.getField("log7").get(null)).blockID, HarvestType.Tree)); MFRRegistry.registerHarvestable(new HarvestableStandard(((Block)forestryBlocks.getField("log8").get(null)).blockID, HarvestType.Tree)); MFRRegistry.registerHarvestable(new HarvestableTreeLeaves(((Block)forestryBlocks.getField("leaves").get(null)).blockID)); MFRRegistry.registerPlantable(new PlantableStandard(((Block)forestryBlocks.getField("saplingGE").get(null)).blockID, ((Block)forestryBlocks.getField("saplingGE").get(null)).blockID)); MFRRegistry.registerFertilizable(new FertilizableSapling(((Block)forestryBlocks.getField("saplingGE").get(null)).blockID)); } } catch (Exception x) { x.printStackTrace(); } }
public static void load(FMLInitializationEvent e) { if(!Loader.isModLoaded("Forestry")) { FMLLog.warning("Forestry missing - MFR Forestry Compat not loading"); return; } try { Item fertilizer = (Item)Class.forName("forestry.core.config.ForestryItem").getField("fertilizerCompound").get(null); if(fertilizer != null) { MFRRegistry.registerFertilizer(new FertilizerStandard(fertilizer.itemID, 0)); } Class<?> forestryBlocks = Class.forName("forestry.core.config.ForestryBlock"); if(forestryBlocks != null) { MFRRegistry.registerHarvestable(new HarvestableStandard(((Block)forestryBlocks.getField("log1").get(null)).blockID, HarvestType.Tree)); MFRRegistry.registerHarvestable(new HarvestableStandard(((Block)forestryBlocks.getField("log2").get(null)).blockID, HarvestType.Tree)); MFRRegistry.registerHarvestable(new HarvestableStandard(((Block)forestryBlocks.getField("log3").get(null)).blockID, HarvestType.Tree)); MFRRegistry.registerHarvestable(new HarvestableStandard(((Block)forestryBlocks.getField("log4").get(null)).blockID, HarvestType.Tree)); MFRRegistry.registerHarvestable(new HarvestableStandard(((Block)forestryBlocks.getField("log5").get(null)).blockID, HarvestType.Tree)); MFRRegistry.registerHarvestable(new HarvestableStandard(((Block)forestryBlocks.getField("log6").get(null)).blockID, HarvestType.Tree)); MFRRegistry.registerHarvestable(new HarvestableStandard(((Block)forestryBlocks.getField("log7").get(null)).blockID, HarvestType.Tree)); MFRRegistry.registerHarvestable(new HarvestableTreeLeaves(((Block)forestryBlocks.getField("leaves").get(null)).blockID)); MFRRegistry.registerPlantable(new PlantableStandard(((Block)forestryBlocks.getField("saplingGE").get(null)).blockID, ((Block)forestryBlocks.getField("saplingGE").get(null)).blockID)); MFRRegistry.registerFertilizable(new FertilizableSapling(((Block)forestryBlocks.getField("saplingGE").get(null)).blockID)); } } catch (Exception x) { x.printStackTrace(); } }
diff --git a/src/main/java/hudson/plugins/ec2/SlaveTemplate.java b/src/main/java/hudson/plugins/ec2/SlaveTemplate.java index 70bbddc..e272f8e 100644 --- a/src/main/java/hudson/plugins/ec2/SlaveTemplate.java +++ b/src/main/java/hudson/plugins/ec2/SlaveTemplate.java @@ -1,213 +1,212 @@ package hudson.plugins.ec2; import com.xerox.amazonws.ec2.EC2Exception; import com.xerox.amazonws.ec2.ImageDescription; import com.xerox.amazonws.ec2.InstanceType; import com.xerox.amazonws.ec2.Jec2; import com.xerox.amazonws.ec2.KeyPairInfo; import com.xerox.amazonws.ec2.ReservationDescription.Instance; import hudson.model.Describable; import hudson.model.Descriptor; import hudson.model.Descriptor.FormException; import hudson.model.Hudson; import hudson.model.TaskListener; import hudson.model.Label; import hudson.model.Node; import hudson.Extension; import hudson.Util; import hudson.model.labels.LabelAtom; import hudson.util.FormValidation; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import javax.servlet.ServletException; import java.io.IOException; import java.io.PrintStream; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Set; /** * Template of {@link EC2Slave} to launch. * * @author Kohsuke Kawaguchi */ public class SlaveTemplate implements Describable<SlaveTemplate> { public final String ami; public final String description; public final String remoteFS; public final String sshPort; public final InstanceType type; public final String labels; public final String initScript; public final String userData; public final String numExecutors; public final String remoteAdmin; public final String rootCommandPrefix; public final String jvmopts; protected transient EC2Cloud parent; private transient /*almost final*/ Set<LabelAtom> labelSet; @DataBoundConstructor public SlaveTemplate(String ami, String remoteFS, String sshPort, InstanceType type, String labelString, String description, String initScript, String userData, String numExecutors, String remoteAdmin, String rootCommandPrefix, String jvmopts) { this.ami = ami; this.remoteFS = remoteFS; this.sshPort = sshPort; this.type = type; this.labels = Util.fixNull(labelString); this.description = description; this.initScript = initScript; this.userData = userData; this.numExecutors = Util.fixNull(numExecutors).trim(); this.remoteAdmin = remoteAdmin; this.rootCommandPrefix = rootCommandPrefix; this.jvmopts = jvmopts; readResolve(); // initialize } public EC2Cloud getParent() { return parent; } public String getLabelString() { return labels; } public String getDisplayName() { return description+" ("+ami+")"; } public int getNumExecutors() { try { return Integer.parseInt(numExecutors); } catch (NumberFormatException e) { return EC2Slave.toNumExecutors(type); } } public int getSshPort() { try { return Integer.parseInt(sshPort); } catch (NumberFormatException e) { return 22; } } public String getRemoteAdmin() { return remoteAdmin; } public String getRootCommandPrefix() { return rootCommandPrefix; } /** * Does this contain the given label? * * @param l * can be null to indicate "don't care". */ public boolean containsLabel(Label l) { return l==null || labelSet.contains(l); } /** * Provisions a new EC2 slave. * * @return always non-null. This needs to be then added to {@link Hudson#addNode(Node)}. */ public EC2Slave provision(TaskListener listener) throws EC2Exception, IOException { PrintStream logger = listener.getLogger(); Jec2 ec2 = getParent().connect(); try { logger.println("Launching "+ami); KeyPairInfo keyPair = parent.getPrivateKey().find(ec2); if(keyPair==null) throw new EC2Exception("No matching keypair found on EC2. Is the EC2 private key a valid one?"); Instance inst = ec2.runInstances(ami, 1, 1, Collections.<String>emptyList(), userData, keyPair.getKeyName(), type).getInstances().get(0); return newSlave(inst); } catch (FormException e) { throw new AssertionError(); // we should have discovered all configuration issues upfront } } private EC2Slave newSlave(Instance inst) throws FormException, IOException { return new EC2Slave(inst.getInstanceId(), description, remoteFS, getSshPort(), getNumExecutors(), labels, initScript, remoteAdmin, rootCommandPrefix, jvmopts); } /** * Provisions a new EC2 slave based on the currently running instance on EC2, * instead of starting a new one. */ public EC2Slave attach(String instanceId, TaskListener listener) throws EC2Exception, IOException { PrintStream logger = listener.getLogger(); Jec2 ec2 = getParent().connect(); try { logger.println("Attaching to "+instanceId); Instance inst = ec2.describeInstances(Collections.singletonList(instanceId)).get(0).getInstances().get(0); return newSlave(inst); } catch (FormException e) { throw new AssertionError(); // we should have discovered all configuration issues upfront } } /** * Initializes data structure that we don't persist. */ protected Object readResolve() { labelSet = Label.parse(labels); return this; } public Descriptor<SlaveTemplate> getDescriptor() { return Hudson.getInstance().getDescriptor(getClass()); } @Extension public static final class DescriptorImpl extends Descriptor<SlaveTemplate> { public String getDisplayName() { return null; } /** * Since this shares much of the configuration with {@link EC2Computer}, check its help page, too. */ @Override public String getHelpFile(String fieldName) { String p = super.getHelpFile(fieldName); if (p==null) p = Hudson.getInstance().getDescriptor(EC2Slave.class).getHelpFile(fieldName); return p; } /*** * Check that the AMI requested is available in the cloud and can be used. */ public FormValidation doValidateAmi( @QueryParameter String accessId, @QueryParameter String secretKey, @QueryParameter AwsRegion region, final @QueryParameter String ami) throws IOException, ServletException { Jec2 jec2 = EC2Cloud.connect(accessId, secretKey, region.ec2Endpoint); if(jec2!=null) { try { List<String> images = new LinkedList<String>(); images.add(ami); List<String> owners = new LinkedList<String>(); List<String> users = new LinkedList<String>(); - users.add("self"); // if we can't run it its not useful. List<ImageDescription> img = jec2.describeImages(images, owners, users); if(img==null || img.isEmpty()) // de-registered AMI causes an empty list to be returned. so be defensive // against other possibilities return FormValidation.error("No such AMI, or not usable with this accessId: "+ami); return FormValidation.ok(img.get(0).getImageLocation()+" by "+img.get(0).getImageOwnerId()); } catch (EC2Exception e) { return FormValidation.error(e.getMessage()); } } else return FormValidation.ok(); // can't test } } }
true
true
public FormValidation doValidateAmi( @QueryParameter String accessId, @QueryParameter String secretKey, @QueryParameter AwsRegion region, final @QueryParameter String ami) throws IOException, ServletException { Jec2 jec2 = EC2Cloud.connect(accessId, secretKey, region.ec2Endpoint); if(jec2!=null) { try { List<String> images = new LinkedList<String>(); images.add(ami); List<String> owners = new LinkedList<String>(); List<String> users = new LinkedList<String>(); users.add("self"); // if we can't run it its not useful. List<ImageDescription> img = jec2.describeImages(images, owners, users); if(img==null || img.isEmpty()) // de-registered AMI causes an empty list to be returned. so be defensive // against other possibilities return FormValidation.error("No such AMI, or not usable with this accessId: "+ami); return FormValidation.ok(img.get(0).getImageLocation()+" by "+img.get(0).getImageOwnerId()); } catch (EC2Exception e) { return FormValidation.error(e.getMessage()); } } else return FormValidation.ok(); // can't test }
public FormValidation doValidateAmi( @QueryParameter String accessId, @QueryParameter String secretKey, @QueryParameter AwsRegion region, final @QueryParameter String ami) throws IOException, ServletException { Jec2 jec2 = EC2Cloud.connect(accessId, secretKey, region.ec2Endpoint); if(jec2!=null) { try { List<String> images = new LinkedList<String>(); images.add(ami); List<String> owners = new LinkedList<String>(); List<String> users = new LinkedList<String>(); List<ImageDescription> img = jec2.describeImages(images, owners, users); if(img==null || img.isEmpty()) // de-registered AMI causes an empty list to be returned. so be defensive // against other possibilities return FormValidation.error("No such AMI, or not usable with this accessId: "+ami); return FormValidation.ok(img.get(0).getImageLocation()+" by "+img.get(0).getImageOwnerId()); } catch (EC2Exception e) { return FormValidation.error(e.getMessage()); } } else return FormValidation.ok(); // can't test }
diff --git a/src/main/org/h2/mvstore/db/TransactionStore.java b/src/main/org/h2/mvstore/db/TransactionStore.java index eca51e69a..ae49c83ae 100644 --- a/src/main/org/h2/mvstore/db/TransactionStore.java +++ b/src/main/org/h2/mvstore/db/TransactionStore.java @@ -1,1590 +1,1590 @@ /* * Copyright 2004-2013 H2 Group. Multiple-Licensed under the H2 License, * Version 1.0, and under the Eclipse Public License, Version 1.0 * (http://h2database.com/html/license.html). * Initial Developer: H2 Group */ package org.h2.mvstore.db; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import org.h2.mvstore.Cursor; import org.h2.mvstore.DataUtils; import org.h2.mvstore.MVMap; import org.h2.mvstore.MVMapConcurrent; import org.h2.mvstore.MVStore; import org.h2.mvstore.WriteBuffer; import org.h2.mvstore.type.DataType; import org.h2.mvstore.type.ObjectDataType; import org.h2.util.New; /** * A store that supports concurrent transactions. */ public class TransactionStore { /** * Whether the concurrent maps should be used. */ private static final boolean CONCURRENT = false; /** * The store. */ final MVStore store; /** * The persisted map of prepared transactions. * Key: transactionId, value: [ status, name ]. */ final MVMap<Integer, Object[]> preparedTransactions; /** * The undo log. * <p> * If the first entry for a transaction doesn't have a logId * of 0, then the transaction is partially committed (which means rollback * is not possible). Log entries are written before the data is changed * (write-ahead). * <p> * Key: [ opId ], value: [ mapId, key, oldValue ]. */ final MVMap<Long, Object[]> undoLog; /** * The map of maps. */ private HashMap<Integer, MVMap<Object, VersionedValue>> maps = New.hashMap(); private final DataType dataType; private int lastTransactionId; private int maxTransactionId = 0xffff; /** * The next id of a temporary map. */ private int nextTempMapId; /** * Create a new transaction store. * * @param store the store */ public TransactionStore(MVStore store) { this(store, new ObjectDataType()); } /** * Create a new transaction store. * * @param store the store * @param dataType the data type for map keys and values */ public TransactionStore(MVStore store, DataType dataType) { this.store = store; this.dataType = dataType; preparedTransactions = store.openMap("openTransactions", new MVMap.Builder<Integer, Object[]>()); VersionedValueType oldValueType = new VersionedValueType(dataType); ArrayType undoLogValueType = new ArrayType(new DataType[]{ new ObjectDataType(), dataType, oldValueType }); MVMap.Builder<Long, Object[]> builder = new MVMap.Builder<Long, Object[]>(). valueType(undoLogValueType); undoLog = store.openMap("undoLog", builder); // remove all temporary maps for (String mapName : store.getMapNames()) { if (mapName.startsWith("temp.")) { MVMap<Object, Integer> temp = openTempMap(mapName); store.removeMap(temp); } } init(); } /** * Set the maximum transaction id, after which ids are re-used. If the old * transaction is still in use when re-using an old id, the new transaction * fails. * * @param max the maximum id */ public void setMaxTransactionId(int max) { this.maxTransactionId = max; } /** * Combine the transaction id and the log id to an operation id. * * @param transactionId the transaction id * @param logId the log id * @return the operation id */ static long getOperationId(int transactionId, long logId) { DataUtils.checkArgument(transactionId >= 0 && transactionId < (1 << 24), "Transaction id out of range: {0}", transactionId); DataUtils.checkArgument(logId >= 0 && logId < (1L << 40), "Transaction log id out of range: {0}", logId); return ((long) transactionId << 40) | logId; } /** * Get the transaction id for the given operation id. * * @param operationId the operation id * @return the transaction id */ static int getTransactionId(long operationId) { return (int) (operationId >>> 40); } /** * Get the log id for the given operation id. * * @param operationId the operation id * @return the log id */ static long getLogId(long operationId) { return operationId & ((1L << 40) - 1); } private synchronized void init() { synchronized (undoLog) { if (undoLog.size() > 0) { Long key = undoLog.firstKey(); lastTransactionId = getTransactionId(key); } } } /** * Get the list of unclosed transactions that have pending writes. * * @return the list of transactions (sorted by id) */ public List<Transaction> getOpenTransactions() { synchronized (undoLog) { ArrayList<Transaction> list = New.arrayList(); Long key = undoLog.firstKey(); while (key != null) { int transactionId = getTransactionId(key); key = undoLog.lowerKey(getOperationId(transactionId + 1, 0)); long logId = getLogId(key) + 1; Object[] data = preparedTransactions.get(transactionId); int status; String name; if (data == null) { if (undoLog.containsKey(getOperationId(transactionId, 0))) { status = Transaction.STATUS_OPEN; } else { status = Transaction.STATUS_COMMITTING; } name = null; } else { status = (Integer) data[0]; name = (String) data[1]; } Transaction t = new Transaction(this, transactionId, status, name, logId); list.add(t); key = undoLog.ceilingKey(getOperationId(transactionId + 1, 0)); } return list; } } /** * Close the transaction store. */ public synchronized void close() { store.commit(); } /** * Begin a new transaction. * * @return the transaction */ public synchronized Transaction begin() { int transactionId = ++lastTransactionId; if (lastTransactionId >= maxTransactionId) { lastTransactionId = 0; } int status = Transaction.STATUS_OPEN; return new Transaction(this, transactionId, status, null, 0); } /** * Store a transaction. * * @param t the transaction */ synchronized void storeTransaction(Transaction t) { if (t.getStatus() == Transaction.STATUS_PREPARED || t.getName() != null) { Object[] v = { t.getStatus(), t.getName() }; preparedTransactions.put(t.getId(), v); } } /** * Log an entry. * * @param t the transaction * @param logId the log id * @param mapId the map id * @param key the key * @param oldValue the old value */ void log(Transaction t, long logId, int mapId, Object key, Object oldValue) { Long undoKey = getOperationId(t.getId(), logId); Object[] log = new Object[] { mapId, key, oldValue }; synchronized (undoLog) { if (logId == 0) { if (undoLog.containsKey(undoKey)) { throw DataUtils.newIllegalStateException( DataUtils.ERROR_TRANSACTION_STILL_OPEN, "An old transaction with the same id is still open: {0}", t.getId()); } } undoLog.put(undoKey, log); } } /** * Remove a log entry. * * @param t the transaction * @param logId the log id */ public void logUndo(Transaction t, long logId) { long[] undoKey = { t.getId(), logId }; synchronized (undoLog) { undoLog.remove(undoKey); } } /** * Remove the given map. * * @param <K> the key type * @param <V> the value type * @param map the map */ synchronized <K, V> void removeMap(TransactionMap<K, V> map) { maps.remove(map.mapId); store.removeMap(map.map); } /** * Commit a transaction. * * @param t the transaction * @param maxLogId the last log id */ void commit(Transaction t, long maxLogId) { if (store.isClosed()) { return; } // TODO could synchronize on blocks (100 at a time or so) synchronized (undoLog) { t.setStatus(Transaction.STATUS_COMMITTING); for (long logId = 0; logId < maxLogId; logId++) { Long undoKey = getOperationId(t.getId(), logId); Object[] op = undoLog.get(undoKey); if (op == null) { // partially committed: load next undoKey = undoLog.ceilingKey(undoKey); if (undoKey == null || getTransactionId(undoKey) != t.getId()) { break; } logId = getLogId(undoKey) - 1; continue; } int mapId = (Integer) op[0]; MVMap<Object, VersionedValue> map = openMap(mapId); if (map == null) { // map was later removed } else { Object key = op[1]; VersionedValue value = map.get(key); if (value == null) { // nothing to do } else if (value.value == null) { // remove the value map.remove(key); } else { VersionedValue v2 = new VersionedValue(); v2.value = value.value; map.put(key, v2); } } undoLog.remove(undoKey); } } endTransaction(t); } /** * Open the map with the given name. * * @param <K> the key type * @param name the map name * @param keyType the key type * @param valueType the value type * @return the map */ synchronized <K> MVMap<K, VersionedValue> openMap(String name, DataType keyType, DataType valueType) { if (keyType == null) { keyType = new ObjectDataType(); } if (valueType == null) { valueType = new ObjectDataType(); } VersionedValueType vt = new VersionedValueType(valueType); MVMap<K, VersionedValue> map; if (CONCURRENT) { MVMapConcurrent.Builder<K, VersionedValue> builder = new MVMapConcurrent.Builder<K, VersionedValue>(). keyType(keyType).valueType(vt); map = store.openMap(name, builder); } else { MVMap.Builder<K, VersionedValue> builder = new MVMap.Builder<K, VersionedValue>(). keyType(keyType).valueType(vt); map = store.openMap(name, builder); } @SuppressWarnings("unchecked") MVMap<Object, VersionedValue> m = (MVMap<Object, VersionedValue>) map; maps.put(map.getId(), m); return map; } /** * Open the map with the given id. * * @param mapId the id * @return the map */ synchronized MVMap<Object, VersionedValue> openMap(int mapId) { MVMap<Object, VersionedValue> map = maps.get(mapId); if (map != null) { return map; } String mapName = store.getMapName(mapId); if (mapName == null) { // the map was removed later on return null; } VersionedValueType vt = new VersionedValueType(dataType); MVMap.Builder<Object, VersionedValue> mapBuilder = new MVMap.Builder<Object, VersionedValue>(). keyType(dataType).valueType(vt); map = store.openMap(mapName, mapBuilder); maps.put(mapId, map); return map; } synchronized MVMap<Object, Integer> createTempMap() { String mapName = "temp." + nextTempMapId++; return openTempMap(mapName); } /** * Open a temporary map. * * @param mapName the map name * @return the map */ MVMap<Object, Integer> openTempMap(String mapName) { MVMap.Builder<Object, Integer> mapBuilder = new MVMap.Builder<Object, Integer>(). keyType(dataType); return store.openMap(mapName, mapBuilder); } /** * End this transaction * * @param t the transaction */ synchronized void endTransaction(Transaction t) { if (t.getStatus() == Transaction.STATUS_PREPARED) { preparedTransactions.remove(t.getId()); } t.setStatus(Transaction.STATUS_CLOSED); if (store.getAutoCommitDelay() == 0) { store.commit(); return; } // to avoid having to store the transaction log, // if there is no open transaction, // and if there have been many changes, store them now if (undoLog.isEmpty()) { int unsaved = store.getUnsavedPageCount(); int max = store.getAutoCommitPageCount(); // save at 3/4 capacity if (unsaved * 4 > max * 3) { store.commit(); } } } /** * Rollback to an old savepoint. * * @param t the transaction * @param maxLogId the last log id * @param toLogId the log id to roll back to */ void rollbackTo(Transaction t, long maxLogId, long toLogId) { // TODO could synchronize on blocks (100 at a time or so) synchronized (undoLog) { for (long logId = maxLogId - 1; logId >= toLogId; logId--) { Long undoKey = getOperationId(t.getId(), logId); Object[] op = undoLog.get(undoKey); if (op == null) { // partially rolled back: load previous undoKey = undoLog.floorKey(undoKey); if (undoKey == null || getTransactionId(undoKey) != t.getId()) { break; } logId = getLogId(undoKey) + 1; continue; } int mapId = ((Integer) op[0]).intValue(); MVMap<Object, VersionedValue> map = openMap(mapId); if (map != null) { Object key = op[1]; VersionedValue oldValue = (VersionedValue) op[2]; if (oldValue == null) { // this transaction added the value map.remove(key); } else { // this transaction updated the value map.put(key, oldValue); } } undoLog.remove(undoKey); } } } /** * Get the changes of the given transaction, starting from the latest log id * back to the given log id. * * @param t the transaction * @param maxLogId the maximum log id * @param toLogId the minimum log id * @return the changes */ Iterator<Change> getChanges(final Transaction t, final long maxLogId, final long toLogId) { return new Iterator<Change>() { private long logId = maxLogId - 1; private Change current; { fetchNext(); } private void fetchNext() { synchronized (undoLog) { while (logId >= toLogId) { Long undoKey = getOperationId(t.getId(), logId); Object[] op = undoLog.get(undoKey); logId--; if (op == null) { // partially rolled back: load previous undoKey = undoLog.floorKey(undoKey); if (undoKey == null || getTransactionId(undoKey) != t.getId()) { break; } logId = getLogId(undoKey); continue; } int mapId = ((Integer) op[0]).intValue(); MVMap<Object, VersionedValue> m = openMap(mapId); if (m == null) { // map was removed later on } else { current = new Change(); current.mapName = m.getName(); current.key = op[1]; VersionedValue oldValue = (VersionedValue) op[2]; current.value = oldValue == null ? null : oldValue.value; return; } } } current = null; } @Override public boolean hasNext() { return current != null; } @Override public Change next() { if (current == null) { throw DataUtils.newUnsupportedOperationException("no data"); } Change result = current; fetchNext(); return result; } @Override public void remove() { throw DataUtils.newUnsupportedOperationException("remove"); } }; } /** * A change in a map. */ public static class Change { /** * The name of the map where the change occurred. */ public String mapName; /** * The key. */ public Object key; /** * The value. */ public Object value; } /** * A transaction. */ public static class Transaction { /** * The status of a closed transaction (committed or rolled back). */ public static final int STATUS_CLOSED = 0; /** * The status of an open transaction. */ public static final int STATUS_OPEN = 1; /** * The status of a prepared transaction. */ public static final int STATUS_PREPARED = 2; /** * The status of a transaction that is being committed, but possibly not * yet finished. A transactions can go into this state when the store is * closed while the transaction is committing. When opening a store, * such transactions should be committed. */ public static final int STATUS_COMMITTING = 3; /** * The transaction store. */ final TransactionStore store; /** * The transaction id. */ final int transactionId; /** * The log id of the last entry in the undo log map. */ long logId; private int status; private String name; Transaction(TransactionStore store, int transactionId, int status, String name, long logId) { this.store = store; this.transactionId = transactionId; this.status = status; this.name = name; this.logId = logId; } public int getId() { return transactionId; } public int getStatus() { return status; } void setStatus(int status) { this.status = status; } public void setName(String name) { checkNotClosed(); this.name = name; store.storeTransaction(this); } public String getName() { return name; } /** * Create a new savepoint. * * @return the savepoint id */ public long setSavepoint() { return logId; } /** * Add a log entry. * * @param mapId the map id * @param key the key * @param oldValue the old value */ void log(int mapId, Object key, Object oldValue) { store.log(this, logId, mapId, key, oldValue); // only increment the log id if logging was successful logId++; } /** * Remove the last log entry. */ void logUndo() { store.logUndo(this, --logId); } /** * Open a data map. * * @param <K> the key type * @param <V> the value type * @param name the name of the map * @return the transaction map */ public <K, V> TransactionMap<K, V> openMap(String name) { return openMap(name, null, null); } /** * Open the map to store the data. * * @param <K> the key type * @param <V> the value type * @param name the name of the map * @param keyType the key data type * @param valueType the value data type * @return the transaction map */ public <K, V> TransactionMap<K, V> openMap(String name, DataType keyType, DataType valueType) { checkNotClosed(); MVMap<K, VersionedValue> map = store.openMap(name, keyType, valueType); int mapId = map.getId(); return new TransactionMap<K, V>(this, map, mapId); } /** * Open the transactional version of the given map. * * @param <K> the key type * @param <V> the value type * @param map the base map * @return the transactional map */ public <K, V> TransactionMap<K, V> openMap(MVMap<K, VersionedValue> map) { checkNotClosed(); int mapId = map.getId(); return new TransactionMap<K, V>(this, map, mapId); } /** * Prepare the transaction. Afterwards, the transaction can only be * committed or rolled back. */ public void prepare() { checkNotClosed(); status = STATUS_PREPARED; store.storeTransaction(this); } /** * Commit the transaction. Afterwards, this transaction is closed. */ public void commit() { checkNotClosed(); store.commit(this, logId); } /** * Roll back to the given savepoint. This is only allowed if the * transaction is open. * * @param savepointId the savepoint id */ public void rollbackToSavepoint(long savepointId) { checkNotClosed(); store.rollbackTo(this, logId, savepointId); logId = savepointId; } /** * Roll the transaction back. Afterwards, this transaction is closed. */ public void rollback() { checkNotClosed(); store.rollbackTo(this, logId, 0); store.endTransaction(this); } /** * Get the list of changes, starting with the latest change, up to the * given savepoint (in reverse order than they occurred). The value of * the change is the value before the change was applied. * * @param savepointId the savepoint id, 0 meaning the beginning of the * transaction * @return the changes */ public Iterator<Change> getChanges(long savepointId) { return store.getChanges(this, logId, savepointId); } /** * Check whether this transaction is open or prepared. */ void checkNotClosed() { if (status == STATUS_CLOSED) { throw DataUtils.newIllegalStateException( DataUtils.ERROR_CLOSED, "Transaction is closed"); } } /** * Remove the map. * * @param map the map */ public <K, V> void removeMap(TransactionMap<K, V> map) { store.removeMap(map); } @Override public String toString() { return "" + transactionId; } } /** * A map that supports transactions. * * @param <K> the key type * @param <V> the value type */ public static class TransactionMap<K, V> { /** * The map id. */ final int mapId; /** * If a record was read that was updated by this transaction, and the * update occurred before this log id, the older version is read. This * is so that changes are not immediately visible, to support statement * processing (for example "update test set id = id + 1"). */ long readLogId = Long.MAX_VALUE; /** * The map used for writing (the latest version). * <p> * Key: key the key of the data. * Value: { transactionId, oldVersion, value } */ final MVMap<K, VersionedValue> map; private Transaction transaction; TransactionMap(Transaction transaction, MVMap<K, VersionedValue> map, int mapId) { this.transaction = transaction; this.map = map; this.mapId = mapId; } /** * Set the savepoint. Afterwards, reads are based on the specified * savepoint. * * @param savepoint the savepoint */ public void setSavepoint(long savepoint) { this.readLogId = savepoint; } /** * Get a clone of this map for the given transaction. * * @param transaction the transaction * @param savepoint the savepoint * @return the map */ public TransactionMap<K, V> getInstance(Transaction transaction, long savepoint) { TransactionMap<K, V> m = new TransactionMap<K, V>(transaction, map, mapId); m.setSavepoint(savepoint); return m; } /** * Get the size of the raw map. This includes uncommitted entries, and * transiently removed entries, so it is the maximum number of entries. * * @return the maximum size */ public long sizeAsLongMax() { return map.sizeAsLong(); } /** * Get the size of the map as seen by this transaction. * * @return the size */ public long sizeAsLong() { long sizeRaw = map.sizeAsLong(); MVMap<Long, Object[]> undo = transaction.store.undoLog; long undoLogSize; synchronized (undo) { undoLogSize = undo.sizeAsLong(); } if (undoLogSize == 0) { return sizeRaw; } if (undoLogSize > sizeRaw) { // the undo log is larger than the map - // count the entries of the map long size = 0; Cursor<K, VersionedValue> cursor = map.cursor(null); while (cursor.hasNext()) { K key = cursor.next(); VersionedValue data = cursor.getValue(); data = getValue(key, readLogId, data); if (data != null && data.value != null) { size++; } } return size; } // the undo log is smaller than the map - // scan the undo log and subtract invisible entries synchronized (undo) { // re-fetch in case any transaction was committed now long size = map.sizeAsLong(); MVMap<Object, Integer> temp = transaction.store.createTempMap(); try { for (Entry<Long, Object[]> e : undo.entrySet()) { Object[] op = e.getValue(); int m = (Integer) op[0]; if (m != mapId) { // a different map - ignore continue; } @SuppressWarnings("unchecked") K key = (K) op[1]; if (get(key) == null) { Integer old = temp.put(key, 1); // count each key only once // (there might be multiple changes for the same key) if (old == null) { size--; } } } } finally { transaction.store.store.removeMap(temp); } return size; } } /** * Remove an entry. * <p> * If the row is locked, this method will retry until the row could be * updated or until a lock timeout. * * @param key the key * @throws IllegalStateException if a lock timeout occurs */ public V remove(K key) { return set(key, null); } /** * Update the value for the given key. * <p> * If the row is locked, this method will retry until the row could be * updated or until a lock timeout. * * @param key the key * @param value the new value (not null) * @return the old value * @throws IllegalStateException if a lock timeout occurs */ public V put(K key, V value) { DataUtils.checkArgument(value != null, "The value may not be null"); return set(key, value); } private V set(K key, V value) { transaction.checkNotClosed(); V old = get(key); boolean ok = trySet(key, value, false); if (ok) { return old; } throw DataUtils.newIllegalStateException( DataUtils.ERROR_TRANSACTION_LOCKED, "Entry is locked"); } /** * Try to remove the value for the given key. * <p> * This will fail if the row is locked by another transaction (that * means, if another open transaction changed the row). * * @param key the key * @return whether the entry could be removed */ public boolean tryRemove(K key) { return trySet(key, null, false); } /** * Try to update the value for the given key. * <p> * This will fail if the row is locked by another transaction (that * means, if another open transaction changed the row). * * @param key the key * @param value the new value * @return whether the entry could be updated */ public boolean tryPut(K key, V value) { DataUtils.checkArgument(value != null, "The value may not be null"); return trySet(key, value, false); } /** * Try to set or remove the value. When updating only unchanged entries, * then the value is only changed if it was not changed after opening * the map. * * @param key the key * @param value the new value (null to remove the value) * @param onlyIfUnchanged only set the value if it was not changed (by * this or another transaction) since the map was opened * @return true if the value was set, false if there was a concurrent update */ public boolean trySet(K key, V value, boolean onlyIfUnchanged) { VersionedValue current = map.get(key); if (onlyIfUnchanged) { VersionedValue old = getValue(key, readLogId); if (!map.areValuesEqual(old, current)) { long tx = getTransactionId(current.operationId); if (tx == transaction.transactionId) { if (value == null) { // ignore removing an entry // if it was added or changed // in the same statement return true; } else if (current.value == null) { // add an entry that was removed // in the same statement } else { return false; } } else { return false; } } } VersionedValue newValue = new VersionedValue(); newValue.operationId = getOperationId( transaction.transactionId, transaction.logId); newValue.value = value; if (current == null) { // a new value transaction.log(mapId, key, current); VersionedValue old = map.putIfAbsent(key, newValue); if (old != null) { transaction.logUndo(); return false; } return true; } long id = current.operationId; if (id == 0) { // committed transaction.log(mapId, key, current); // the transaction is committed: // overwrite the value if (!map.replace(key, current, newValue)) { // somebody else was faster transaction.logUndo(); return false; } return true; } int tx = getTransactionId(current.operationId); if (tx == transaction.transactionId) { // added or updated by this transaction transaction.log(mapId, key, current); if (!map.replace(key, current, newValue)) { - // strange, somebody overwrite the value - // even thought the change was not committed + // strange, somebody overwrote the value + // even though the change was not committed transaction.logUndo(); return false; } return true; } // the transaction is not yet committed return false; } /** * Get the value for the given key at the time when this map was opened. * * @param key the key * @return the value or null */ public V get(K key) { return get(key, readLogId); } /** * Get the most recent value for the given key. * * @param key the key * @return the value or null */ public V getLatest(K key) { return get(key, Long.MAX_VALUE); } /** * Whether the map contains the key. * * @param key the key * @return true if the map contains an entry for this key */ public boolean containsKey(K key) { return get(key) != null; } /** * Get the value for the given key. * * @param key the key * @param maxLogId the maximum log id * @return the value or null */ @SuppressWarnings("unchecked") public V get(K key, long maxLogId) { transaction.checkNotClosed(); VersionedValue data = getValue(key, maxLogId); return data == null ? null : (V) data.value; } /** * Whether the entry for this key was added or removed from this session. * * @param key the key * @return true if yes */ public boolean isSameTransaction(K key) { VersionedValue data = map.get(key); if (data == null) { // doesn't exist or deleted by a committed transaction return false; } int tx = getTransactionId(data.operationId); return tx == transaction.transactionId; } private VersionedValue getValue(K key, long maxLog) { VersionedValue data = map.get(key); return getValue(key, maxLog, data); } /** * Get the versioned value for the given key. * * @param key the key * @param maxLog the maximum log id of the entry * @param data the value stored in the main map * @return the value */ VersionedValue getValue(K key, long maxLog, VersionedValue data) { while (true) { if (data == null) { // doesn't exist or deleted by a committed transaction return null; } long id = data.operationId; if (id == 0) { // it is committed return data; } int tx = getTransactionId(id); if (tx == transaction.transactionId) { // added by this transaction if (getLogId(id) < maxLog) { return data; } } // get the value before the uncommitted transaction Object[] d; synchronized (transaction.store.undoLog) { d = transaction.store.undoLog.get(id); } if (d == null) { // this entry was committed or rolled back // in the meantime (the transaction might still be open) data = map.get(key); } else { data = (VersionedValue) d[2]; } // verify this is either committed, // or the same transaction and earlier if (data != null) { long id2 = data.operationId; if (id2 != 0) { int tx2 = getTransactionId(id2); if (tx2 != tx) { // a different transaction break; } if (getLogId(id2) > getLogId(id)) { // newer than before break; } } } } throw DataUtils.newIllegalStateException( DataUtils.ERROR_TRANSACTION_CORRUPT, "The transaction log might be corrupt for key {0}", key); } /** * Check whether this map is closed. * * @return true if closed */ public boolean isClosed() { return map.isClosed(); } /** * Clear the map. */ public void clear() { // TODO truncate transactionally? map.clear(); } /** * Get the first key. * * @return the first key, or null if empty */ public K firstKey() { Iterator<K> it = keyIterator(null); return it.hasNext() ? it.next() : null; } /** * Get the last key. * * @return the last key, or null if empty */ public K lastKey() { K k = map.lastKey(); while (true) { if (k == null) { return null; } if (get(k) != null) { return k; } k = map.lowerKey(k); } } /** * Get the most recent smallest key that is larger or equal to this key. * * @param key the key (may not be null) * @return the result */ public K getLatestCeilingKey(K key) { Iterator<K> cursor = map.keyIterator(key); while (cursor.hasNext()) { key = cursor.next(); if (get(key, Long.MAX_VALUE) != null) { return key; } } return null; } /** * Get the smallest key that is larger than the given key, or null if no * such key exists. * * @param key the key (may not be null) * @return the result */ public K higherKey(K key) { while (true) { K k = map.higherKey(key); if (k == null || get(k) != null) { return k; } key = k; } } /** * Get the largest key that is smaller than the given key, or null if no * such key exists. * * @param key the key (may not be null) * @return the result */ public K lowerKey(K key) { while (true) { K k = map.lowerKey(key); if (k == null || get(k) != null) { return k; } key = k; } } /** * Iterate over keys. * * @param from the first key to return * @return the iterator */ public Iterator<K> keyIterator(K from) { return keyIterator(from, false); } /** * Iterate over keys. * * @param from the first key to return * @param includeUncommitted whether uncommitted entries should be included * @return the iterator */ public Iterator<K> keyIterator(K from, boolean includeUncommitted) { Iterator<K> it = map.keyIterator(from); return wrapIterator(it, includeUncommitted); } /** * Iterate over entries. * * @param from the first key to return * @return the iterator */ public Iterator<Entry<K, V>> entryIterator(K from) { final Cursor<K, VersionedValue> cursor = map.cursor(from); return new Iterator<Entry<K, V>>() { private Entry<K, V> current; { fetchNext(); } private void fetchNext() { while (cursor.hasNext()) { final K key = cursor.next(); VersionedValue data = cursor.getValue(); data = getValue(key, readLogId, data); if (data != null && data.value != null) { @SuppressWarnings("unchecked") final V value = (V) data.value; current = new DataUtils.MapEntry<K, V>(key, value); return; } } current = null; } @Override public boolean hasNext() { return current != null; } @Override public Entry<K, V> next() { Entry<K, V> result = current; fetchNext(); return result; } @Override public void remove() { throw DataUtils.newUnsupportedOperationException( "Removing is not supported"); } }; } /** * Iterate over keys. * * @param iterator the iterator to wrap * @param includeUncommitted whether uncommitted entries should be included * @return the iterator */ public Iterator<K> wrapIterator(final Iterator<K> iterator, final boolean includeUncommitted) { // TODO duplicate code for wrapIterator and entryIterator return new Iterator<K>() { private K current; { fetchNext(); } private void fetchNext() { while (iterator.hasNext()) { current = iterator.next(); if (includeUncommitted) { return; } if (containsKey(current)) { return; } } current = null; } @Override public boolean hasNext() { return current != null; } @Override public K next() { K result = current; fetchNext(); return result; } @Override public void remove() { throw DataUtils.newUnsupportedOperationException( "Removing is not supported"); } }; } public Transaction getTransaction() { return transaction; } public DataType getKeyType() { return map.getKeyType(); } } /** * A versioned value (possibly null). It contains a pointer to the old * value, and the value itself. */ static class VersionedValue { /** * The operation id. */ public long operationId; /** * The value. */ public Object value; @Override public String toString() { return value + (operationId == 0 ? "" : ( " " + getTransactionId(operationId) + "/" + getLogId(operationId))); } } /** * The value type for a versioned value. */ public static class VersionedValueType implements DataType { private final DataType valueType; VersionedValueType(DataType valueType) { this.valueType = valueType; } @Override public int getMemory(Object obj) { VersionedValue v = (VersionedValue) obj; return valueType.getMemory(v.value) + 8; } @Override public int compare(Object aObj, Object bObj) { if (aObj == bObj) { return 0; } VersionedValue a = (VersionedValue) aObj; VersionedValue b = (VersionedValue) bObj; long comp = a.operationId - b.operationId; if (comp == 0) { return valueType.compare(a.value, b.value); } return Long.signum(comp); } @Override public void write(WriteBuffer buff, Object obj) { VersionedValue v = (VersionedValue) obj; buff.putVarLong(v.operationId); if (v.value == null) { buff.put((byte) 0); } else { buff.put((byte) 1); valueType.write(buff, v.value); } } @Override public Object read(ByteBuffer buff) { VersionedValue v = new VersionedValue(); v.operationId = DataUtils.readVarLong(buff); if (buff.get() == 1) { v.value = valueType.read(buff); } return v; } } /** * A data type that contains an array of objects with the specified data * types. */ public static class ArrayType implements DataType { private final int arrayLength; private final DataType[] elementTypes; ArrayType(DataType[] elementTypes) { this.arrayLength = elementTypes.length; this.elementTypes = elementTypes; } @Override public int getMemory(Object obj) { Object[] array = (Object[]) obj; int size = 0; for (int i = 0; i < arrayLength; i++) { DataType t = elementTypes[i]; Object o = array[i]; if (o != null) { size += t.getMemory(o); } } return size; } @Override public int compare(Object aObj, Object bObj) { if (aObj == bObj) { return 0; } Object[] a = (Object[]) aObj; Object[] b = (Object[]) bObj; for (int i = 0; i < arrayLength; i++) { DataType t = elementTypes[i]; int comp = t.compare(a[i], b[i]); if (comp != 0) { return comp; } } return 0; } @Override public void write(WriteBuffer buff, Object obj) { Object[] array = (Object[]) obj; for (int i = 0; i < arrayLength; i++) { DataType t = elementTypes[i]; Object o = array[i]; if (o == null) { buff.put((byte) 0); } else { buff.put((byte) 1); t.write(buff, o); } } } @Override public Object read(ByteBuffer buff) { Object[] array = new Object[arrayLength]; for (int i = 0; i < arrayLength; i++) { DataType t = elementTypes[i]; if (buff.get() == 1) { array[i] = t.read(buff); } } return array; } } }
true
true
public boolean trySet(K key, V value, boolean onlyIfUnchanged) { VersionedValue current = map.get(key); if (onlyIfUnchanged) { VersionedValue old = getValue(key, readLogId); if (!map.areValuesEqual(old, current)) { long tx = getTransactionId(current.operationId); if (tx == transaction.transactionId) { if (value == null) { // ignore removing an entry // if it was added or changed // in the same statement return true; } else if (current.value == null) { // add an entry that was removed // in the same statement } else { return false; } } else { return false; } } } VersionedValue newValue = new VersionedValue(); newValue.operationId = getOperationId( transaction.transactionId, transaction.logId); newValue.value = value; if (current == null) { // a new value transaction.log(mapId, key, current); VersionedValue old = map.putIfAbsent(key, newValue); if (old != null) { transaction.logUndo(); return false; } return true; } long id = current.operationId; if (id == 0) { // committed transaction.log(mapId, key, current); // the transaction is committed: // overwrite the value if (!map.replace(key, current, newValue)) { // somebody else was faster transaction.logUndo(); return false; } return true; } int tx = getTransactionId(current.operationId); if (tx == transaction.transactionId) { // added or updated by this transaction transaction.log(mapId, key, current); if (!map.replace(key, current, newValue)) { // strange, somebody overwrite the value // even thought the change was not committed transaction.logUndo(); return false; } return true; } // the transaction is not yet committed return false; }
public boolean trySet(K key, V value, boolean onlyIfUnchanged) { VersionedValue current = map.get(key); if (onlyIfUnchanged) { VersionedValue old = getValue(key, readLogId); if (!map.areValuesEqual(old, current)) { long tx = getTransactionId(current.operationId); if (tx == transaction.transactionId) { if (value == null) { // ignore removing an entry // if it was added or changed // in the same statement return true; } else if (current.value == null) { // add an entry that was removed // in the same statement } else { return false; } } else { return false; } } } VersionedValue newValue = new VersionedValue(); newValue.operationId = getOperationId( transaction.transactionId, transaction.logId); newValue.value = value; if (current == null) { // a new value transaction.log(mapId, key, current); VersionedValue old = map.putIfAbsent(key, newValue); if (old != null) { transaction.logUndo(); return false; } return true; } long id = current.operationId; if (id == 0) { // committed transaction.log(mapId, key, current); // the transaction is committed: // overwrite the value if (!map.replace(key, current, newValue)) { // somebody else was faster transaction.logUndo(); return false; } return true; } int tx = getTransactionId(current.operationId); if (tx == transaction.transactionId) { // added or updated by this transaction transaction.log(mapId, key, current); if (!map.replace(key, current, newValue)) { // strange, somebody overwrote the value // even though the change was not committed transaction.logUndo(); return false; } return true; } // the transaction is not yet committed return false; }
diff --git a/examples/org.eclipse.ocl.examples.codegen/src/org/eclipse/ocl/examples/codegen/expression/OCLinEcore2JavaClass.java b/examples/org.eclipse.ocl.examples.codegen/src/org/eclipse/ocl/examples/codegen/expression/OCLinEcore2JavaClass.java index f23964464b..b39797a3a7 100644 --- a/examples/org.eclipse.ocl.examples.codegen/src/org/eclipse/ocl/examples/codegen/expression/OCLinEcore2JavaClass.java +++ b/examples/org.eclipse.ocl.examples.codegen/src/org/eclipse/ocl/examples/codegen/expression/OCLinEcore2JavaClass.java @@ -1,252 +1,260 @@ /** * <copyright> * * Copyright (c) 2011,2012 E.D.Willink 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: * E.D.Willink - initial API and implementation * * </copyright> **/ package org.eclipse.ocl.examples.codegen.expression; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Set; import org.eclipse.emf.codegen.ecore.genmodel.GenClassifier; import org.eclipse.emf.codegen.ecore.genmodel.GenPackage; import org.eclipse.emf.ecore.EClassifier; import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.Nullable; import org.eclipse.ocl.examples.codegen.analyzer.CodeGenAnalysis; import org.eclipse.ocl.examples.codegen.analyzer.CodeGenAnalyzer; import org.eclipse.ocl.examples.codegen.common.PivotQueries; import org.eclipse.ocl.examples.codegen.generator.CodeGenSnippet; import org.eclipse.ocl.examples.codegen.generator.CodeGenText; import org.eclipse.ocl.examples.codegen.generator.java.JavaCodeGenerator; import org.eclipse.ocl.examples.domain.utilities.DomainUtil; import org.eclipse.ocl.examples.domain.values.util.ValuesUtil; import org.eclipse.ocl.examples.pivot.Constraint; import org.eclipse.ocl.examples.pivot.Element; import org.eclipse.ocl.examples.pivot.ExpressionInOCL; import org.eclipse.ocl.examples.pivot.Feature; import org.eclipse.ocl.examples.pivot.NamedElement; import org.eclipse.ocl.examples.pivot.Operation; import org.eclipse.ocl.examples.pivot.Property; import org.eclipse.ocl.examples.pivot.ValueSpecification; import org.eclipse.ocl.examples.pivot.Variable; import org.eclipse.ocl.examples.pivot.manager.MetaModelManager; /** * OCL2JavaClass supports generation of the content of a JavaClassFile to provide the polymorphic implementation * of an ExpressionInOCL. */ public class OCLinEcore2JavaClass extends JavaCodeGenerator { public static final @NonNull String INSTANCE_NAME = "INSTANCE"; protected final @NonNull CodeGenAnalyzer cgAnalyzer; protected final @NonNull EClassifier eClassifier; protected final @NonNull CodeGenSnippet fileSnippet = createCodeGenSnippet("", CodeGenSnippet.LIVE); private static @NonNull Comparator<? super NamedElement> nameComparator = new Comparator<NamedElement>(){ public int compare(NamedElement o1, NamedElement o2) { String n1 = String.valueOf(o1.getName()); String n2 = String.valueOf(o2.getName()); return n1.compareTo(n2); } }; public OCLinEcore2JavaClass(@NonNull MetaModelManager metaModelManager, @NonNull EClassifier eClassifier) { super(metaModelManager); cgAnalyzer = new CodeGenAnalyzer(this); this.eClassifier = eClassifier; nameManager.reserveName(INSTANCE_NAME, null); } private void activateGuards(@NonNull CodeGenAnalysis analysis) { Set<CodeGenAnalysis> invalidGuards = analysis.getInvalidGuards(); if (invalidGuards != null) { for (CodeGenAnalysis invalidGuard : invalidGuards) { getSnippet(invalidGuard.getExpression()).getName(); } } Set<CodeGenAnalysis> nullGuards = analysis.getNullGuards(); if (nullGuards != null) { for (CodeGenAnalysis nullGuard : nullGuards) { getSnippet(nullGuard.getExpression()).getName(); } } CodeGenAnalysis[] children = analysis.getChildren(); if (children != null) { for (CodeGenAnalysis child : children) { assert child != null; activateGuards(child); } } } public @Nullable CodeGenAnalysis findAnalysis(@NonNull Element element) { return cgAnalyzer.findAnalysis(element); } protected void generateInnerClass(@NonNull CodeGenSnippet innerClassSnippet, @NonNull String className, @NonNull String title, @NonNull ExpressionInOCL expression, @Nullable Feature feature) { // System.out.println("innerClass " + className); boolean isRequired = (feature == null) || feature.isRequired(); Class<?> returnClass = feature != null ? getBoxedClass(feature.getTypeId()) : Boolean.class; push(); CodeGenAnalysis rootAnalysis = cgAnalyzer.analyze(expression, isRequired); cgAnalyzer.optimize(rootAnalysis); List<Variable> parameterVariable = DomainUtil.nonNullEMF(expression.getParameterVariable()); Class<?> baseClass = genModelHelper.getAbstractOperationClass(parameterVariable); CodeGenText classDefinition = innerClassSnippet.appendIndentedText(""); classDefinition.appendCommentWithOCL(title, expression); classDefinition.append("public static class " + className + " extends "); classDefinition.appendClassReference(baseClass); classDefinition.append("\n"); classDefinition.append("{\n"); // // Inner Class statics // CodeGenSnippet innerStatics = innerClassSnippet.appendIndentedNodes(null, CodeGenSnippet.LIVE); innerStatics.append("public static final " + innerClassSnippet.atNonNull() + " " + className + " " + INSTANCE_NAME + " = new " + className + "();\n"); // getSnippetLabel(GLOBAL_ROOT).push(globalRoot); innerClassSnippet.append("\n"); generateEvaluateFunction(innerClassSnippet, returnClass, isRequired, expression); innerClassSnippet.append("}\n"); activateGuards(rootAnalysis); pop(); } protected void generateOuterClassDefinition(@NonNull GenClassifier genClassifier, @NonNull String className, @Nullable Class<?> baseClass, @NonNull org.eclipse.ocl.examples.pivot.Class pivotClass) { // @NonNull EClassifier eClassifier = genClassifier.getEcoreClassifier(); // Element element = expInOcl; // String outerTitle = className + " provides the Java implementation for\n"; CodeGenText classDefinition = fileSnippet.appendIndentedText(""); // classDefinition.appendCommentWithOCL(title, element); classDefinition.append("@SuppressWarnings(\"nls\")\n"); classDefinition.append("public class " + className); if (baseClass != null) { classDefinition.append(" extends "); classDefinition.appendClassReference(baseClass); } classDefinition.append("\n"); classDefinition.append("{\n"); // // Outer class statics // CodeGenSnippet globalRoot = fileSnippet.appendIndentedNodes(null, CodeGenSnippet.LIVE); // globalRoot.append("public static " + fileSnippet.atNonNull() + " " + className + " " + instanceName + " = new " + className + "();\n"); getSnippetLabel(GLOBAL_ROOT).push(globalRoot); // // Class invariants // List<Constraint> ownedRules = new ArrayList<Constraint>(pivotClass.getOwnedRule()); Collections.sort(ownedRules, nameComparator); for (Constraint constraint : ownedRules) { ValueSpecification specification = DomainUtil.nonNullModel(constraint.getSpecification()); ExpressionInOCL expression = PivotQueries.getExpressionInOCL(pivotClass, specification); if ((expression != null) && (expression.getContextVariable() != null)) { fileSnippet.append("\n"); CodeGenSnippet innerClassSnippet = fileSnippet.appendIndentedNodes(null, 0); - String innerClassName = "_" + constraint.getStereotype() + "_" + constraint.getName(); - String innerTitle = "Implementation of the " + pivotClass.getName() + " '" + constraint.getName() + "' <" + constraint.getStereotype() + ">\n"; + String constraintName = constraint.getName(); + if (constraintName == null) { + constraintName = ""; + } + String innerClassName = "_" + constraint.getStereotype() + "_" + constraintName; + String innerTitle = "Implementation of the " + pivotClass.getName() + " '" + constraintName + "' <" + constraint.getStereotype() + ">\n"; generateInnerClass(innerClassSnippet, innerClassName, innerTitle, expression, null); } } // // Operation bodies // List<Operation> ownedOperations = new ArrayList<Operation>(PivotQueries.getOperations(pivotClass)); Collections.sort(ownedOperations, nameComparator); for (Operation anOperation : ownedOperations) { assert anOperation != null; for (Constraint constraint : anOperation.getOwnedRule()) { ValueSpecification specification = DomainUtil.nonNullModel(constraint.getSpecification()); ExpressionInOCL expression = PivotQueries.getExpressionInOCL(anOperation, specification); if ((expression != null) && (expression.getContextVariable() != null)) { fileSnippet.append("\n"); CodeGenSnippet innerClassSnippet = fileSnippet.appendIndentedNodes(null, 0); String constraintName = constraint.getName(); if (constraintName == null) { constraintName = ""; } String innerClassName = "_" + anOperation.getName() + "_" + constraint.getStereotype() + "_" + constraintName; String innerTitle = "Implementation of the " + pivotClass.getName() + "::" + anOperation.getName() + " '" + constraintName + "' <" + constraint.getStereotype() + ">\n"; generateInnerClass(innerClassSnippet, innerClassName, innerTitle, expression, anOperation); } } } // // Property bodies // List<Property> ownedProperties = new ArrayList<Property>(PivotQueries.getProperties(pivotClass)); Collections.sort(ownedProperties, nameComparator); for (Property aProperty : ownedProperties) { assert aProperty != null; for (Constraint constraint : aProperty.getOwnedRule()) { ValueSpecification specification = DomainUtil.nonNullModel(constraint.getSpecification()); ExpressionInOCL expression = PivotQueries.getExpressionInOCL(aProperty, specification); if ((expression != null) && (expression.getContextVariable() != null)) { fileSnippet.append("\n"); CodeGenSnippet innerClassSnippet = fileSnippet.appendIndentedNodes(null, 0); - String innerClassName = "_" + aProperty.getName() + "_" + constraint.getStereotype() + "_" + constraint.getName(); - String innerTitle = "Implementation of the " + pivotClass.getName() + "::" + aProperty.getName() + " '" + constraint.getName() + "' <" + constraint.getStereotype() + ">\n"; + String constraintName = constraint.getName(); + if (constraintName == null) { + constraintName = ""; + } + String innerClassName = "_" + aProperty.getName() + "_" + constraint.getStereotype() + "_" + constraintName; + String innerTitle = "Implementation of the " + pivotClass.getName() + "::" + aProperty.getName() + " '" + constraintName + "' <" + constraint.getStereotype() + ">\n"; generateInnerClass(innerClassSnippet, innerClassName, innerTitle, expression, aProperty); } } } fileSnippet.append("}\n"); } public @NonNull CodeGenSnippet generateClassFile(@NonNull GenClassifier genClassifier, @NonNull String packageName, @NonNull String className, @NonNull org.eclipse.ocl.examples.pivot.Class pivotClass) { @SuppressWarnings("null")@NonNull GenPackage genPackage = genClassifier.getGenPackage(); String copyright = genPackage.getCopyright(" "); fileSnippet.append("/**\n"); CodeGenText commentBody = fileSnippet.appendIndentedText(" *"); if (copyright != null) { commentBody.append(copyright); commentBody.append("\n"); } commentBody.append("************************************************************************\n"); commentBody.append(" This code is 100% auto-generated\n"); commentBody.append(" using: " + getClass().getName() + "\n"); commentBody.append("\n"); commentBody.append(" Do not edit it.\n"); commentBody.append("/\n"); fileSnippet.append("package " + packageName + ";\n"); fileSnippet.append("\n"); // CodeGenText importsBlock = fileSnippet.appendIndentedText(""); // generateOuterClassDefinition(genClassifier, className, ValuesUtil.class, pivotClass); // resolveLiveImports(importsBlock); importsBlock.append("\n"); return fileSnippet; } public @NonNull CodeGenAnalysis getAnalysis(@NonNull Element element) { return cgAnalyzer.getAnalysis(element); } protected void resolveLiveImports(@NonNull CodeGenText importsBlock) { Set<String> referencedClasses = new HashSet<String>(); fileSnippet.gatherLiveSnippets(new HashSet<CodeGenSnippet>(), referencedClasses); List<String> allImports = new ArrayList<String>(referencedClasses); Collections.sort(allImports); for (String anImport : allImports) { importsBlock.append("import " + anImport + ";\n"); } } }
false
true
protected void generateOuterClassDefinition(@NonNull GenClassifier genClassifier, @NonNull String className, @Nullable Class<?> baseClass, @NonNull org.eclipse.ocl.examples.pivot.Class pivotClass) { // @NonNull EClassifier eClassifier = genClassifier.getEcoreClassifier(); // Element element = expInOcl; // String outerTitle = className + " provides the Java implementation for\n"; CodeGenText classDefinition = fileSnippet.appendIndentedText(""); // classDefinition.appendCommentWithOCL(title, element); classDefinition.append("@SuppressWarnings(\"nls\")\n"); classDefinition.append("public class " + className); if (baseClass != null) { classDefinition.append(" extends "); classDefinition.appendClassReference(baseClass); } classDefinition.append("\n"); classDefinition.append("{\n"); // // Outer class statics // CodeGenSnippet globalRoot = fileSnippet.appendIndentedNodes(null, CodeGenSnippet.LIVE); // globalRoot.append("public static " + fileSnippet.atNonNull() + " " + className + " " + instanceName + " = new " + className + "();\n"); getSnippetLabel(GLOBAL_ROOT).push(globalRoot); // // Class invariants // List<Constraint> ownedRules = new ArrayList<Constraint>(pivotClass.getOwnedRule()); Collections.sort(ownedRules, nameComparator); for (Constraint constraint : ownedRules) { ValueSpecification specification = DomainUtil.nonNullModel(constraint.getSpecification()); ExpressionInOCL expression = PivotQueries.getExpressionInOCL(pivotClass, specification); if ((expression != null) && (expression.getContextVariable() != null)) { fileSnippet.append("\n"); CodeGenSnippet innerClassSnippet = fileSnippet.appendIndentedNodes(null, 0); String innerClassName = "_" + constraint.getStereotype() + "_" + constraint.getName(); String innerTitle = "Implementation of the " + pivotClass.getName() + " '" + constraint.getName() + "' <" + constraint.getStereotype() + ">\n"; generateInnerClass(innerClassSnippet, innerClassName, innerTitle, expression, null); } } // // Operation bodies // List<Operation> ownedOperations = new ArrayList<Operation>(PivotQueries.getOperations(pivotClass)); Collections.sort(ownedOperations, nameComparator); for (Operation anOperation : ownedOperations) { assert anOperation != null; for (Constraint constraint : anOperation.getOwnedRule()) { ValueSpecification specification = DomainUtil.nonNullModel(constraint.getSpecification()); ExpressionInOCL expression = PivotQueries.getExpressionInOCL(anOperation, specification); if ((expression != null) && (expression.getContextVariable() != null)) { fileSnippet.append("\n"); CodeGenSnippet innerClassSnippet = fileSnippet.appendIndentedNodes(null, 0); String constraintName = constraint.getName(); if (constraintName == null) { constraintName = ""; } String innerClassName = "_" + anOperation.getName() + "_" + constraint.getStereotype() + "_" + constraintName; String innerTitle = "Implementation of the " + pivotClass.getName() + "::" + anOperation.getName() + " '" + constraintName + "' <" + constraint.getStereotype() + ">\n"; generateInnerClass(innerClassSnippet, innerClassName, innerTitle, expression, anOperation); } } } // // Property bodies // List<Property> ownedProperties = new ArrayList<Property>(PivotQueries.getProperties(pivotClass)); Collections.sort(ownedProperties, nameComparator); for (Property aProperty : ownedProperties) { assert aProperty != null; for (Constraint constraint : aProperty.getOwnedRule()) { ValueSpecification specification = DomainUtil.nonNullModel(constraint.getSpecification()); ExpressionInOCL expression = PivotQueries.getExpressionInOCL(aProperty, specification); if ((expression != null) && (expression.getContextVariable() != null)) { fileSnippet.append("\n"); CodeGenSnippet innerClassSnippet = fileSnippet.appendIndentedNodes(null, 0); String innerClassName = "_" + aProperty.getName() + "_" + constraint.getStereotype() + "_" + constraint.getName(); String innerTitle = "Implementation of the " + pivotClass.getName() + "::" + aProperty.getName() + " '" + constraint.getName() + "' <" + constraint.getStereotype() + ">\n"; generateInnerClass(innerClassSnippet, innerClassName, innerTitle, expression, aProperty); } } } fileSnippet.append("}\n"); }
protected void generateOuterClassDefinition(@NonNull GenClassifier genClassifier, @NonNull String className, @Nullable Class<?> baseClass, @NonNull org.eclipse.ocl.examples.pivot.Class pivotClass) { // @NonNull EClassifier eClassifier = genClassifier.getEcoreClassifier(); // Element element = expInOcl; // String outerTitle = className + " provides the Java implementation for\n"; CodeGenText classDefinition = fileSnippet.appendIndentedText(""); // classDefinition.appendCommentWithOCL(title, element); classDefinition.append("@SuppressWarnings(\"nls\")\n"); classDefinition.append("public class " + className); if (baseClass != null) { classDefinition.append(" extends "); classDefinition.appendClassReference(baseClass); } classDefinition.append("\n"); classDefinition.append("{\n"); // // Outer class statics // CodeGenSnippet globalRoot = fileSnippet.appendIndentedNodes(null, CodeGenSnippet.LIVE); // globalRoot.append("public static " + fileSnippet.atNonNull() + " " + className + " " + instanceName + " = new " + className + "();\n"); getSnippetLabel(GLOBAL_ROOT).push(globalRoot); // // Class invariants // List<Constraint> ownedRules = new ArrayList<Constraint>(pivotClass.getOwnedRule()); Collections.sort(ownedRules, nameComparator); for (Constraint constraint : ownedRules) { ValueSpecification specification = DomainUtil.nonNullModel(constraint.getSpecification()); ExpressionInOCL expression = PivotQueries.getExpressionInOCL(pivotClass, specification); if ((expression != null) && (expression.getContextVariable() != null)) { fileSnippet.append("\n"); CodeGenSnippet innerClassSnippet = fileSnippet.appendIndentedNodes(null, 0); String constraintName = constraint.getName(); if (constraintName == null) { constraintName = ""; } String innerClassName = "_" + constraint.getStereotype() + "_" + constraintName; String innerTitle = "Implementation of the " + pivotClass.getName() + " '" + constraintName + "' <" + constraint.getStereotype() + ">\n"; generateInnerClass(innerClassSnippet, innerClassName, innerTitle, expression, null); } } // // Operation bodies // List<Operation> ownedOperations = new ArrayList<Operation>(PivotQueries.getOperations(pivotClass)); Collections.sort(ownedOperations, nameComparator); for (Operation anOperation : ownedOperations) { assert anOperation != null; for (Constraint constraint : anOperation.getOwnedRule()) { ValueSpecification specification = DomainUtil.nonNullModel(constraint.getSpecification()); ExpressionInOCL expression = PivotQueries.getExpressionInOCL(anOperation, specification); if ((expression != null) && (expression.getContextVariable() != null)) { fileSnippet.append("\n"); CodeGenSnippet innerClassSnippet = fileSnippet.appendIndentedNodes(null, 0); String constraintName = constraint.getName(); if (constraintName == null) { constraintName = ""; } String innerClassName = "_" + anOperation.getName() + "_" + constraint.getStereotype() + "_" + constraintName; String innerTitle = "Implementation of the " + pivotClass.getName() + "::" + anOperation.getName() + " '" + constraintName + "' <" + constraint.getStereotype() + ">\n"; generateInnerClass(innerClassSnippet, innerClassName, innerTitle, expression, anOperation); } } } // // Property bodies // List<Property> ownedProperties = new ArrayList<Property>(PivotQueries.getProperties(pivotClass)); Collections.sort(ownedProperties, nameComparator); for (Property aProperty : ownedProperties) { assert aProperty != null; for (Constraint constraint : aProperty.getOwnedRule()) { ValueSpecification specification = DomainUtil.nonNullModel(constraint.getSpecification()); ExpressionInOCL expression = PivotQueries.getExpressionInOCL(aProperty, specification); if ((expression != null) && (expression.getContextVariable() != null)) { fileSnippet.append("\n"); CodeGenSnippet innerClassSnippet = fileSnippet.appendIndentedNodes(null, 0); String constraintName = constraint.getName(); if (constraintName == null) { constraintName = ""; } String innerClassName = "_" + aProperty.getName() + "_" + constraint.getStereotype() + "_" + constraintName; String innerTitle = "Implementation of the " + pivotClass.getName() + "::" + aProperty.getName() + " '" + constraintName + "' <" + constraint.getStereotype() + ">\n"; generateInnerClass(innerClassSnippet, innerClassName, innerTitle, expression, aProperty); } } } fileSnippet.append("}\n"); }
diff --git a/src/me/neatmonster/spacebukkit/PingListener.java b/src/me/neatmonster/spacebukkit/PingListener.java index 5f4a2ef..ceb37cb 100644 --- a/src/me/neatmonster/spacebukkit/PingListener.java +++ b/src/me/neatmonster/spacebukkit/PingListener.java @@ -1,130 +1,131 @@ /* * This file is part of SpaceBukkit (http://spacebukkit.xereo.net/). * * SpaceBukkit is free software: you can redistribute it and/or modify it under the terms of the * Attribution-NonCommercial-ShareAlike Unported (CC BY-NC-SA) license as published by the Creative Common organization, * either version 3.0 of the license, or (at your option) any later version. * * SpaceBukkit 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 Attribution-NonCommercial-ShareAlike * Unported (CC BY-NC-SA) license for more details. * * You should have received a copy of the Attribution-NonCommercial-ShareAlike Unported (CC BY-NC-SA) license along with * this program. If not, see <http://creativecommons.org/licenses/by-nc-sa/3.0/>. */ package me.neatmonster.spacebukkit; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.util.concurrent.atomic.AtomicBoolean; /** * Pings the Module to ensure it is functioning correctly */ public class PingListener extends Thread { public static final int REQUEST_THRESHOLD = 60000; // Sixty seconds public static final int SLEEP_TIME = 30000; // Thirty seconds private boolean lostModule; private DatagramSocket socket; private AtomicBoolean running = new AtomicBoolean(false); private InetAddress localHost; /** * Creates a new PingListener */ public PingListener() { super("Ping Listener Main Thread"); try { this.localHost = InetAddress.getLocalHost(); } catch (UnknownHostException e) { handleException(e, "Unable to get the Local Host!"); } this.lostModule = false; try { this.socket = new DatagramSocket(); } catch (IOException e) { handleException(e, "Unable to start the PingListener"); } } /** * Starts the Ping Listener */ public void startup() { this.running.set(true); this.start(); } @Override public void run() { try { socket.setSoTimeout(REQUEST_THRESHOLD); } catch (SocketException e) { handleException(e, "Error setting the So Timeout!"); } while (running.get()) { byte[] buffer = new byte[512]; + buffer[0] = 1; try { DatagramPacket packet = new DatagramPacket(buffer, buffer.length, localHost, SpaceBukkit.getInstance().pingPort); socket.send(packet); try { Thread.sleep(SLEEP_TIME); } catch (InterruptedException e) { handleException(e, "Error sleeping in the run() loop!"); } socket.receive(packet); } catch (SocketTimeoutException e) { onModuleNotFound(); } catch (IOException e) { handleException(e, "Error sending and receiving the plugin packet!"); } } } /** * Shuts down the Ping Listener */ public void shutdown() { this.running.set(false); } /** * Called when an exception is thrown * * @param e * Exception thrown */ public void handleException(Exception e, String reason) { shutdown(); System.err.println("[SpaceBukkit] Ping Listener Error!"); System.err.println(reason); System.err.println("Error message:"); e.printStackTrace(); } /** * Called when the Module can't be found */ public void onModuleNotFound() { if (lostModule) { return; } shutdown(); System.err.println("[SpaceBukkit] Unable to ping the Module!"); System.err .println("[SpaceBukkit] Please insure the correct ports are open"); System.err .println("[SpaceBukkit] Please contact the forums (http://forums.xereo.net/) or IRC (#SpaceBukkit on irc.esper.net)"); lostModule = true; } }
true
true
public void run() { try { socket.setSoTimeout(REQUEST_THRESHOLD); } catch (SocketException e) { handleException(e, "Error setting the So Timeout!"); } while (running.get()) { byte[] buffer = new byte[512]; try { DatagramPacket packet = new DatagramPacket(buffer, buffer.length, localHost, SpaceBukkit.getInstance().pingPort); socket.send(packet); try { Thread.sleep(SLEEP_TIME); } catch (InterruptedException e) { handleException(e, "Error sleeping in the run() loop!"); } socket.receive(packet); } catch (SocketTimeoutException e) { onModuleNotFound(); } catch (IOException e) { handleException(e, "Error sending and receiving the plugin packet!"); } } }
public void run() { try { socket.setSoTimeout(REQUEST_THRESHOLD); } catch (SocketException e) { handleException(e, "Error setting the So Timeout!"); } while (running.get()) { byte[] buffer = new byte[512]; buffer[0] = 1; try { DatagramPacket packet = new DatagramPacket(buffer, buffer.length, localHost, SpaceBukkit.getInstance().pingPort); socket.send(packet); try { Thread.sleep(SLEEP_TIME); } catch (InterruptedException e) { handleException(e, "Error sleeping in the run() loop!"); } socket.receive(packet); } catch (SocketTimeoutException e) { onModuleNotFound(); } catch (IOException e) { handleException(e, "Error sending and receiving the plugin packet!"); } } }
diff --git a/maqetta.core.server/src/org/maqetta/server/ServerManager.java b/maqetta.core.server/src/org/maqetta/server/ServerManager.java index 635d91c6e..0d97fd532 100644 --- a/maqetta.core.server/src/org/maqetta/server/ServerManager.java +++ b/maqetta.core.server/src/org/maqetta/server/ServerManager.java @@ -1,260 +1,262 @@ package org.maqetta.server; import java.io.File; import java.util.ArrayList; import java.util.List; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NameNotFoundException; import javax.naming.NamingException; import javax.servlet.ServletConfig; import org.davinci.ajaxLibrary.ILibraryManager; import org.davinci.ajaxLibrary.LibraryManager; import org.davinci.server.internal.Activator; import org.davinci.server.internal.IRegistryListener; import org.davinci.server.user.IUserManager; import org.davinci.server.user.IPersonManager; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.IExtension; import org.eclipse.core.runtime.IExtensionPoint; import org.eclipse.core.runtime.IExtensionRegistry; public class ServerManager implements IServerManager { static ServerManager theServerManager; IUserManager userManager; IExtensionRegistry registry; IPersonManager personManager; ILibraryManager libraryManager; public ServletConfig servletConfig; private IStorage userDir; public static boolean DEBUG_IO_TO_CONSOLE; public static boolean LOCAL_INSTALL; public static boolean IN_WAR; { ServerManager.IN_WAR = false; String localInstall = this.getDavinciProperty(IDavinciServerConstants.LOCAL_INSTALL); if (localInstall != null) { ServerManager.LOCAL_INSTALL = Boolean.parseBoolean(localInstall); } else { ServerManager.LOCAL_INSTALL = false; } String base = System.getProperty(IDavinciServerConstants.BASE_DIRECTORY_PROPERTY); ServerManager.IN_WAR = Boolean.parseBoolean(this.getDavinciProperty(IDavinciServerConstants.INWAR_PROPERTY)); } ServerManager() { String shouldDebug = this.getDavinciProperty(IDavinciServerConstants.SERVER_DEBUG); if (shouldDebug != null && "true".equals(shouldDebug)) { ServerManager.DEBUG_IO_TO_CONSOLE = Boolean.parseBoolean(shouldDebug); } else { ServerManager.DEBUG_IO_TO_CONSOLE = false; } Activator.getActivator().addRegistryChangeListener(new IRegistryListener() { public void registryChanged() { ServerManager.this.registry = Activator.getActivator().getRegistry(); } }); } public static ServerManager getServerManger() { if(ServerManager.theServerManager==null) ServerManager.theServerManager = new ServerManager(); return ServerManager.theServerManager; } /* (non-Javadoc) * @see org.davinci.server.IServerManager#getDavinciProperty(java.lang.String) */ public String getDavinciProperty(String propertyName) { String property = null; if (ServerManager.IN_WAR) { try { Context env = (Context) new InitialContext().lookup("java:comp/env"); property = (String) env.lookup(propertyName); } catch (NameNotFoundException e) { // ignore } catch (NamingException e) { e.printStackTrace(); } // String property // =this.servletConfig.getServletContext().getInitParameter(propertyName); - System.out.println("servlet parm '" + propertyName + "' is : " + property); + if(ServerManager.DEBUG_IO_TO_CONSOLE) + System.out.println("servlet parm '" + propertyName + "' is : " + property); } if (property == null) { property = System.getProperty(propertyName); - System.out.println("servlet parm '" + propertyName + "' is : " + property); + if(ServerManager.DEBUG_IO_TO_CONSOLE) + System.out.println("servlet parm '" + propertyName + "' is : " + property); } return property; } /* (non-Javadoc) * @see org.davinci.server.IServerManager#getUserManager() */ public IUserManager getUserManager() { if (userManager == null) { IConfigurationElement libraryElement = ServerManager.getServerManger().getExtension(IDavinciServerConstants.EXTENSION_POINT_USER_MANAGER, IDavinciServerConstants.EP_TAG_USER_MANAGER); if (libraryElement != null) { try { this.userManager = (IUserManager) libraryElement.createExecutableExtension(IDavinciServerConstants.EP_ATTR_CLASS); } catch (CoreException e) { e.printStackTrace(); } } } return userManager; } /* (non-Javadoc) * @see org.davinci.server.IServerManager#getExtensions(java.lang.String, java.lang.String) */ public List getExtensions(String extensionPoint, String elementTag) { ArrayList list = new ArrayList(); IExtension[] extensions = this.getExtensions(extensionPoint); for (int i = 0; i < extensions.length; i++) { IConfigurationElement[] elements = extensions[i].getConfigurationElements(); for (int j = 0; j < elements.length; j++) { if (elements[j].getName().equals(elementTag)) { list.add(elements[j]); } } } return list; } /* (non-Javadoc) * @see org.davinci.server.IServerManager#getExtension(java.lang.String, java.lang.String) */ public IConfigurationElement getExtension(String extensionPoint, String elementTag) { IExtension[] extensions = this.getExtensions(extensionPoint); IConfigurationElement winner = null; int highest = -100000; for(int i=0;i<extensions.length;i++){ IConfigurationElement[] elements = extensions[i].getConfigurationElements(); for (int j = 0; j < elements.length; j++) { if (elements[j].getName().equals(elementTag)) { String stringPriority = elements[j].getAttribute(IDavinciServerConstants.EP_ATTR_PAGE_PRIORITY); int priority = -10000; if(stringPriority!=null) priority= Integer.parseInt(stringPriority); if(priority > highest){ winner = elements[j]; highest = priority; } } } } return winner; } private static final IExtension[] EMPTY_EXTENSIONS = {}; /* (non-Javadoc) * @see org.davinci.server.IServerManager#getExtensions(java.lang.String) */ public IExtension[] getExtensions(String extensionPoint) { if (this.registry == null) { this.registry = Activator.getActivator().getRegistry(); } if (this.registry != null) { IExtensionPoint point = this.registry.getExtensionPoint(IDavinciServerConstants.BUNDLE_ID, extensionPoint); if (point != null) { return point.getExtensions(); } } return ServerManager.EMPTY_EXTENSIONS; } /* (non-Javadoc) * @see org.davinci.server.IServerManager#getLibraryManager() */ public synchronized ILibraryManager getLibraryManager() { if (libraryManager == null) { /* IConfigurationElement libraryElement = ServerManager.getServerManger().getExtension(IDavinciServerConstants.EXTENSION_POINT_LIBRARY_MANAGER, IDavinciServerConstants.EP_TAG_LIBRARY_MANAGER); if (libraryElement != null) { try { this.libraryManager = (ILibraryManager) libraryElement.createExecutableExtension(IDavinciServerConstants.EP_ATTR_CLASS); } catch (CoreException e) { e.printStackTrace(); } } */ libraryManager = new LibraryManager(); } return libraryManager; } public IPersonManager getPersonManager() { if(this.personManager==null){ IConfigurationElement libraryElement = ServerManager.getServerManger().getExtension(IDavinciServerConstants.EXTENSION_POINT_PERSON_MANAGER, IDavinciServerConstants.EP_TAG_PERSON_MANAGER); if (libraryElement != null) { try { this.personManager = (IPersonManager) libraryElement.createExecutableExtension(IDavinciServerConstants.EP_ATTR_CLASS); } catch (CoreException e) { e.printStackTrace(); } } } return this.personManager; } public void setBaseDirectory(IStorage baseDirectory){ this.userDir = baseDirectory; } public IStorage getBaseDirectory(){ if(this.userDir ==null){ String basePath = getDavinciProperty(IDavinciServerConstants.BASE_DIRECTORY_PROPERTY); if (basePath != null && basePath.length() > 0) { IStorage dir = new StorageFileSystem(basePath); if (dir.exists()) { userDir = dir; } else { System.err.println("FATAL!!!!! User directory does not exist."); } } if (userDir == null) { File tempDir = (File) servletConfig.getServletContext().getAttribute("javax.servlet.context.tempdir"); userDir = new StorageFileSystem(tempDir); } if (userDir == null) { userDir =new StorageFileSystem("."); } } return this.userDir; } }
false
true
public String getDavinciProperty(String propertyName) { String property = null; if (ServerManager.IN_WAR) { try { Context env = (Context) new InitialContext().lookup("java:comp/env"); property = (String) env.lookup(propertyName); } catch (NameNotFoundException e) { // ignore } catch (NamingException e) { e.printStackTrace(); } // String property // =this.servletConfig.getServletContext().getInitParameter(propertyName); System.out.println("servlet parm '" + propertyName + "' is : " + property); } if (property == null) { property = System.getProperty(propertyName); System.out.println("servlet parm '" + propertyName + "' is : " + property); } return property; }
public String getDavinciProperty(String propertyName) { String property = null; if (ServerManager.IN_WAR) { try { Context env = (Context) new InitialContext().lookup("java:comp/env"); property = (String) env.lookup(propertyName); } catch (NameNotFoundException e) { // ignore } catch (NamingException e) { e.printStackTrace(); } // String property // =this.servletConfig.getServletContext().getInitParameter(propertyName); if(ServerManager.DEBUG_IO_TO_CONSOLE) System.out.println("servlet parm '" + propertyName + "' is : " + property); } if (property == null) { property = System.getProperty(propertyName); if(ServerManager.DEBUG_IO_TO_CONSOLE) System.out.println("servlet parm '" + propertyName + "' is : " + property); } return property; }
diff --git a/uk.ac.gda.client.tomo/src/uk/ac/gda/client/tomo/alignment/view/handlers/impl/TiltController.java b/uk.ac.gda.client.tomo/src/uk/ac/gda/client/tomo/alignment/view/handlers/impl/TiltController.java index de53604..6957a3d 100644 --- a/uk.ac.gda.client.tomo/src/uk/ac/gda/client/tomo/alignment/view/handlers/impl/TiltController.java +++ b/uk.ac.gda.client.tomo/src/uk/ac/gda/client/tomo/alignment/view/handlers/impl/TiltController.java @@ -1,549 +1,549 @@ /*- * Copyright © 2011 Diamond Light Source Ltd. * * This file is part of GDA. * * GDA is free software: you can redistribute it and/or modify it under the * terms of the GNU General Public License version 3 as published by the Free * Software Foundation. * * GDA 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 GDA. If not, see <http://www.gnu.org/licenses/>. */ package uk.ac.gda.client.tomo.alignment.view.handlers.impl; import gda.data.NumTracker; import gda.data.PathConstructor; import gda.device.DeviceException; import gda.factory.Findable; import gda.jython.IScanDataPointObserver; import gda.jython.InterfaceProvider; import gda.jython.JythonServerFacade; import gda.observable.IObservable; import gda.observable.IObserver; import gda.util.Sleep; import java.io.BufferedReader; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import java.util.regex.Pattern; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.SubMonitor; import org.eclipse.core.runtime.SubProgressMonitor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.ac.gda.client.tomo.DoublePointList; import uk.ac.gda.client.tomo.ExternalFunction; import uk.ac.gda.client.tomo.TiltPlotPointsHolder; import uk.ac.gda.client.tomo.alignment.view.TomoAlignmentCommands; import uk.ac.gda.client.tomo.alignment.view.handlers.ICameraHandler; import uk.ac.gda.client.tomo.alignment.view.handlers.ICameraModuleMotorHandler; import uk.ac.gda.client.tomo.alignment.view.handlers.ISampleStageMotorHandler; import uk.ac.gda.client.tomo.alignment.view.handlers.ITiltBallLookupTableHandler; import uk.ac.gda.client.tomo.alignment.view.handlers.ITiltController; import uk.ac.gda.client.tomo.composites.ModuleButtonComposite.CAMERA_MODULE; import uk.ac.gda.client.tomo.view.handlers.exceptions.ExternalProcessingFailedException; /** * */ public class TiltController implements ITiltController { private static final String MATLAB_OUTPUT_PREFIX = "output ="; private static final String NAN_VALUE = "NaN"; private Pattern doublePattern = Pattern.compile("\\-?[0-9]*\\.?[0-9]*"); private static final String SUBDIRECTORY = "Subdirectory:"; private ExternalFunction externalProgram1; private ExternalFunction externalProgram2; private ITiltBallLookupTableHandler lookupTableHandler; private ISampleStageMotorHandler sampleStageMotorHandler; private ICameraModuleMotorHandler cameraModuleMotorHandler; private ICameraHandler cameraHandler; private IObservable tomoScriptController; private String result; private boolean test = false; private double preTiltSs1RxVal = 0.2; private double preTiltCam1RollVal = 0.5; public void setPreTiltCam1RollVal(double preTiltCam1RollVal) { this.preTiltCam1RollVal = preTiltCam1RollVal; } public void setPreTiltSs1RxVal(double preTiltSs1RxVal) { this.preTiltSs1RxVal = preTiltSs1RxVal; } public String getResult() { return result; } public void setTomoScriptController(IObservable tomoScriptController) { this.tomoScriptController = tomoScriptController; } private static final Logger logger = LoggerFactory.getLogger(TiltController.class); public void setCameraModuleMotorHandler(ICameraModuleMotorHandler cameraModuleMotorHandler) { this.cameraModuleMotorHandler = cameraModuleMotorHandler; } public void setLookupTableHandler(ITiltBallLookupTableHandler lookupTableHandler) { this.lookupTableHandler = lookupTableHandler; } public int getMinY(CAMERA_MODULE selectedCameraModule) throws DeviceException { if (CAMERA_MODULE.NO_MODULE.equals(selectedCameraModule)) { return Integer.MIN_VALUE; } return lookupTableHandler.getMinY(selectedCameraModule.getValue()); } public int getMaxY(CAMERA_MODULE selectedCameraModule) throws DeviceException { if (CAMERA_MODULE.NO_MODULE.equals(selectedCameraModule)) { return Integer.MIN_VALUE; } return lookupTableHandler.getMaxY(selectedCameraModule.getValue()); } @Override public TiltPlotPointsHolder doTilt(IProgressMonitor monitor, CAMERA_MODULE module, double exposureTime) throws Exception { SubMonitor progress = SubMonitor.convert(monitor); progress.beginTask("Preparing for Tilt alignment", 100); // 1. set roi minY and maxY to values in the lookuptable so that the scanned images are cropped. int minY = getMinY(module); int maxY = getMaxY(module); int minX = getMinX(module); int maxX = getMaxX(module); String firstScanFolder = null; String secondScanFolder = null; try { // Move the cam1_roll and the ss1_rx to preset values so that the matlab tilt procedure evaluates good // values. cameraModuleMotorHandler.moveCam1Roll(progress, preTiltCam1RollVal); sampleStageMotorHandler.moveSs1RxBy(progress, preTiltSs1RxVal); // cameraHandler.setUpForTilt(minY, maxY, minX, maxX); logger.debug("Set the camera minY at:" + minY + " and maxY at:" + maxY); double txOffset = getTxOffset(module); String subDir = getSubDir(); try { changeSubDir("tmp"); // Move tx by offset logger.debug("the tx offset is:{}", txOffset); if (!monitor.isCanceled()) { // Relative to where it was - conclusion from testing with Mike sampleStageMotorHandler.moveSs1TxBy(progress, txOffset); // 2. scan 0 to 340 deg in steps of 20 logger.debug("will run scan command next"); if (!monitor.isCanceled()) { - //scanThetha(progress, exposureTime); + scanThetha(progress, exposureTime); if (!monitor.isCanceled()) { // 3. call matlab - first time firstScanFolder = runExternalProcess(progress, 1); String result = getResult(); // 4. read output from matlab and move motors // output= x,yz,z Double[] motorsToMove = getTiltMotorPositions(result); logger.debug("motorsto move:{}", motorsToMove); if (!progress.isCanceled()) { if (motorsToMove != null) { logger.debug("Current cam1_roll is :{}", cameraModuleMotorHandler.getCam1RollPosition()); logger.debug("Current rx is :{}", sampleStageMotorHandler.getSs1RxPosition()); double rz = motorsToMove[0];// roll double rx = motorsToMove[1];// pitch // sampleStageMotorHandler.moveSs1RzBy(progress, -rz); cameraModuleMotorHandler.moveCam1Roll(progress, cameraModuleMotorHandler.getCam1RollPosition() - rz); sampleStageMotorHandler.moveSs1RxBy(progress, -rx); logger.debug("After move cam1 roll is :{}", cameraModuleMotorHandler.getCam1RollPosition()); logger.debug("After move ss1_rx is :{}", sampleStageMotorHandler.getSs1RxPosition()); if (!monitor.isCanceled()) { // 5. scan 0 to 340 deg in steps of 20 scanThetha(progress, exposureTime); if (!monitor.isCanceled()) { // 6. call matlab secondScanFolder = runExternalProcess(progress, 2); } } } else { throw new IllegalArgumentException("Matlab returned no values"); } } } } } } finally { sampleStageMotorHandler.moveSs1TxBy(progress, -txOffset); changeSubDir(subDir); } } finally { // - move the motor back // motorHandler.moveSs1TxBy(progress, -txOffset); cameraHandler.resetAfterTilt(); sampleStageMotorHandler.moveRotationMotorTo(progress, 0); // Return the plottable points progress.done(); } return getPlottablePoint(firstScanFolder, secondScanFolder); } private String getSubDir() { final boolean[] subdirChanged = new boolean[1]; final String[] subdir = new String[1]; IObserver observer = null; if (tomoScriptController != null) { observer = new IObserver() { @Override public void update(Object source, Object arg) { if (arg instanceof String) { String msg = (String) arg; if (msg.startsWith(SUBDIRECTORY)) { subdir[0] = msg.substring(SUBDIRECTORY.length()); subdirChanged[0] = true; } } } }; tomoScriptController.addIObserver(observer); } InterfaceProvider.getCommandRunner().evaluateCommand(TomoAlignmentCommands.GET_SUBDIR); while (!subdirChanged[0]) { Sleep.sleep(5); } if (tomoScriptController != null && observer != null) { tomoScriptController.deleteIObserver(observer); } logger.debug("Subdir is {}", subdir[0]); return subdir[0]; } private void changeSubDir(final String subdir) { final boolean[] subdirChanged = new boolean[1]; IObserver observer = null; if (tomoScriptController != null) { observer = new IObserver() { @Override public void update(Object source, Object arg) { if (arg instanceof String) { String msg = (String) arg; if (msg.equals("Subdirectory set to " + subdir)) { subdirChanged[0] = true; } } } }; tomoScriptController.addIObserver(observer); } InterfaceProvider.getCommandRunner() .evaluateCommand(String.format(TomoAlignmentCommands.CHANGE_SUBDIR, subdir)); while (!subdirChanged[0]) { Sleep.sleep(5); } if (tomoScriptController != null && observer != null) { tomoScriptController.deleteIObserver(observer); } logger.debug("Subdirectory set to {}", subdir); } private void scanThetha(final IProgressMonitor progress, double exposureTime) { SubMonitor subMonitor = SubMonitor.convert(progress); subMonitor.beginTask("Scan", 10); String scanCmd = String.format("scan %1$s 0 340 20 %2$s %3$f", sampleStageMotorHandler.getThethaMotorName(), cameraHandler.getCameraName(), exposureTime); logger.debug("Scan command being executed:{}", scanCmd); PrepareTiltSubProgressMonitor prepareTiltSubProgressMonitor = new PrepareTiltSubProgressMonitor(subMonitor, 80); prepareTiltSubProgressMonitor.subTask(String.format("Command:%1$s", scanCmd)); JythonServerFacade.getInstance().addIObserver(prepareTiltSubProgressMonitor); JythonServerFacade.getInstance().evaluateCommand(scanCmd); JythonServerFacade.getInstance().deleteIObserver(prepareTiltSubProgressMonitor); prepareTiltSubProgressMonitor.done(); subMonitor.done(); } private static class PrepareTiltSubProgressMonitor extends SubProgressMonitor implements IScanDataPointObserver, Findable { private String name; public PrepareTiltSubProgressMonitor(IProgressMonitor monitor, int ticks) { super(monitor, ticks); } @Override public void setName(String name) { this.name = name; } @Override public String getName() { return name; } @Override public void update(Object source, Object arg) { logger.debug("PrepareTiltSubProgressMonitor#update#{}", source); String msg = arg.toString(); if (msg.startsWith("point")) { subTask(String.format("Scan data information: %s", arg)); worked(1); } } } protected String runExternalProcess(IProgressMonitor monitor, int count) throws Exception { SubMonitor progress = SubMonitor.convert(monitor); result = null; progress.beginTask("Matlab Processing", 10); ArrayList<String> cmdAndArgs = new ArrayList<String>(); cmdAndArgs.add(externalProgram1.getCommand()); String path = PathConstructor.createFromDefaultProperty(); long filenumber = new NumTracker("i12").getCurrentFileNumber(); // String imagesPath = path + File.separator + filenumber + File.separator + "projections" + File.separator; String lastImageFilename = "p_00017.tif"; if (!externalProgram1.getArgs().isEmpty()) { cmdAndArgs.add(externalProgram1.getArgs().get(0)); } if (test) { cmdAndArgs.add("'/dls_sw/i12/software/tomoTilt/images/projections/p_00017.tif'" + ",1,true"); } else { String lastPartOfCmd = "'" + imagesPath + lastImageFilename + "',1,true"; cmdAndArgs.add(lastPartOfCmd); logger.info("imageLastFileName:{}", lastPartOfCmd); } logger.info("CommandAndArgs1:{}", cmdAndArgs); runExtProcess(progress, cmdAndArgs); cmdAndArgs.clear(); cmdAndArgs.add(externalProgram2.getCommand()); if (!externalProgram2.getArgs().isEmpty()) { cmdAndArgs.add(externalProgram2.getArgs().get(0)); if (test) { String cmdArgs = externalProgram2.getArgs().get(1) + "'/dls_sw/i12/software/tomoTilt/images/projections/p_00017.tif','/dls_sw/i12/software/tomoTilt/images/projections/calculated_flatfield.tif'" + "," + count; logger.info("Test cmd:{}", cmdArgs); cmdAndArgs.add(cmdArgs); } else { String cmdArgs = externalProgram2.getArgs().get(1) + "'" + imagesPath + lastImageFilename + "','" + imagesPath + "calculated_flatfield.tif'," + count; logger.info("External program being run:{}", cmdArgs); cmdAndArgs.add(cmdArgs); } } logger.info("CommandAndArgs2:{}", cmdAndArgs); runExtProcess(progress, cmdAndArgs); progress.done(); return imagesPath; } protected void runExtProcess(IProgressMonitor monitor, List<String> cmdAndArgs) throws Exception { ProcessBuilder pb = new ProcessBuilder(); pb.redirectErrorStream(true); pb.command(cmdAndArgs); final Process p = pb.start(); try { BufferedReader output = new BufferedReader(new InputStreamReader(p.getInputStream())); String line; while ((line = output.readLine()) != null) { logger.info(line); if (!line.equals("")) { monitor.subTask(line); if (line.startsWith(MATLAB_OUTPUT_PREFIX)) { result = line; } } } int exitValue = p.waitFor(); closeStream(p.getInputStream(), "output"); if (exitValue != 0) { throw new ExternalProcessingFailedException("External Processing Failed" + cmdAndArgs); } } catch (Exception ex) { logger.error(ex.getMessage()); throw ex; } finally { p.destroy(); } } private static void closeStream(Closeable stream, String name) { try { stream.close(); } catch (IOException ioe) { logger.warn(String.format("Unable to close process %s stream", name), ioe); } } public void setExternalProgram1(ExternalFunction externalProgram1) { this.externalProgram1 = externalProgram1; } public void setExternalProgram2(ExternalFunction externalProgram2) { this.externalProgram2 = externalProgram2; } public double getTxOffset(CAMERA_MODULE selectedCameraModule) throws DeviceException { if (CAMERA_MODULE.NO_MODULE.equals(selectedCameraModule)) { return Double.NaN; } return lookupTableHandler.getTxOffset(selectedCameraModule.getValue()); } protected TiltPlotPointsHolder getPlottablePoint(String firstScanFolder, String secondScanFolder) throws IOException { TiltPlotPointsHolder tiltPlotPointsHolder = new TiltPlotPointsHolder(); tiltPlotPointsHolder.setCenters1(getDoublePointList(firstScanFolder + File.separator + "centers_1.csv")); tiltPlotPointsHolder.setEllipse1(getDoublePointList(firstScanFolder + File.separator + "ellipse_1.csv")); tiltPlotPointsHolder.setCenters2(getDoublePointList(secondScanFolder + File.separator + "centers_2.csv")); tiltPlotPointsHolder.setEllipse2(getDoublePointList(secondScanFolder + File.separator + "ellipse_2.csv")); tiltPlotPointsHolder.setLine2(getDoublePointList(secondScanFolder + File.separator + "line_2.csv")); return tiltPlotPointsHolder; } private DoublePointList getDoublePointList(String fileName) throws IOException { File firstScanCentersFile = new File(fileName); DoublePointList pointList = new DoublePointList(); if (firstScanCentersFile.exists()) { FileInputStream fis = new FileInputStream(firstScanCentersFile); InputStreamReader inpStreamReader = new InputStreamReader(fis); BufferedReader br = new BufferedReader(inpStreamReader); String rl = null; rl = br.readLine(); while (rl != null) { StringTokenizer strTokenizer = new StringTokenizer(rl, ","); if (strTokenizer.countTokens() != 2) { fis.close(); br.close(); throw new IllegalArgumentException("Invalid row in the table"); } double x = Double.parseDouble(strTokenizer.nextToken()); double y = Double.parseDouble(strTokenizer.nextToken()); pointList.addPoint(x, y); rl = br.readLine(); } fis.close(); br.close(); inpStreamReader.close(); } else { logger.error("File {} does not exist", fileName); } return pointList; } public int getMinX(CAMERA_MODULE selectedCameraModule) throws DeviceException { if (CAMERA_MODULE.NO_MODULE.equals(selectedCameraModule)) { return Integer.MIN_VALUE; } return lookupTableHandler.getMinX(selectedCameraModule.getValue()); } public int getMaxX(CAMERA_MODULE selectedCameraModule) throws DeviceException { if (CAMERA_MODULE.NO_MODULE.equals(selectedCameraModule)) { return Integer.MIN_VALUE; } return lookupTableHandler.getMaxX(selectedCameraModule.getValue()); } private Double[] getTiltMotorPositions(String result) throws Exception { if (result != null) { String values = result.substring(MATLAB_OUTPUT_PREFIX.length()); StringTokenizer tokenizer = new StringTokenizer(values, ","); int count = 0; Double[] motorsToMove = new Double[tokenizer.countTokens()]; while (tokenizer.hasMoreElements()) { String token = tokenizer.nextElement().toString().trim(); // Matcher doublePatternMatcher = doublePattern.matcher(token); // if (!doublePatternMatcher.matches()) { // return null; // } try { if (NAN_VALUE.equals(token)) { throw new Exception("Unable to get correct tilt values"); } motorsToMove[count] = Double.parseDouble(token); count = count + 1; // Only interested in the first two decimals if (count == 2) { break; } } catch (NumberFormatException nfe) { logger.error("Not a number", nfe); throw new Exception("Values received are not numbers", nfe); } } return motorsToMove; } return null; } public void setCameraHandler(ICameraHandler cameraHandler) { this.cameraHandler = cameraHandler; } @Override public void dispose() { // TODO Auto-generated method stub } public void setSampleStageMotorHandler(ISampleStageMotorHandler sampleStageMotorHandler) { this.sampleStageMotorHandler = sampleStageMotorHandler; } }
true
true
public TiltPlotPointsHolder doTilt(IProgressMonitor monitor, CAMERA_MODULE module, double exposureTime) throws Exception { SubMonitor progress = SubMonitor.convert(monitor); progress.beginTask("Preparing for Tilt alignment", 100); // 1. set roi minY and maxY to values in the lookuptable so that the scanned images are cropped. int minY = getMinY(module); int maxY = getMaxY(module); int minX = getMinX(module); int maxX = getMaxX(module); String firstScanFolder = null; String secondScanFolder = null; try { // Move the cam1_roll and the ss1_rx to preset values so that the matlab tilt procedure evaluates good // values. cameraModuleMotorHandler.moveCam1Roll(progress, preTiltCam1RollVal); sampleStageMotorHandler.moveSs1RxBy(progress, preTiltSs1RxVal); // cameraHandler.setUpForTilt(minY, maxY, minX, maxX); logger.debug("Set the camera minY at:" + minY + " and maxY at:" + maxY); double txOffset = getTxOffset(module); String subDir = getSubDir(); try { changeSubDir("tmp"); // Move tx by offset logger.debug("the tx offset is:{}", txOffset); if (!monitor.isCanceled()) { // Relative to where it was - conclusion from testing with Mike sampleStageMotorHandler.moveSs1TxBy(progress, txOffset); // 2. scan 0 to 340 deg in steps of 20 logger.debug("will run scan command next"); if (!monitor.isCanceled()) { //scanThetha(progress, exposureTime); if (!monitor.isCanceled()) { // 3. call matlab - first time firstScanFolder = runExternalProcess(progress, 1); String result = getResult(); // 4. read output from matlab and move motors // output= x,yz,z Double[] motorsToMove = getTiltMotorPositions(result); logger.debug("motorsto move:{}", motorsToMove); if (!progress.isCanceled()) { if (motorsToMove != null) { logger.debug("Current cam1_roll is :{}", cameraModuleMotorHandler.getCam1RollPosition()); logger.debug("Current rx is :{}", sampleStageMotorHandler.getSs1RxPosition()); double rz = motorsToMove[0];// roll double rx = motorsToMove[1];// pitch // sampleStageMotorHandler.moveSs1RzBy(progress, -rz); cameraModuleMotorHandler.moveCam1Roll(progress, cameraModuleMotorHandler.getCam1RollPosition() - rz); sampleStageMotorHandler.moveSs1RxBy(progress, -rx); logger.debug("After move cam1 roll is :{}", cameraModuleMotorHandler.getCam1RollPosition()); logger.debug("After move ss1_rx is :{}", sampleStageMotorHandler.getSs1RxPosition()); if (!monitor.isCanceled()) { // 5. scan 0 to 340 deg in steps of 20 scanThetha(progress, exposureTime); if (!monitor.isCanceled()) { // 6. call matlab secondScanFolder = runExternalProcess(progress, 2); } } } else { throw new IllegalArgumentException("Matlab returned no values"); } } } } } } finally { sampleStageMotorHandler.moveSs1TxBy(progress, -txOffset); changeSubDir(subDir); } } finally { // - move the motor back // motorHandler.moveSs1TxBy(progress, -txOffset); cameraHandler.resetAfterTilt(); sampleStageMotorHandler.moveRotationMotorTo(progress, 0); // Return the plottable points progress.done(); } return getPlottablePoint(firstScanFolder, secondScanFolder); }
public TiltPlotPointsHolder doTilt(IProgressMonitor monitor, CAMERA_MODULE module, double exposureTime) throws Exception { SubMonitor progress = SubMonitor.convert(monitor); progress.beginTask("Preparing for Tilt alignment", 100); // 1. set roi minY and maxY to values in the lookuptable so that the scanned images are cropped. int minY = getMinY(module); int maxY = getMaxY(module); int minX = getMinX(module); int maxX = getMaxX(module); String firstScanFolder = null; String secondScanFolder = null; try { // Move the cam1_roll and the ss1_rx to preset values so that the matlab tilt procedure evaluates good // values. cameraModuleMotorHandler.moveCam1Roll(progress, preTiltCam1RollVal); sampleStageMotorHandler.moveSs1RxBy(progress, preTiltSs1RxVal); // cameraHandler.setUpForTilt(minY, maxY, minX, maxX); logger.debug("Set the camera minY at:" + minY + " and maxY at:" + maxY); double txOffset = getTxOffset(module); String subDir = getSubDir(); try { changeSubDir("tmp"); // Move tx by offset logger.debug("the tx offset is:{}", txOffset); if (!monitor.isCanceled()) { // Relative to where it was - conclusion from testing with Mike sampleStageMotorHandler.moveSs1TxBy(progress, txOffset); // 2. scan 0 to 340 deg in steps of 20 logger.debug("will run scan command next"); if (!monitor.isCanceled()) { scanThetha(progress, exposureTime); if (!monitor.isCanceled()) { // 3. call matlab - first time firstScanFolder = runExternalProcess(progress, 1); String result = getResult(); // 4. read output from matlab and move motors // output= x,yz,z Double[] motorsToMove = getTiltMotorPositions(result); logger.debug("motorsto move:{}", motorsToMove); if (!progress.isCanceled()) { if (motorsToMove != null) { logger.debug("Current cam1_roll is :{}", cameraModuleMotorHandler.getCam1RollPosition()); logger.debug("Current rx is :{}", sampleStageMotorHandler.getSs1RxPosition()); double rz = motorsToMove[0];// roll double rx = motorsToMove[1];// pitch // sampleStageMotorHandler.moveSs1RzBy(progress, -rz); cameraModuleMotorHandler.moveCam1Roll(progress, cameraModuleMotorHandler.getCam1RollPosition() - rz); sampleStageMotorHandler.moveSs1RxBy(progress, -rx); logger.debug("After move cam1 roll is :{}", cameraModuleMotorHandler.getCam1RollPosition()); logger.debug("After move ss1_rx is :{}", sampleStageMotorHandler.getSs1RxPosition()); if (!monitor.isCanceled()) { // 5. scan 0 to 340 deg in steps of 20 scanThetha(progress, exposureTime); if (!monitor.isCanceled()) { // 6. call matlab secondScanFolder = runExternalProcess(progress, 2); } } } else { throw new IllegalArgumentException("Matlab returned no values"); } } } } } } finally { sampleStageMotorHandler.moveSs1TxBy(progress, -txOffset); changeSubDir(subDir); } } finally { // - move the motor back // motorHandler.moveSs1TxBy(progress, -txOffset); cameraHandler.resetAfterTilt(); sampleStageMotorHandler.moveRotationMotorTo(progress, 0); // Return the plottable points progress.done(); } return getPlottablePoint(firstScanFolder, secondScanFolder); }
diff --git a/server/src/main/java/io/druid/segment/loading/S3DataSegmentPuller.java b/server/src/main/java/io/druid/segment/loading/S3DataSegmentPuller.java index 49b7501ad5..abf4b3502c 100644 --- a/server/src/main/java/io/druid/segment/loading/S3DataSegmentPuller.java +++ b/server/src/main/java/io/druid/segment/loading/S3DataSegmentPuller.java @@ -1,212 +1,221 @@ /* * Druid - a distributed column store. * Copyright (C) 2012, 2013 Metamarkets Group 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package io.druid.segment.loading; import com.google.common.base.Throwables; import com.google.common.io.ByteStreams; import com.google.common.io.Closeables; import com.google.common.io.Files; import com.google.inject.Inject; import com.metamx.common.ISE; import com.metamx.common.MapUtils; import com.metamx.common.logger.Logger; import io.druid.common.utils.CompressionUtils; import io.druid.storage.s3.S3Utils; import io.druid.timeline.DataSegment; import org.apache.commons.io.FileUtils; import org.jets3t.service.ServiceException; import org.jets3t.service.impl.rest.httpclient.RestS3Service; import org.jets3t.service.model.S3Object; import org.jets3t.service.model.StorageObject; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.concurrent.Callable; import java.util.zip.GZIPInputStream; /** */ public class S3DataSegmentPuller implements DataSegmentPuller { private static final Logger log = new Logger(S3DataSegmentPuller.class); private static final String BUCKET = "bucket"; private static final String KEY = "key"; private final RestS3Service s3Client; @Inject public S3DataSegmentPuller( RestS3Service s3Client ) { this.s3Client = s3Client; } @Override public void getSegmentFiles(final DataSegment segment, final File outDir) throws SegmentLoadingException { final S3Coords s3Coords = new S3Coords(segment); log.info("Pulling index at path[%s] to outDir[%s]", s3Coords, outDir); if (!isObjectInBucket(s3Coords)) { throw new SegmentLoadingException("IndexFile[%s] does not exist.", s3Coords); } if (!outDir.exists()) { outDir.mkdirs(); } if (!outDir.isDirectory()) { throw new ISE("outDir[%s] must be a directory.", outDir); } try { S3Utils.retryS3Operation( new Callable<Void>() { @Override public Void call() throws Exception { long startTime = System.currentTimeMillis(); S3Object s3Obj = null; try { s3Obj = s3Client.getObject(s3Coords.bucket, s3Coords.path); InputStream in = null; try { in = s3Obj.getDataInputStream(); final String key = s3Obj.getKey(); if (key.endsWith(".zip")) { CompressionUtils.unzip(in, outDir); } else if (key.endsWith(".gz")) { final File outFile = new File(outDir, toFilename(key, ".gz")); ByteStreams.copy(new GZIPInputStream(in), Files.newOutputStreamSupplier(outFile)); } else { ByteStreams.copy(in, Files.newOutputStreamSupplier(new File(outDir, toFilename(key, "")))); } log.info("Pull of file[%s] completed in %,d millis", s3Obj, System.currentTimeMillis() - startTime); return null; } catch (IOException e) { - FileUtils.deleteDirectory(outDir); throw new IOException(String.format("Problem decompressing object[%s]", s3Obj), e); } finally { Closeables.closeQuietly(in); } } finally { S3Utils.closeStreamsQuietly(s3Obj); } } } ); } catch (Exception e) { + try { + FileUtils.deleteDirectory(outDir); + } catch (IOException ioe) { + log.warn( + ioe, + "Failed to remove output directory for segment[%s] after exception: %s", + segment.getIdentifier(), + outDir + ); + } throw new SegmentLoadingException(e, e.getMessage()); } } private String toFilename(String key, final String suffix) { String filename = key.substring(key.lastIndexOf("/") + 1); // characters after last '/' filename = filename.substring(0, filename.length() - suffix.length()); // remove the suffix from the end return filename; } private boolean isObjectInBucket(final S3Coords coords) throws SegmentLoadingException { try { return S3Utils.retryS3Operation( new Callable<Boolean>() { @Override public Boolean call() throws Exception { return s3Client.isObjectInBucket(coords.bucket, coords.path); } } ); } catch (InterruptedException e) { throw Throwables.propagate(e); } catch (IOException e) { throw new SegmentLoadingException(e, "S3 fail! Key[%s]", coords); } catch (ServiceException e) { throw new SegmentLoadingException(e, "S3 fail! Key[%s]", coords); } } @Override public long getLastModified(DataSegment segment) throws SegmentLoadingException { final S3Coords coords = new S3Coords(segment); try { final StorageObject objDetails = S3Utils.retryS3Operation( new Callable<StorageObject>() { @Override public StorageObject call() throws Exception { return s3Client.getObjectDetails(coords.bucket, coords.path); } } ); return objDetails.getLastModifiedDate().getTime(); } catch (InterruptedException e) { throw Throwables.propagate(e); } catch (IOException e) { throw new SegmentLoadingException(e, e.getMessage()); } catch (ServiceException e) { throw new SegmentLoadingException(e, e.getMessage()); } } private static class S3Coords { String bucket; String path; public S3Coords(DataSegment segment) { Map<String, Object> loadSpec = segment.getLoadSpec(); bucket = MapUtils.getString(loadSpec, BUCKET); path = MapUtils.getString(loadSpec, KEY); if (path.startsWith("/")) { path = path.substring(1); } } public String toString() { return String.format("s3://%s/%s", bucket, path); } } }
false
true
public void getSegmentFiles(final DataSegment segment, final File outDir) throws SegmentLoadingException { final S3Coords s3Coords = new S3Coords(segment); log.info("Pulling index at path[%s] to outDir[%s]", s3Coords, outDir); if (!isObjectInBucket(s3Coords)) { throw new SegmentLoadingException("IndexFile[%s] does not exist.", s3Coords); } if (!outDir.exists()) { outDir.mkdirs(); } if (!outDir.isDirectory()) { throw new ISE("outDir[%s] must be a directory.", outDir); } try { S3Utils.retryS3Operation( new Callable<Void>() { @Override public Void call() throws Exception { long startTime = System.currentTimeMillis(); S3Object s3Obj = null; try { s3Obj = s3Client.getObject(s3Coords.bucket, s3Coords.path); InputStream in = null; try { in = s3Obj.getDataInputStream(); final String key = s3Obj.getKey(); if (key.endsWith(".zip")) { CompressionUtils.unzip(in, outDir); } else if (key.endsWith(".gz")) { final File outFile = new File(outDir, toFilename(key, ".gz")); ByteStreams.copy(new GZIPInputStream(in), Files.newOutputStreamSupplier(outFile)); } else { ByteStreams.copy(in, Files.newOutputStreamSupplier(new File(outDir, toFilename(key, "")))); } log.info("Pull of file[%s] completed in %,d millis", s3Obj, System.currentTimeMillis() - startTime); return null; } catch (IOException e) { FileUtils.deleteDirectory(outDir); throw new IOException(String.format("Problem decompressing object[%s]", s3Obj), e); } finally { Closeables.closeQuietly(in); } } finally { S3Utils.closeStreamsQuietly(s3Obj); } } } ); } catch (Exception e) { throw new SegmentLoadingException(e, e.getMessage()); } }
public void getSegmentFiles(final DataSegment segment, final File outDir) throws SegmentLoadingException { final S3Coords s3Coords = new S3Coords(segment); log.info("Pulling index at path[%s] to outDir[%s]", s3Coords, outDir); if (!isObjectInBucket(s3Coords)) { throw new SegmentLoadingException("IndexFile[%s] does not exist.", s3Coords); } if (!outDir.exists()) { outDir.mkdirs(); } if (!outDir.isDirectory()) { throw new ISE("outDir[%s] must be a directory.", outDir); } try { S3Utils.retryS3Operation( new Callable<Void>() { @Override public Void call() throws Exception { long startTime = System.currentTimeMillis(); S3Object s3Obj = null; try { s3Obj = s3Client.getObject(s3Coords.bucket, s3Coords.path); InputStream in = null; try { in = s3Obj.getDataInputStream(); final String key = s3Obj.getKey(); if (key.endsWith(".zip")) { CompressionUtils.unzip(in, outDir); } else if (key.endsWith(".gz")) { final File outFile = new File(outDir, toFilename(key, ".gz")); ByteStreams.copy(new GZIPInputStream(in), Files.newOutputStreamSupplier(outFile)); } else { ByteStreams.copy(in, Files.newOutputStreamSupplier(new File(outDir, toFilename(key, "")))); } log.info("Pull of file[%s] completed in %,d millis", s3Obj, System.currentTimeMillis() - startTime); return null; } catch (IOException e) { throw new IOException(String.format("Problem decompressing object[%s]", s3Obj), e); } finally { Closeables.closeQuietly(in); } } finally { S3Utils.closeStreamsQuietly(s3Obj); } } } ); } catch (Exception e) { try { FileUtils.deleteDirectory(outDir); } catch (IOException ioe) { log.warn( ioe, "Failed to remove output directory for segment[%s] after exception: %s", segment.getIdentifier(), outDir ); } throw new SegmentLoadingException(e, e.getMessage()); } }
diff --git a/portal/src/main/java/com/googlecode/fascinator/portal/security/handler/FascinatorLoginUrlAuthenticationEntryPoint.java b/portal/src/main/java/com/googlecode/fascinator/portal/security/handler/FascinatorLoginUrlAuthenticationEntryPoint.java index 6f8f878..17db760 100644 --- a/portal/src/main/java/com/googlecode/fascinator/portal/security/handler/FascinatorLoginUrlAuthenticationEntryPoint.java +++ b/portal/src/main/java/com/googlecode/fascinator/portal/security/handler/FascinatorLoginUrlAuthenticationEntryPoint.java @@ -1,30 +1,37 @@ package com.googlecode.fascinator.portal.security.handler; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint; /** * A subclass of LoginUrlAuthenticationEntryPoint that will redirect the user to * the login page in the correct portal * * @author andrewbrazzatti * */ public class FascinatorLoginUrlAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint { @Override protected String determineUrlToUseForThisRequest( HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) { String path = request.getServletPath(); path = path.substring(1, path.length()); - String portal = path.substring(0, path.indexOf("/")); + int nextSlash = path.indexOf("/"); + String portal; + if (nextSlash == -1) { + portal = path; + path = ""; + } else { + portal = path.substring(0, path.indexOf("/")); + } String redirectPath = path.substring(path.indexOf("/") + 1, path.length()); return "/" + portal + "/login?fromUrl=" + redirectPath; } }
true
true
protected String determineUrlToUseForThisRequest( HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) { String path = request.getServletPath(); path = path.substring(1, path.length()); String portal = path.substring(0, path.indexOf("/")); String redirectPath = path.substring(path.indexOf("/") + 1, path.length()); return "/" + portal + "/login?fromUrl=" + redirectPath; }
protected String determineUrlToUseForThisRequest( HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) { String path = request.getServletPath(); path = path.substring(1, path.length()); int nextSlash = path.indexOf("/"); String portal; if (nextSlash == -1) { portal = path; path = ""; } else { portal = path.substring(0, path.indexOf("/")); } String redirectPath = path.substring(path.indexOf("/") + 1, path.length()); return "/" + portal + "/login?fromUrl=" + redirectPath; }
diff --git a/java/client/test/com/thoughtworks/selenium/corebased/TestType.java b/java/client/test/com/thoughtworks/selenium/corebased/TestType.java index f4b101b99..99b19415f 100644 --- a/java/client/test/com/thoughtworks/selenium/corebased/TestType.java +++ b/java/client/test/com/thoughtworks/selenium/corebased/TestType.java @@ -1,29 +1,30 @@ package com.thoughtworks.selenium.corebased; import com.thoughtworks.selenium.InternalSelenseTestBase; import org.junit.Test; public class TestType extends InternalSelenseTestBase { @Test public void testType() throws Exception { selenium.open("../tests/html/test_type_page1.html"); verifyEquals(selenium.getValue("username"), ""); selenium.shiftKeyDown(); selenium.type("username", "x"); verifyEquals(selenium.getValue("username"), "X"); selenium.shiftKeyUp(); selenium.type("username", "TestUserWithLongName"); verifyEquals(selenium.getValue("username"), "TestUserWi"); selenium.type("username", "TestUser"); verifyEquals(selenium.getValue("username"), "TestUser"); verifyEquals(selenium.getValue("password"), ""); selenium.type("password", "testUserPasswordIsVeryLong"); verifyEquals(selenium.getValue("password"), "testUserPasswordIsVe"); selenium.type("password", "testUserPassword"); verifyEquals(selenium.getValue("password"), "testUserPassword"); + selenium.type("file", "/test/file"); selenium.click("submitButton"); selenium.waitForPageToLoad("30000"); verifyTrue(selenium.isTextPresent("Welcome, TestUser!")); } }
true
true
public void testType() throws Exception { selenium.open("../tests/html/test_type_page1.html"); verifyEquals(selenium.getValue("username"), ""); selenium.shiftKeyDown(); selenium.type("username", "x"); verifyEquals(selenium.getValue("username"), "X"); selenium.shiftKeyUp(); selenium.type("username", "TestUserWithLongName"); verifyEquals(selenium.getValue("username"), "TestUserWi"); selenium.type("username", "TestUser"); verifyEquals(selenium.getValue("username"), "TestUser"); verifyEquals(selenium.getValue("password"), ""); selenium.type("password", "testUserPasswordIsVeryLong"); verifyEquals(selenium.getValue("password"), "testUserPasswordIsVe"); selenium.type("password", "testUserPassword"); verifyEquals(selenium.getValue("password"), "testUserPassword"); selenium.click("submitButton"); selenium.waitForPageToLoad("30000"); verifyTrue(selenium.isTextPresent("Welcome, TestUser!")); }
public void testType() throws Exception { selenium.open("../tests/html/test_type_page1.html"); verifyEquals(selenium.getValue("username"), ""); selenium.shiftKeyDown(); selenium.type("username", "x"); verifyEquals(selenium.getValue("username"), "X"); selenium.shiftKeyUp(); selenium.type("username", "TestUserWithLongName"); verifyEquals(selenium.getValue("username"), "TestUserWi"); selenium.type("username", "TestUser"); verifyEquals(selenium.getValue("username"), "TestUser"); verifyEquals(selenium.getValue("password"), ""); selenium.type("password", "testUserPasswordIsVeryLong"); verifyEquals(selenium.getValue("password"), "testUserPasswordIsVe"); selenium.type("password", "testUserPassword"); verifyEquals(selenium.getValue("password"), "testUserPassword"); selenium.type("file", "/test/file"); selenium.click("submitButton"); selenium.waitForPageToLoad("30000"); verifyTrue(selenium.isTextPresent("Welcome, TestUser!")); }
diff --git a/samples/showcase/showcase/src/main/java/org/icefaces/samples/showcase/example/ace/date/DateTimeBean.java b/samples/showcase/showcase/src/main/java/org/icefaces/samples/showcase/example/ace/date/DateTimeBean.java index 97e0f865b..bd6377286 100644 --- a/samples/showcase/showcase/src/main/java/org/icefaces/samples/showcase/example/ace/date/DateTimeBean.java +++ b/samples/showcase/showcase/src/main/java/org/icefaces/samples/showcase/example/ace/date/DateTimeBean.java @@ -1,146 +1,147 @@ /* * Copyright 2004-2012 ICEsoft Technologies Canada Corp. * * 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.icefaces.samples.showcase.example.ace.date; import java.io.Serializable; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import javax.annotation.PostConstruct; import javax.faces.bean.CustomScoped; import javax.faces.bean.ManagedBean; import javax.faces.event.ValueChangeEvent; import org.icefaces.samples.showcase.metadata.annotation.ComponentExample; import org.icefaces.samples.showcase.metadata.annotation.ExampleResource; import org.icefaces.samples.showcase.metadata.annotation.ExampleResources; import org.icefaces.samples.showcase.metadata.annotation.ResourceType; import org.icefaces.samples.showcase.metadata.context.ComponentExampleImpl; @ComponentExample(parent = DateEntryBean.BEAN_NAME, title = "example.ace.dateentry.timeentry.title", description = "example.ace.dateentry.timeentry.description", example = "/resources/examples/ace/date/datetimeentry.xhtml") @ExampleResources(resources = { // xhtml @ExampleResource(type = ResourceType.xhtml, title = "datetimeentry.xhtml", resource = "/resources/examples/ace/date/datetimeentry.xhtml"), // Java Source @ExampleResource(type = ResourceType.java, title = "DateTimeBean.java", resource = "/WEB-INF/classes/org/icefaces/samples/showcase/example/ace/date/DateTimeBean.java") }) @ManagedBean(name = DateTimeBean.BEAN_NAME) @CustomScoped(value = "#{window}") public class DateTimeBean extends ComponentExampleImpl<DateTimeBean> implements Serializable { public static final String BEAN_NAME = "dateTime"; private static final String PATTERN_DATE = "MM/dd/yyyy"; private static final String PATTERN_TIME = "h:mm:ss a"; private static final String PATTERN_BOTH = PATTERN_DATE + " " + PATTERN_TIME; private Date selectedDate; private String timeType = "both"; private String pattern = PATTERN_BOTH; private boolean timeOnly = false; public DateTimeBean() { super(DateTimeBean.class); Calendar calendar = Calendar.getInstance( TimeZone.getTimeZone("Canada/Mountain"), Locale.getDefault()); selectedDate = calendar.getTime(); } public Date getSelectedDate() { return selectedDate; } public String getTimeType() { return timeType; } public String getPattern() { return pattern; } public boolean getTimeOnly() { return timeOnly; } public void setSelectedDate(Date selectedDate) { if (pattern.equals(PATTERN_TIME)) { // Only update the time portion of the date Calendar currentDate = Calendar.getInstance(); currentDate.setTime(this.selectedDate); Calendar newDate = Calendar.getInstance(); newDate.setTime(selectedDate); currentDate.set(Calendar.HOUR_OF_DAY, newDate.get(Calendar.HOUR_OF_DAY)); currentDate.set(Calendar.MINUTE, newDate.get(Calendar.MINUTE)); currentDate.set(Calendar.SECOND, newDate.get(Calendar.SECOND)); this.selectedDate = currentDate.getTime(); } else if (pattern.equals(PATTERN_DATE)) { // Only update the date portion of the date Calendar currentDate = Calendar.getInstance(); currentDate.setTime(this.selectedDate); Calendar newDate = Calendar.getInstance(); newDate.setTime(selectedDate); currentDate.set(Calendar.DAY_OF_MONTH, newDate.get(Calendar.DAY_OF_MONTH)); currentDate.set(Calendar.MONTH, newDate.get(Calendar.MONTH)); currentDate.set(Calendar.YEAR, newDate.get(Calendar.YEAR)); + this.selectedDate = currentDate.getTime(); } else { // Overwrite the whole object this.selectedDate = selectedDate; } } public void setTimeType(String timeType) { this.timeType = timeType; } public void setPattern(String pattern) { this.pattern = pattern; } public void setTimeOnly(boolean timeOnly) { this.timeOnly = timeOnly; } @PostConstruct public void initMetaData() { super.initMetaData(); } public void typeChanged(ValueChangeEvent event) { String val = event.getNewValue().toString(); if ("time".equals(val)) { pattern = PATTERN_TIME; timeOnly = true; } else if ("date".equals(val)) { pattern = PATTERN_DATE; timeOnly = false; } else { pattern = PATTERN_BOTH; timeOnly = false; } } }
true
true
public void setSelectedDate(Date selectedDate) { if (pattern.equals(PATTERN_TIME)) { // Only update the time portion of the date Calendar currentDate = Calendar.getInstance(); currentDate.setTime(this.selectedDate); Calendar newDate = Calendar.getInstance(); newDate.setTime(selectedDate); currentDate.set(Calendar.HOUR_OF_DAY, newDate.get(Calendar.HOUR_OF_DAY)); currentDate.set(Calendar.MINUTE, newDate.get(Calendar.MINUTE)); currentDate.set(Calendar.SECOND, newDate.get(Calendar.SECOND)); this.selectedDate = currentDate.getTime(); } else if (pattern.equals(PATTERN_DATE)) { // Only update the date portion of the date Calendar currentDate = Calendar.getInstance(); currentDate.setTime(this.selectedDate); Calendar newDate = Calendar.getInstance(); newDate.setTime(selectedDate); currentDate.set(Calendar.DAY_OF_MONTH, newDate.get(Calendar.DAY_OF_MONTH)); currentDate.set(Calendar.MONTH, newDate.get(Calendar.MONTH)); currentDate.set(Calendar.YEAR, newDate.get(Calendar.YEAR)); } else { // Overwrite the whole object this.selectedDate = selectedDate; } }
public void setSelectedDate(Date selectedDate) { if (pattern.equals(PATTERN_TIME)) { // Only update the time portion of the date Calendar currentDate = Calendar.getInstance(); currentDate.setTime(this.selectedDate); Calendar newDate = Calendar.getInstance(); newDate.setTime(selectedDate); currentDate.set(Calendar.HOUR_OF_DAY, newDate.get(Calendar.HOUR_OF_DAY)); currentDate.set(Calendar.MINUTE, newDate.get(Calendar.MINUTE)); currentDate.set(Calendar.SECOND, newDate.get(Calendar.SECOND)); this.selectedDate = currentDate.getTime(); } else if (pattern.equals(PATTERN_DATE)) { // Only update the date portion of the date Calendar currentDate = Calendar.getInstance(); currentDate.setTime(this.selectedDate); Calendar newDate = Calendar.getInstance(); newDate.setTime(selectedDate); currentDate.set(Calendar.DAY_OF_MONTH, newDate.get(Calendar.DAY_OF_MONTH)); currentDate.set(Calendar.MONTH, newDate.get(Calendar.MONTH)); currentDate.set(Calendar.YEAR, newDate.get(Calendar.YEAR)); this.selectedDate = currentDate.getTime(); } else { // Overwrite the whole object this.selectedDate = selectedDate; } }
diff --git a/src/VASSAL/tools/AdjustableSpeedScrollPane.java b/src/VASSAL/tools/AdjustableSpeedScrollPane.java index 25695d54..02c8710e 100644 --- a/src/VASSAL/tools/AdjustableSpeedScrollPane.java +++ b/src/VASSAL/tools/AdjustableSpeedScrollPane.java @@ -1,98 +1,103 @@ /* * $Id$ * * Copyright (c) 2006 by Joel Uckelman * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License (LGPL) as published by the Free Software Foundation. * * 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, copies are available * at http://www.opensource.org. */ package VASSAL.tools; import java.awt.Component; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.JScrollPane; import VASSAL.build.GameModule; import VASSAL.configure.IntConfigurer; import VASSAL.i18n.Resources; import VASSAL.preferences.Prefs; /** * AdjustableSpeedScrollPane extends {@link ScrollPane} by making the * scroll speed user-configurable. Use AdjustableScrollPane instead * of ScrollPane wherever a scrollpane for large images is needed. * * @author Joel Uckelman * @see VASSAL.tools.ScrollPane * @see javax.swing.JScrollPane */ public class AdjustableSpeedScrollPane extends ScrollPane { private static final long serialVersionUID = 1L; private static final String SCROLL_SPEED = "scrollSpeed"; //$NON-NLS-1$ private static final int defaultSpeed = 50; /** * Creates an AdjustableSpeedScrollPane that displays the contents of the * specified component, where both horizontal and vertical scrollbars * appear whenever the component's contents are larger than the view. * * @param view the component to display in the scrollpane's viewport */ public AdjustableSpeedScrollPane(Component view) { this(view, VERTICAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_AS_NEEDED); } /** * Creates an AdjustableSpeedScrollPane that displays the view component * in a viewport with the specified scrollbar policies. The available * policy settings are listed at * {@link JScrollPane#setVerticalScrollBarPolicy} and * {@link JScrollPane#setHorizontalScrollBarPolicy}. * * @param view the component to display in the scrollpane's viewport * @param vsbPolicy an integer that specifies the vertical scrollbar policy * @param hsbPolicy an integer that specifies the horizontal scrollbar * policy */ public AdjustableSpeedScrollPane(Component view, int vsbPolicy, int hsbPolicy) { super(view, vsbPolicy, hsbPolicy); // set configurer final IntConfigurer config = new IntConfigurer( SCROLL_SPEED, Resources.getString("AdjustableSpeedScrollPane.scroll_increment"), defaultSpeed ); config.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { if (SCROLL_SPEED.equals(e.getPropertyName())) setSpeed(((Integer) e.getNewValue()).intValue()); - } } - ); + }); - final Prefs prefs = GameModule.getGameModule().getPrefs(); - prefs.addOption(Resources.getString("Prefs.general_tab"), config); //$NON-NLS-1$ - setSpeed(((Integer) prefs.getValue(SCROLL_SPEED)).intValue()); + final GameModule g = GameModule.getGameModule(); + if (g == null) { + setSpeed(defaultSpeed); + } + else { + final Prefs prefs = g.getPrefs(); + prefs.addOption(Resources.getString("Prefs.general_tab"), config); //$NON-NLS-1$ + setSpeed(((Integer) prefs.getValue(SCROLL_SPEED)).intValue()); + } } private void setSpeed(int speed) { verticalScrollBar.setUnitIncrement(speed); horizontalScrollBar.setUnitIncrement(speed); } }
false
true
public AdjustableSpeedScrollPane(Component view, int vsbPolicy, int hsbPolicy) { super(view, vsbPolicy, hsbPolicy); // set configurer final IntConfigurer config = new IntConfigurer( SCROLL_SPEED, Resources.getString("AdjustableSpeedScrollPane.scroll_increment"), defaultSpeed ); config.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { if (SCROLL_SPEED.equals(e.getPropertyName())) setSpeed(((Integer) e.getNewValue()).intValue()); } } ); final Prefs prefs = GameModule.getGameModule().getPrefs(); prefs.addOption(Resources.getString("Prefs.general_tab"), config); //$NON-NLS-1$ setSpeed(((Integer) prefs.getValue(SCROLL_SPEED)).intValue()); }
public AdjustableSpeedScrollPane(Component view, int vsbPolicy, int hsbPolicy) { super(view, vsbPolicy, hsbPolicy); // set configurer final IntConfigurer config = new IntConfigurer( SCROLL_SPEED, Resources.getString("AdjustableSpeedScrollPane.scroll_increment"), defaultSpeed ); config.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { if (SCROLL_SPEED.equals(e.getPropertyName())) setSpeed(((Integer) e.getNewValue()).intValue()); } }); final GameModule g = GameModule.getGameModule(); if (g == null) { setSpeed(defaultSpeed); } else { final Prefs prefs = g.getPrefs(); prefs.addOption(Resources.getString("Prefs.general_tab"), config); //$NON-NLS-1$ setSpeed(((Integer) prefs.getValue(SCROLL_SPEED)).intValue()); } }
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/TasksUiPlugin.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/TasksUiPlugin.java index a07753735..3ead55452 100644 --- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/TasksUiPlugin.java +++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/TasksUiPlugin.java @@ -1,1259 +1,1261 @@ /******************************************************************************* * Copyright (c) 2004, 2007 Mylyn project committers 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 *******************************************************************************/ package org.eclipse.mylyn.internal.tasks.ui; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import org.eclipse.core.net.proxy.IProxyChangeEvent; import org.eclipse.core.net.proxy.IProxyChangeListener; import org.eclipse.core.net.proxy.IProxyService; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ISaveContext; import org.eclipse.core.resources.ISaveParticipant; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.ISafeRunnable; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.SafeRunner; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.util.SafeRunnable; import org.eclipse.mylyn.commons.core.CoreUtil; import org.eclipse.mylyn.commons.core.StatusHandler; import org.eclipse.mylyn.commons.net.AuthenticationType; import org.eclipse.mylyn.commons.net.WebUtil; import org.eclipse.mylyn.context.core.ContextCore; import org.eclipse.mylyn.internal.commons.net.WebClientLog; import org.eclipse.mylyn.internal.context.core.ContextCorePlugin; import org.eclipse.mylyn.internal.provisional.commons.ui.AbstractNotification; import org.eclipse.mylyn.internal.provisional.commons.ui.CommonColors; import org.eclipse.mylyn.internal.provisional.commons.ui.CommonFonts; import org.eclipse.mylyn.internal.tasks.core.AbstractSearchHandler; import org.eclipse.mylyn.internal.tasks.core.AbstractTask; import org.eclipse.mylyn.internal.tasks.core.IRepositoryModelListener; import org.eclipse.mylyn.internal.tasks.core.ITasksCoreConstants; import org.eclipse.mylyn.internal.tasks.core.LocalRepositoryConnector; import org.eclipse.mylyn.internal.tasks.core.RepositoryExternalizationParticipant; import org.eclipse.mylyn.internal.tasks.core.RepositoryModel; import org.eclipse.mylyn.internal.tasks.core.RepositoryTemplateManager; import org.eclipse.mylyn.internal.tasks.core.TaskActivityManager; import org.eclipse.mylyn.internal.tasks.core.TaskActivityUtil; import org.eclipse.mylyn.internal.tasks.core.TaskDataStorageManager; import org.eclipse.mylyn.internal.tasks.core.TaskList; import org.eclipse.mylyn.internal.tasks.core.TaskRepositoryManager; import org.eclipse.mylyn.internal.tasks.core.data.TaskDataManager; import org.eclipse.mylyn.internal.tasks.core.data.TaskDataStore; import org.eclipse.mylyn.internal.tasks.core.deprecated.AbstractLegacyRepositoryConnector; import org.eclipse.mylyn.internal.tasks.core.externalization.ExternalizationManager; import org.eclipse.mylyn.internal.tasks.core.externalization.IExternalizationParticipant; import org.eclipse.mylyn.internal.tasks.core.externalization.TaskListExternalizationParticipant; import org.eclipse.mylyn.internal.tasks.core.externalization.TaskListExternalizer; import org.eclipse.mylyn.internal.tasks.ui.deprecated.AbstractTaskEditorFactory; import org.eclipse.mylyn.internal.tasks.ui.notifications.TaskListNotificationReminder; import org.eclipse.mylyn.internal.tasks.ui.notifications.TaskListNotifier; import org.eclipse.mylyn.internal.tasks.ui.util.TaskListElementImporter; import org.eclipse.mylyn.internal.tasks.ui.util.TasksUiExtensionReader; import org.eclipse.mylyn.internal.tasks.ui.views.TaskRepositoriesView; import org.eclipse.mylyn.tasks.core.AbstractDuplicateDetector; import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector; import org.eclipse.mylyn.tasks.core.IRepositoryQuery; import org.eclipse.mylyn.tasks.core.ITask; import org.eclipse.mylyn.tasks.core.ITaskActivationListener; import org.eclipse.mylyn.tasks.core.ITaskContainer; import org.eclipse.mylyn.tasks.core.RepositoryTemplate; import org.eclipse.mylyn.tasks.core.TaskActivationAdapter; import org.eclipse.mylyn.tasks.core.TaskRepository; import org.eclipse.mylyn.tasks.core.ITask.PriorityLevel; import org.eclipse.mylyn.tasks.ui.AbstractRepositoryConnectorUi; import org.eclipse.mylyn.tasks.ui.AbstractTaskRepositoryLinkProvider; import org.eclipse.mylyn.tasks.ui.TasksUi; import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPageFactory; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IStartup; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.forms.FormColors; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.eclipse.ui.progress.IProgressService; import org.eclipse.ui.progress.UIJob; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; /** * Main entry point for the Tasks UI. * * @author Mik Kersten * @since 3.0 */ public class TasksUiPlugin extends AbstractUIPlugin { private static final int DELAY_QUERY_REFRESH_ON_STARTUP = 20 * 1000; private static final int LINK_PROVIDER_TIMEOUT_SECONDS = 5; public static final String LABEL_VIEW_REPOSITORIES = "Task Repositories"; public static final String ID_PLUGIN = "org.eclipse.mylyn.tasks.ui"; private static final String FOLDER_OFFLINE = "offline"; private static final String DIRECTORY_METADATA = ".metadata"; private static final String NAME_DATA_DIR = ".mylyn"; private static final char DEFAULT_PATH_SEPARATOR = '/'; private static final int NOTIFICATION_DELAY = 5000; private static TasksUiPlugin INSTANCE; private static ExternalizationManager externalizationManager; private static TaskListManager taskListManager; private static TaskActivityManager taskActivityManager; private static TaskRepositoryManager repositoryManager; private static TaskListSynchronizationScheduler synchronizationScheduler; private static TaskDataManager taskDataManager; private static Map<String, AbstractRepositoryConnectorUi> repositoryConnectorUiMap = new HashMap<String, AbstractRepositoryConnectorUi>(); //private TaskListSaveManager taskListSaveManager; private TaskListNotificationManager taskListNotificationManager; private TaskListBackupManager taskListBackupManager; private TaskDataStorageManager taskDataStorageManager; private RepositoryTemplateManager repositoryTemplateManager; @Deprecated private final Set<AbstractTaskEditorFactory> taskEditorFactories = new HashSet<AbstractTaskEditorFactory>(); private final Set<AbstractTaskEditorPageFactory> taskEditorPageFactories = new HashSet<AbstractTaskEditorPageFactory>(); private final TreeSet<AbstractTaskRepositoryLinkProvider> repositoryLinkProviders = new TreeSet<AbstractTaskRepositoryLinkProvider>( new OrderComparator()); private TaskListExternalizer taskListExternalizer; private ITaskHighlighter highlighter; private final Map<String, Image> brandingIcons = new HashMap<String, Image>(); private final Map<String, ImageDescriptor> overlayIcons = new HashMap<String, ImageDescriptor>(); private final Set<AbstractDuplicateDetector> duplicateDetectors = new HashSet<AbstractDuplicateDetector>(); private ISaveParticipant saveParticipant; private TaskEditorBloatMonitor taskEditorBloatManager; private TaskJobFactory taskJobFactory; // shared colors for all forms private FormColors formColors; private final List<AbstractSearchHandler> searchHandlers = new ArrayList<AbstractSearchHandler>(); private static final boolean DEBUG_HTTPCLIENT = "true".equalsIgnoreCase(Platform.getDebugOption("org.eclipse.mylyn.tasks.ui/debug/httpclient")); // XXX reconsider if this is necessary public static class TasksUiStartup implements IStartup { public void earlyStartup() { // ignore } } private static final class OrderComparator implements Comparator<AbstractTaskRepositoryLinkProvider> { public int compare(AbstractTaskRepositoryLinkProvider p1, AbstractTaskRepositoryLinkProvider p2) { return p1.getOrder() - p2.getOrder(); } } public enum TaskListSaveMode { ONE_HOUR, THREE_HOURS, DAY; @Override public String toString() { switch (this) { case ONE_HOUR: return "1 hour"; case THREE_HOURS: return "3 hours"; case DAY: return "1 day"; default: return "3 hours"; } } public static TaskListSaveMode fromString(String string) { if (string == null) { return null; } if (string.equals("1 hour")) { return ONE_HOUR; } if (string.equals("3 hours")) { return THREE_HOURS; } if (string.equals("1 day")) { return DAY; } return null; } public static long fromStringToLong(String string) { long hour = 3600 * 1000; switch (fromString(string)) { case ONE_HOUR: return hour; case THREE_HOURS: return hour * 3; case DAY: return hour * 24; default: return hour * 3; } } } public enum ReportOpenMode { EDITOR, INTERNAL_BROWSER, EXTERNAL_BROWSER; } private static ITaskActivationListener CONTEXT_TASK_ACTIVATION_LISTENER = new TaskActivationAdapter() { @Override public void taskActivated(final ITask task) { ContextCore.getContextManager().activateContext(task.getHandleIdentifier()); } @Override public void taskDeactivated(final ITask task) { ContextCore.getContextManager().deactivateContext(task.getHandleIdentifier()); } }; private static ITaskListNotificationProvider REMINDER_NOTIFICATION_PROVIDER = new ITaskListNotificationProvider() { public Set<AbstractNotification> getNotifications() { Collection<AbstractTask> allTasks = TasksUiPlugin.getTaskList().getAllTasks(); Set<AbstractNotification> reminders = new HashSet<AbstractNotification>(); for (AbstractTask task : allTasks) { if (task.isPastReminder() && !task.isReminded()) { reminders.add(new TaskListNotificationReminder(task)); task.setReminded(true); } } return reminders; } }; // private static ITaskListNotificationProvider INCOMING_NOTIFICATION_PROVIDER = new ITaskListNotificationProvider() { // // @SuppressWarnings( { "deprecation", "restriction" }) // public Set<AbstractNotification> getNotifications() { // Set<AbstractNotification> notifications = new HashSet<AbstractNotification>(); // // Incoming Changes // for (TaskRepository repository : getRepositoryManager().getAllRepositories()) { // AbstractRepositoryConnector connector = getRepositoryManager().getRepositoryConnector( // repository.getConnectorKind()); // if (connector instanceof AbstractLegacyRepositoryConnector) { // AbstractRepositoryConnectorUi connectorUi = getConnectorUi(repository.getConnectorKind()); // if (connectorUi != null && !connectorUi.hasCustomNotifications()) { // for (ITask itask : TasksUiPlugin.getTaskList().getTasks(repository.getRepositoryUrl())) { // if (itask instanceof AbstractTask) { // AbstractTask task = (AbstractTask) itask; // if ((task.getLastReadTimeStamp() == null || task.getSynchronizationState() == SynchronizationState.INCOMING) // && task.isNotified() == false) { // TaskListNotification notification = LegacyChangeManager.getIncommingNotification( // connector, task); // notifications.add(notification); // task.setNotified(true); // } // } // } // } // } // } // // New query hits // for (RepositoryQuery query : TasksUiPlugin.getTaskList().getQueries()) { // TaskRepository repository = getRepositoryManager().getRepository(query.getRepositoryUrl()); // if (repository != null) { // AbstractRepositoryConnector connector = getRepositoryManager().getRepositoryConnector( // repository.getConnectorKind()); // if (connector instanceof AbstractLegacyRepositoryConnector) { // AbstractRepositoryConnectorUi connectorUi = getConnectorUi(repository.getConnectorKind()); // if (!connectorUi.hasCustomNotifications()) { // for (ITask hit : query.getChildren()) { // if (((AbstractTask) hit).isNotified() == false) { // notifications.add(new TaskListNotificationQueryIncoming(hit)); // ((AbstractTask) hit).setNotified(true); // } // } // } // } // } // } // return notifications; // } // }; // private final IPropertyChangeListener PREFERENCE_LISTENER = new IPropertyChangeListener() { // // public void propertyChange(PropertyChangeEvent event) { // // TODO: do we ever get here? //// if (event.getProperty().equals(ContextPreferenceContstants.PREF_DATA_DIR)) { //// if (event.getOldValue() instanceof String) { //// reloadDataDirectory(); //// } //// } // } // }; private final org.eclipse.jface.util.IPropertyChangeListener PROPERTY_LISTENER = new org.eclipse.jface.util.IPropertyChangeListener() { public void propertyChange(org.eclipse.jface.util.PropertyChangeEvent event) { if (event.getProperty().equals(ITasksUiPreferenceConstants.PREF_DATA_DIR)) { if (event.getOldValue() instanceof String) { try { setDataDirectory((String) event.getNewValue(), new NullProgressMonitor(), false); } catch (CoreException e) { StatusHandler.log(new Status(IStatus.ERROR, ID_PLUGIN, "Unable to load from task data folder", e)); } } } if (event.getProperty().equals(ITasksUiPreferenceConstants.PLANNING_ENDHOUR) || event.getProperty().equals(ITasksUiPreferenceConstants.WEEK_START_DAY)) { updateTaskActivityManager(); } if (event.getProperty().equals(ITasksUiPreferenceConstants.REPOSITORY_SYNCH_SCHEDULE_ENABLED) || event.getProperty().equals(ITasksUiPreferenceConstants.REPOSITORY_SYNCH_SCHEDULE_MILISECONDS)) { updateSynchronizationScheduler(false); } } }; private TaskActivityMonitor taskActivityMonitor; private ServiceReference proxyServiceReference; private IProxyChangeListener proxyChangeListener; private TaskListExternalizationParticipant taskListSaveParticipant; private final Set<IRepositoryModelListener> listeners = new HashSet<IRepositoryModelListener>(); private boolean settingDataDirectory = false; private static TaskList taskList; private static RepositoryModel repositoryModel; private class TasksUiInitializationJob extends UIJob { public TasksUiInitializationJob() { super("Initializing Task List"); setSystem(true); } @Override public IStatus runInUIThread(IProgressMonitor monitor) { // NOTE: failure in one part of the initialization should // not prevent others monitor.beginTask("Initializing Task List", 5); try { // Needs to run after workbench is loaded because it // relies on images. TasksUiExtensionReader.initWorkbenchUiExtensions(); if (externalizationManager.getLoadStatus() != null) { // XXX: recovery from task list load failure (Rendered in task list) } // Needs to happen asynchronously to avoid bug 159706 for (AbstractTask task : taskListManager.getTaskList().getAllTasks()) { if (task.isActive()) { taskListManager.activateTask(task); break; } } //taskActivityMonitor.reloadActivityTime(); } catch (Throwable t) { StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "Could not initialize task activity", t)); } monitor.worked(1); try { taskListNotificationManager = new TaskListNotificationManager(); taskListNotificationManager.addNotificationProvider(REMINDER_NOTIFICATION_PROVIDER); // taskListNotificationManager.addNotificationProvider(INCOMING_NOTIFICATION_PROVIDER); taskListNotificationManager.addNotificationProvider(new TaskListNotifier(getRepositoryModel(), getTaskDataManager())); taskListNotificationManager.startNotification(NOTIFICATION_DELAY); getPreferenceStore().addPropertyChangeListener(taskListNotificationManager); } catch (Throwable t) { StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "Could not initialize notifications", t)); } monitor.worked(1); try { taskListBackupManager = new TaskListBackupManager(getBackupFolderPath()); getPreferenceStore().addPropertyChangeListener(taskListBackupManager); synchronizationScheduler = new TaskListSynchronizationScheduler(taskJobFactory); updateSynchronizationScheduler(true); } catch (Throwable t) { StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "Could not initialize task list backup and synchronization", t)); } monitor.worked(1); try { getPreferenceStore().addPropertyChangeListener(PROPERTY_LISTENER); // TODO: get rid of this, hack to make decorators show // up on startup TaskRepositoriesView repositoriesView = TaskRepositoriesView.getFromActivePerspective(); if (repositoriesView != null) { repositoriesView.getViewer().refresh(); } taskEditorBloatManager = new TaskEditorBloatMonitor(); taskEditorBloatManager.install(PlatformUI.getWorkbench()); } catch (Throwable t) { StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "Could not finish Tasks UI initialization", t)); } finally { monitor.done(); } return new Status(IStatus.OK, TasksUiPlugin.ID_PLUGIN, IStatus.OK, "", null); } } public TasksUiPlugin() { super(); INSTANCE = this; } private void updateSynchronizationScheduler(boolean initial) { boolean enabled = TasksUiPlugin.getDefault().getPreferenceStore().getBoolean( ITasksUiPreferenceConstants.REPOSITORY_SYNCH_SCHEDULE_ENABLED); if (enabled) { long interval = TasksUiPlugin.getDefault().getPreferenceStore().getLong( ITasksUiPreferenceConstants.REPOSITORY_SYNCH_SCHEDULE_MILISECONDS); if (initial) { synchronizationScheduler.setInterval(DELAY_QUERY_REFRESH_ON_STARTUP, interval); } else { synchronizationScheduler.setInterval(interval); } } else { synchronizationScheduler.setInterval(0); } } @SuppressWarnings( { "deprecation", "restriction" }) @Override public void start(BundleContext context) throws Exception { super.start(context); // NOTE: startup order is very sensitive try { // initialize framework and settings WebUtil.init(); WebClientLog.setLoggingEnabled(DEBUG_HTTPCLIENT); initializePreferences(getPreferenceStore()); // initialize CommonFonts from UI thread: bug 240076 - CommonFonts.BOLD.toString(); + if (CommonFonts.BOLD == null) { + // ignore + } File dataDir = new File(getDataDirectory()); dataDir.mkdirs(); // create data model externalizationManager = new ExternalizationManager(getDataDirectory()); repositoryManager = new TaskRepositoryManager(); IExternalizationParticipant repositoryParticipant = new RepositoryExternalizationParticipant( externalizationManager, repositoryManager); externalizationManager.addParticipant(repositoryParticipant); taskList = new TaskList(); repositoryModel = new RepositoryModel(taskList, repositoryManager); taskListExternalizer = new TaskListExternalizer(repositoryModel, repositoryManager); TaskListElementImporter taskListImporter = new TaskListElementImporter(repositoryManager, repositoryModel); taskListSaveParticipant = new TaskListExternalizationParticipant(repositoryModel, taskList, taskListExternalizer, externalizationManager, repositoryManager); //externalizationManager.load(taskListSaveParticipant); externalizationManager.addParticipant(taskListSaveParticipant); taskList.addChangeListener(taskListSaveParticipant); taskActivityManager = new TaskActivityManager(repositoryManager, taskList); taskActivityManager.addActivationListener(taskListSaveParticipant); taskListManager = new TaskListManager(taskList, taskListSaveParticipant, taskListImporter); // initialize updateTaskActivityManager(); proxyServiceReference = context.getServiceReference(IProxyService.class.getName()); if (proxyServiceReference != null) { IProxyService proxyService = (IProxyService) context.getService(proxyServiceReference); if (proxyService != null) { proxyChangeListener = new IProxyChangeListener() { public void proxyInfoChanged(IProxyChangeEvent event) { List<TaskRepository> repos = repositoryManager.getAllRepositories(); for (TaskRepository repo : repos) { if (repo.isDefaultProxyEnabled()) { repositoryManager.notifyRepositorySettingsChanged(repo); } } } }; proxyService.addProxyChangeListener(proxyChangeListener); } } repositoryTemplateManager = new RepositoryTemplateManager(); // NOTE: initializing extensions in start(..) has caused race // conditions previously TasksUiExtensionReader.initStartupExtensions(taskListExternalizer, taskListImporter); // instantiates taskDataManager File root = new File(this.getDataDirectory() + '/' + FOLDER_OFFLINE); OfflineFileStorage storage = new OfflineFileStorage(root); OfflineCachingStorage cachedStorage = new OfflineCachingStorage(storage); taskDataStorageManager = new TaskDataStorageManager(repositoryManager, cachedStorage); taskDataStorageManager.start(); TaskDataStore taskDataStore = new TaskDataStore(repositoryManager); taskDataManager = new TaskDataManager(taskDataStorageManager, taskDataStore, repositoryManager, taskListManager.getTaskList(), taskActivityManager); taskDataManager.setDataPath(getDataDirectory()); for (AbstractRepositoryConnector connector : repositoryManager.getRepositoryConnectors()) { if (connector instanceof AbstractLegacyRepositoryConnector) { ((AbstractLegacyRepositoryConnector) connector).init(taskDataManager); } } taskJobFactory = new TaskJobFactory(taskListManager.getTaskList(), taskDataManager, repositoryManager, repositoryModel); taskActivityManager.addActivationListener(CONTEXT_TASK_ACTIVATION_LISTENER); taskActivityMonitor = new TaskActivityMonitor(taskActivityManager, ContextCorePlugin.getContextManager()); taskActivityMonitor.start(); saveParticipant = new ISaveParticipant() { public void doneSaving(ISaveContext context) { } public void prepareToSave(ISaveContext context) throws CoreException { } public void rollback(ISaveContext context) { } public void saving(ISaveContext context) throws CoreException { if (context.getKind() == ISaveContext.FULL_SAVE) { externalizationManager.stop(); taskDataStorageManager.stop(); } } }; ResourcesPlugin.getWorkspace().addSaveParticipant(this, saveParticipant); ActivityExternalizationParticipant ACTIVITY_EXTERNALIZTAION_PARTICIPANT = new ActivityExternalizationParticipant( externalizationManager); externalizationManager.addParticipant(ACTIVITY_EXTERNALIZTAION_PARTICIPANT); taskActivityManager.addActivityListener(ACTIVITY_EXTERNALIZTAION_PARTICIPANT); taskActivityMonitor.setExternalizationParticipant(ACTIVITY_EXTERNALIZTAION_PARTICIPANT); loadDataSources(); new TasksUiInitializationJob().schedule(); } catch (Exception e) { StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "Task list initialization failed", e)); } } private void updateTaskActivityManager() { int endHour = getPreferenceStore().getInt(ITasksUiPreferenceConstants.PLANNING_ENDHOUR); // if (taskActivityManager.getEndHour() != endHour) { // taskActivityManager.setEndHour(endHour); TaskActivityUtil.setEndHour(endHour); // } int newWeekStartDay = getPreferenceStore().getInt(ITasksUiPreferenceConstants.WEEK_START_DAY); int oldWeekStartDay = taskActivityManager.getWeekStartDay(); if (oldWeekStartDay != newWeekStartDay) { taskActivityManager.setWeekStartDay(newWeekStartDay); // taskActivityManager.setStartTime(new Date()); } // event.getProperty().equals(TaskListPreferenceConstants.PLANNING_STARTDAY) // scheduledStartHour = // TasksUiPlugin.getDefault().getPreferenceStore().getInt( // TaskListPreferenceConstants.PLANNING_STARTHOUR); } private void loadTemplateRepositories() { // Add standard local task repository TaskRepository localRepository = getLocalTaskRepository(); // FIXME what does this line do? localRepository.setRepositoryLabel(LocalRepositoryConnector.REPOSITORY_LABEL); // Add the automatically created templates for (AbstractRepositoryConnector connector : repositoryManager.getRepositoryConnectors()) { for (RepositoryTemplate template : repositoryTemplateManager.getTemplates(connector.getConnectorKind())) { if (template.addAutomatically && !TaskRepositoryUtil.isAddAutomaticallyDisabled(template.repositoryUrl)) { try { TaskRepository taskRepository = repositoryManager.getRepository(connector.getConnectorKind(), template.repositoryUrl); if (taskRepository == null) { taskRepository = new TaskRepository(connector.getConnectorKind(), template.repositoryUrl); taskRepository.setVersion(template.version); taskRepository.setRepositoryLabel(template.label); taskRepository.setCharacterEncoding(template.characterEncoding); if (template.anonymous) { taskRepository.setCredentials(AuthenticationType.REPOSITORY, null, true); } repositoryManager.addRepository(taskRepository); } } catch (Throwable t) { StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "Could not load repository template", t)); } } } } } /** * Returns the local task repository. If the repository does not exist it is created and added to the task * repository manager. * * @return the local task repository; never <code>null</code> * @since 3.0 */ public TaskRepository getLocalTaskRepository() { TaskRepository localRepository = repositoryManager.getRepository(LocalRepositoryConnector.CONNECTOR_KIND, LocalRepositoryConnector.REPOSITORY_URL); if (localRepository == null) { localRepository = new TaskRepository(LocalRepositoryConnector.CONNECTOR_KIND, LocalRepositoryConnector.REPOSITORY_URL); localRepository.setVersion(LocalRepositoryConnector.REPOSITORY_VERSION); localRepository.setRepositoryLabel(LocalRepositoryConnector.REPOSITORY_LABEL); repositoryManager.addRepository(localRepository); } return localRepository; } @Override public void stop(BundleContext context) throws Exception { try { if (formColors != null) { formColors.dispose(); formColors = null; } if (taskActivityMonitor != null) { taskActivityMonitor.stop(); } if (ResourcesPlugin.getWorkspace() != null) { ResourcesPlugin.getWorkspace().removeSaveParticipant(this); } if (proxyServiceReference != null) { IProxyService proxyService = (IProxyService) context.getService(proxyServiceReference); if (proxyService != null) { proxyService.removeProxyChangeListener(proxyChangeListener); } context.ungetService(proxyServiceReference); } if (PlatformUI.isWorkbenchRunning()) { getPreferenceStore().removePropertyChangeListener(taskListNotificationManager); getPreferenceStore().removePropertyChangeListener(taskListBackupManager); getPreferenceStore().removePropertyChangeListener(PROPERTY_LISTENER); //taskListManager.getTaskList().removeChangeListener(taskListSaveManager); CommonColors.dispose(); // if (ContextCorePlugin.getDefault() != null) { // ContextCorePlugin.getDefault().getPluginPreferences().removePropertyChangeListener( // PREFERENCE_LISTENER); // } taskEditorBloatManager.dispose(PlatformUI.getWorkbench()); INSTANCE = null; } } catch (Exception e) { StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "Task list stop terminated abnormally", e)); } finally { super.stop(context); } } public String getDefaultDataDirectory() { return ResourcesPlugin.getWorkspace().getRoot().getLocation().toString() + '/' + DIRECTORY_METADATA + '/' + NAME_DATA_DIR; } public String getDataDirectory() { return getPreferenceStore().getString(ITasksUiPreferenceConstants.PREF_DATA_DIR); } /** * Save first, then load from <code>newPath</code>. Sets the new data directory, which upon setting results in * reload of task list information from the <code>newPath</code> supplied. * * @throws CoreException */ public void setDataDirectory(final String newPath, IProgressMonitor monitor) throws CoreException { setDataDirectory(newPath, monitor, true); } @SuppressWarnings("restriction") private void setDataDirectory(final String newPath, IProgressMonitor monitor, boolean setPreference) throws CoreException { // guard against updates from preference listeners that are triggered by the setValue() call below if (settingDataDirectory) { return; } // FIXME reset the preference in case switching to the new location fails? try { settingDataDirectory = true; loadDataDirectory(newPath, !setPreference); if (setPreference) { getPreferenceStore().setValue(ITasksUiPreferenceConstants.PREF_DATA_DIR, newPath); } File newFile = new File(newPath, ITasksCoreConstants.CONTEXTS_DIRECTORY); if (!newFile.exists()) { newFile.mkdirs(); } ContextCorePlugin.getContextStore().setContextDirectory(newFile); } finally { settingDataDirectory = false; } } public void reloadDataDirectory() throws CoreException { // no save just load what is there loadDataDirectory(getDataDirectory(), false); } /** * Load's data sources from <code>newPath</code> and executes with progress */ private synchronized void loadDataDirectory(final String newPath, final boolean save) throws CoreException { IRunnableWithProgress setDirectoryRunnable = new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { monitor.beginTask("Load Data Directory", IProgressMonitor.UNKNOWN); if (save) { externalizationManager.save(false); } Job.getJobManager().beginRule(ITasksCoreConstants.ROOT_SCHEDULING_RULE, new SubProgressMonitor(monitor, 1)); if (monitor.isCanceled()) { throw new InterruptedException(); } TasksUi.getTaskActivityManager().deactivateActiveTask(); externalizationManager.setRootFolderPath(newPath); loadDataSources(); } finally { Job.getJobManager().endRule(ITasksCoreConstants.ROOT_SCHEDULING_RULE); monitor.done(); } } }; IProgressService service = PlatformUI.getWorkbench().getProgressService(); try { if (!CoreUtil.TEST_MODE) { service.run(false, false, setDirectoryRunnable); } else { setDirectoryRunnable.run(new NullProgressMonitor()); } } catch (InvocationTargetException e) { throw new CoreException(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "Failed to set data directory", e.getCause())); } catch (InterruptedException e) { throw new OperationCanceledException(); } } /** * called on startup and when the mylyn data structures are reloaded from disk */ @SuppressWarnings("restriction") private void loadDataSources() { File storeFile = getContextStoreDir(); ContextCorePlugin.getContextStore().setContextDirectory(storeFile); externalizationManager.load(); // TODO: Move management of template repositories to TaskRepositoryManager loadTemplateRepositories(); taskActivityManager.clear(); ContextCorePlugin.getContextManager().loadActivityMetaContext(); taskActivityMonitor.reloadActivityTime(); taskActivityManager.reloadPlanningData(); for (final IRepositoryModelListener listener : listeners) { SafeRunner.run(new ISafeRunnable() { public void handleException(Throwable exception) { StatusHandler.log(new Status(IStatus.WARNING, TasksUiPlugin.ID_PLUGIN, "Listener failed: " + listener.getClass(), exception)); } public void run() throws Exception { listener.loaded(); } }); } } private File getContextStoreDir() { File storeFile = new File(getDataDirectory(), ITasksCoreConstants.CONTEXTS_DIRECTORY); if (!storeFile.exists()) { storeFile.mkdirs(); } return storeFile; } private void initializePreferences(IPreferenceStore store) { store.setDefault(ITasksUiPreferenceConstants.PREF_DATA_DIR, getDefaultDataDirectory()); store.setDefault(ITasksUiPreferenceConstants.GROUP_SUBTASKS, true); store.setDefault(ITasksUiPreferenceConstants.NOTIFICATIONS_ENABLED, true); store.setDefault(ITasksUiPreferenceConstants.FILTER_PRIORITY, PriorityLevel.P5.toString()); store.setDefault(ITasksUiPreferenceConstants.EDITOR_TASKS_RICH, true); store.setDefault(ITasksUiPreferenceConstants.ACTIVATE_WHEN_OPENED, false); store.setDefault(ITasksUiPreferenceConstants.SHOW_TRIM, false); store.setDefault(ITasksUiPreferenceConstants.LOCAL_SUB_TASKS_ENABLED, false); store.setDefault(ITasksUiPreferenceConstants.REPOSITORY_SYNCH_SCHEDULE_ENABLED, true); store.setDefault(ITasksUiPreferenceConstants.REPOSITORY_SYNCH_SCHEDULE_MILISECONDS, "" + (20 * 60 * 1000)); //store.setDefault(TasksUiPreferenceConstants.BACKUP_SCHEDULE, 1); store.setDefault(ITasksUiPreferenceConstants.BACKUP_MAXFILES, 20); store.setDefault(ITasksUiPreferenceConstants.BACKUP_LAST, 0f); store.setDefault(ITasksUiPreferenceConstants.FILTER_ARCHIVE_MODE, true); store.setDefault(ITasksUiPreferenceConstants.ACTIVATE_MULTIPLE, false); store.setValue(ITasksUiPreferenceConstants.ACTIVATE_MULTIPLE, false); store.setDefault(ITasksUiPreferenceConstants.WEEK_START_DAY, Calendar.getInstance().getFirstDayOfWeek()); //store.setDefault(TasksUiPreferenceConstants.PLANNING_STARTHOUR, 9); store.setDefault(ITasksUiPreferenceConstants.PLANNING_ENDHOUR, 18); } public static TaskListManager getTaskListManager() { return taskListManager; } public static TaskActivityManager getTaskActivityManager() { return taskActivityManager; } public static TaskListNotificationManager getTaskListNotificationManager() { return INSTANCE.taskListNotificationManager; } /** * Returns the shared instance. */ public static TasksUiPlugin getDefault() { return INSTANCE; } public boolean groupSubtasks(ITaskContainer element) { boolean groupSubtasks = TasksUiPlugin.getDefault().getPreferenceStore().getBoolean( ITasksUiPreferenceConstants.GROUP_SUBTASKS); if (element instanceof ITask) { AbstractRepositoryConnectorUi connectorUi = TasksUiPlugin.getConnectorUi(((ITask) element).getConnectorKind()); if (connectorUi != null) { if (connectorUi.hasStrictSubtaskHierarchy()) { groupSubtasks = true; } } } if (element instanceof IRepositoryQuery) { AbstractRepositoryConnectorUi connectorUi = TasksUiPlugin.getConnectorUi(((IRepositoryQuery) element).getConnectorKind()); if (connectorUi != null) { if (connectorUi.hasStrictSubtaskHierarchy()) { groupSubtasks = true; } } } return groupSubtasks; } private final Map<String, List<IDynamicSubMenuContributor>> menuContributors = new HashMap<String, List<IDynamicSubMenuContributor>>(); public Map<String, List<IDynamicSubMenuContributor>> getDynamicMenuMap() { return menuContributors; } // API-3.0: move to a standard dynamic menu mechanism? public void addDynamicPopupContributor(String menuPath, IDynamicSubMenuContributor contributor) { List<IDynamicSubMenuContributor> contributors = menuContributors.get(menuPath); if (contributors == null) { contributors = new ArrayList<IDynamicSubMenuContributor>(); menuContributors.put(menuPath, contributors); } contributors.add(contributor); } public String[] getSaveOptions() { String[] options = { TaskListSaveMode.ONE_HOUR.toString(), TaskListSaveMode.THREE_HOURS.toString(), TaskListSaveMode.DAY.toString() }; return options; } public String getBackupFolderPath() { return getDataDirectory() + DEFAULT_PATH_SEPARATOR + ITasksCoreConstants.DEFAULT_BACKUP_FOLDER_NAME; } public ITaskHighlighter getHighlighter() { return highlighter; } public void setHighlighter(ITaskHighlighter highlighter) { this.highlighter = highlighter; } /** * @since 3.0 */ public AbstractTaskEditorPageFactory[] getTaskEditorPageFactories() { return taskEditorPageFactories.toArray(new AbstractTaskEditorPageFactory[0]); } public Set<AbstractTaskEditorFactory> getTaskEditorFactories() { return taskEditorFactories; } public void addContextEditor(AbstractTaskEditorFactory contextEditor) { if (contextEditor != null) { this.taskEditorFactories.add(contextEditor); } } /** * @since 3.0 */ public void addTaskEditorPageFactory(AbstractTaskEditorPageFactory factory) { Assert.isNotNull(factory); taskEditorPageFactories.add(factory); } /** * @since 3.0 */ public void removeTaskEditorPageFactory(AbstractTaskEditorPageFactory factory) { Assert.isNotNull(factory); taskEditorPageFactories.remove(factory); } public static TaskRepositoryManager getRepositoryManager() { return repositoryManager; } /** * @since 3.0 */ public static RepositoryTemplateManager getRepositoryTemplateManager() { return INSTANCE.repositoryTemplateManager; } public void addBrandingIcon(String repositoryType, Image icon) { brandingIcons.put(repositoryType, icon); } public Image getBrandingIcon(String repositoryType) { return brandingIcons.get(repositoryType); } public void addOverlayIcon(String repositoryType, ImageDescriptor icon) { overlayIcons.put(repositoryType, icon); } public ImageDescriptor getOverlayIcon(String repositoryType) { return overlayIcons.get(repositoryType); } public void addRepositoryLinkProvider(AbstractTaskRepositoryLinkProvider repositoryLinkProvider) { if (repositoryLinkProvider != null) { this.repositoryLinkProviders.add(repositoryLinkProvider); } } public static TaskListBackupManager getBackupManager() { return INSTANCE.taskListBackupManager; } public static TaskDataStorageManager getTaskDataStorageManager() { return INSTANCE.taskDataStorageManager; } public void addRepositoryConnectorUi(AbstractRepositoryConnectorUi repositoryConnectorUi) { if (!repositoryConnectorUiMap.values().contains(repositoryConnectorUi)) { repositoryConnectorUiMap.put(repositoryConnectorUi.getConnectorKind(), repositoryConnectorUi); } } /** * @since 3.0 */ public static AbstractRepositoryConnector getConnector(String kind) { return getRepositoryManager().getRepositoryConnector(kind); } public static AbstractRepositoryConnectorUi getConnectorUi(String kind) { return repositoryConnectorUiMap.get(kind); } public static TaskListSynchronizationScheduler getSynchronizationScheduler() { return synchronizationScheduler; } /** * @since 3.0 */ public static TaskDataManager getTaskDataManager() { return taskDataManager; } /** * @since 3.0 */ public static TaskJobFactory getTaskJobFactory() { return INSTANCE.taskJobFactory; } public void addDuplicateDetector(AbstractDuplicateDetector duplicateDetector) { Assert.isNotNull(duplicateDetector); duplicateDetectors.add(duplicateDetector); } public Set<AbstractDuplicateDetector> getDuplicateSearchCollectorsList() { return duplicateDetectors; } public String getRepositoriesFilePath() { return getDataDirectory() + File.separator + TaskRepositoryManager.DEFAULT_REPOSITORIES_FILE; } public void addModelListener(IRepositoryModelListener listener) { listeners.add(listener); } public void removeModelListener(IRepositoryModelListener listener) { listeners.remove(listener); } public boolean canSetRepositoryForResource(IResource resource) { if (resource == null) { return false; } // find first provider that can link repository for (AbstractTaskRepositoryLinkProvider linkProvider : repositoryLinkProviders) { TaskRepository repository = linkProvider.getTaskRepository(resource, getRepositoryManager()); if (repository != null) { return linkProvider.canSetTaskRepository(resource); } } // find first provider that can set new repository for (AbstractTaskRepositoryLinkProvider linkProvider : repositoryLinkProviders) { if (linkProvider.canSetTaskRepository(resource)) { return true; } } return false; } /** * Associate a Task Repository with a workbench project * * @param resource * project or resource belonging to a project * @param repository * task repository to associate with given project * @throws CoreException */ public void setRepositoryForResource(IResource resource, TaskRepository repository) throws CoreException { if (resource == null || repository == null) { return; } for (AbstractTaskRepositoryLinkProvider linkProvider : repositoryLinkProviders) { TaskRepository r = linkProvider.getTaskRepository(resource, getRepositoryManager()); boolean canSetRepository = linkProvider.canSetTaskRepository(resource); if (r != null && !canSetRepository) { return; } if (canSetRepository) { linkProvider.setTaskRepository(resource, repository); return; } } } /** * Retrieve the task repository that has been associated with the given project (or resource belonging to a project) * * NOTE: if call does not return in LINK_PROVIDER_TIMEOUT_SECONDS, the provide will be disabled until the next time * that the Workbench starts. */ public TaskRepository getRepositoryForResource(final IResource resource) { Assert.isNotNull(resource); Set<AbstractTaskRepositoryLinkProvider> defectiveLinkProviders = new HashSet<AbstractTaskRepositoryLinkProvider>(); for (final AbstractTaskRepositoryLinkProvider linkProvider : repositoryLinkProviders) { long startTime = System.nanoTime(); final TaskRepository[] repository = new TaskRepository[1]; SafeRunnable.run(new ISafeRunnable() { public void handleException(Throwable e) { StatusHandler.log(new Status(IStatus.ERROR, ID_PLUGIN, "Repository link provider failed: \"" + linkProvider.getId() + "\"", e)); } public void run() throws Exception { repository[0] = linkProvider.getTaskRepository(resource, getRepositoryManager()); } }); long elapsed = System.nanoTime() - startTime; if (elapsed > LINK_PROVIDER_TIMEOUT_SECONDS * 1000 * 1000 * 1000) { defectiveLinkProviders.add(linkProvider); } if (repository[0] != null) { return repository[0]; } } if (!defectiveLinkProviders.isEmpty()) { repositoryLinkProviders.removeAll(defectiveLinkProviders); StatusHandler.log(new Status(IStatus.WARNING, ID_PLUGIN, "Repository link provider took over 5s to execute and was timed out: \"" + defectiveLinkProviders + "\"")); } return null; } @Deprecated public TaskRepository getRepositoryForResource(final IResource resource, boolean silent) { TaskRepository repository = getRepositoryForResource(resource); if (repository == null && !silent) { MessageDialog.openInformation(null, "No Repository Found", "No repository was found. Associate a Task Repository with this project via the project's property page."); } return repository; } public String getNextNewRepositoryTaskId() { return getTaskDataStorageManager().getNewRepositoryTaskId(); } public static ExternalizationManager getExternalizationManager() { return externalizationManager; } public static TaskActivityMonitor getTaskActivityMonitor() { return INSTANCE.taskActivityMonitor; } public static TaskList getTaskList() { return taskList; } public static RepositoryModel getRepositoryModel() { return repositoryModel; } /** * Note: This is provisional API that is used by connectors. * <p> * DO NOT CHANGE. */ public void addSearchHandler(AbstractSearchHandler searchHandler) { searchHandlers.add(searchHandler); } /** * Note: This is provisional API that is used by connectors. * <p> * DO NOT CHANGE. */ public void removeSearchHandler(AbstractSearchHandler searchHandler) { searchHandlers.remove(searchHandler); } public AbstractSearchHandler getSearchHandler(String connectorKind) { Assert.isNotNull(connectorKind); for (AbstractSearchHandler searchHandler : searchHandlers) { if (searchHandler.getConnectorKind().equals(connectorKind)) { return searchHandler; } } return null; } public FormColors getFormColors(Display display) { if (formColors == null) { formColors = new FormColors(display); formColors.markShared(); } return formColors; } }
true
true
public void start(BundleContext context) throws Exception { super.start(context); // NOTE: startup order is very sensitive try { // initialize framework and settings WebUtil.init(); WebClientLog.setLoggingEnabled(DEBUG_HTTPCLIENT); initializePreferences(getPreferenceStore()); // initialize CommonFonts from UI thread: bug 240076 CommonFonts.BOLD.toString(); File dataDir = new File(getDataDirectory()); dataDir.mkdirs(); // create data model externalizationManager = new ExternalizationManager(getDataDirectory()); repositoryManager = new TaskRepositoryManager(); IExternalizationParticipant repositoryParticipant = new RepositoryExternalizationParticipant( externalizationManager, repositoryManager); externalizationManager.addParticipant(repositoryParticipant); taskList = new TaskList(); repositoryModel = new RepositoryModel(taskList, repositoryManager); taskListExternalizer = new TaskListExternalizer(repositoryModel, repositoryManager); TaskListElementImporter taskListImporter = new TaskListElementImporter(repositoryManager, repositoryModel); taskListSaveParticipant = new TaskListExternalizationParticipant(repositoryModel, taskList, taskListExternalizer, externalizationManager, repositoryManager); //externalizationManager.load(taskListSaveParticipant); externalizationManager.addParticipant(taskListSaveParticipant); taskList.addChangeListener(taskListSaveParticipant); taskActivityManager = new TaskActivityManager(repositoryManager, taskList); taskActivityManager.addActivationListener(taskListSaveParticipant); taskListManager = new TaskListManager(taskList, taskListSaveParticipant, taskListImporter); // initialize updateTaskActivityManager(); proxyServiceReference = context.getServiceReference(IProxyService.class.getName()); if (proxyServiceReference != null) { IProxyService proxyService = (IProxyService) context.getService(proxyServiceReference); if (proxyService != null) { proxyChangeListener = new IProxyChangeListener() { public void proxyInfoChanged(IProxyChangeEvent event) { List<TaskRepository> repos = repositoryManager.getAllRepositories(); for (TaskRepository repo : repos) { if (repo.isDefaultProxyEnabled()) { repositoryManager.notifyRepositorySettingsChanged(repo); } } } }; proxyService.addProxyChangeListener(proxyChangeListener); } } repositoryTemplateManager = new RepositoryTemplateManager(); // NOTE: initializing extensions in start(..) has caused race // conditions previously TasksUiExtensionReader.initStartupExtensions(taskListExternalizer, taskListImporter); // instantiates taskDataManager File root = new File(this.getDataDirectory() + '/' + FOLDER_OFFLINE); OfflineFileStorage storage = new OfflineFileStorage(root); OfflineCachingStorage cachedStorage = new OfflineCachingStorage(storage); taskDataStorageManager = new TaskDataStorageManager(repositoryManager, cachedStorage); taskDataStorageManager.start(); TaskDataStore taskDataStore = new TaskDataStore(repositoryManager); taskDataManager = new TaskDataManager(taskDataStorageManager, taskDataStore, repositoryManager, taskListManager.getTaskList(), taskActivityManager); taskDataManager.setDataPath(getDataDirectory()); for (AbstractRepositoryConnector connector : repositoryManager.getRepositoryConnectors()) { if (connector instanceof AbstractLegacyRepositoryConnector) { ((AbstractLegacyRepositoryConnector) connector).init(taskDataManager); } } taskJobFactory = new TaskJobFactory(taskListManager.getTaskList(), taskDataManager, repositoryManager, repositoryModel); taskActivityManager.addActivationListener(CONTEXT_TASK_ACTIVATION_LISTENER); taskActivityMonitor = new TaskActivityMonitor(taskActivityManager, ContextCorePlugin.getContextManager()); taskActivityMonitor.start(); saveParticipant = new ISaveParticipant() { public void doneSaving(ISaveContext context) { } public void prepareToSave(ISaveContext context) throws CoreException { } public void rollback(ISaveContext context) { } public void saving(ISaveContext context) throws CoreException { if (context.getKind() == ISaveContext.FULL_SAVE) { externalizationManager.stop(); taskDataStorageManager.stop(); } } }; ResourcesPlugin.getWorkspace().addSaveParticipant(this, saveParticipant); ActivityExternalizationParticipant ACTIVITY_EXTERNALIZTAION_PARTICIPANT = new ActivityExternalizationParticipant( externalizationManager); externalizationManager.addParticipant(ACTIVITY_EXTERNALIZTAION_PARTICIPANT); taskActivityManager.addActivityListener(ACTIVITY_EXTERNALIZTAION_PARTICIPANT); taskActivityMonitor.setExternalizationParticipant(ACTIVITY_EXTERNALIZTAION_PARTICIPANT); loadDataSources(); new TasksUiInitializationJob().schedule(); } catch (Exception e) { StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "Task list initialization failed", e)); } }
public void start(BundleContext context) throws Exception { super.start(context); // NOTE: startup order is very sensitive try { // initialize framework and settings WebUtil.init(); WebClientLog.setLoggingEnabled(DEBUG_HTTPCLIENT); initializePreferences(getPreferenceStore()); // initialize CommonFonts from UI thread: bug 240076 if (CommonFonts.BOLD == null) { // ignore } File dataDir = new File(getDataDirectory()); dataDir.mkdirs(); // create data model externalizationManager = new ExternalizationManager(getDataDirectory()); repositoryManager = new TaskRepositoryManager(); IExternalizationParticipant repositoryParticipant = new RepositoryExternalizationParticipant( externalizationManager, repositoryManager); externalizationManager.addParticipant(repositoryParticipant); taskList = new TaskList(); repositoryModel = new RepositoryModel(taskList, repositoryManager); taskListExternalizer = new TaskListExternalizer(repositoryModel, repositoryManager); TaskListElementImporter taskListImporter = new TaskListElementImporter(repositoryManager, repositoryModel); taskListSaveParticipant = new TaskListExternalizationParticipant(repositoryModel, taskList, taskListExternalizer, externalizationManager, repositoryManager); //externalizationManager.load(taskListSaveParticipant); externalizationManager.addParticipant(taskListSaveParticipant); taskList.addChangeListener(taskListSaveParticipant); taskActivityManager = new TaskActivityManager(repositoryManager, taskList); taskActivityManager.addActivationListener(taskListSaveParticipant); taskListManager = new TaskListManager(taskList, taskListSaveParticipant, taskListImporter); // initialize updateTaskActivityManager(); proxyServiceReference = context.getServiceReference(IProxyService.class.getName()); if (proxyServiceReference != null) { IProxyService proxyService = (IProxyService) context.getService(proxyServiceReference); if (proxyService != null) { proxyChangeListener = new IProxyChangeListener() { public void proxyInfoChanged(IProxyChangeEvent event) { List<TaskRepository> repos = repositoryManager.getAllRepositories(); for (TaskRepository repo : repos) { if (repo.isDefaultProxyEnabled()) { repositoryManager.notifyRepositorySettingsChanged(repo); } } } }; proxyService.addProxyChangeListener(proxyChangeListener); } } repositoryTemplateManager = new RepositoryTemplateManager(); // NOTE: initializing extensions in start(..) has caused race // conditions previously TasksUiExtensionReader.initStartupExtensions(taskListExternalizer, taskListImporter); // instantiates taskDataManager File root = new File(this.getDataDirectory() + '/' + FOLDER_OFFLINE); OfflineFileStorage storage = new OfflineFileStorage(root); OfflineCachingStorage cachedStorage = new OfflineCachingStorage(storage); taskDataStorageManager = new TaskDataStorageManager(repositoryManager, cachedStorage); taskDataStorageManager.start(); TaskDataStore taskDataStore = new TaskDataStore(repositoryManager); taskDataManager = new TaskDataManager(taskDataStorageManager, taskDataStore, repositoryManager, taskListManager.getTaskList(), taskActivityManager); taskDataManager.setDataPath(getDataDirectory()); for (AbstractRepositoryConnector connector : repositoryManager.getRepositoryConnectors()) { if (connector instanceof AbstractLegacyRepositoryConnector) { ((AbstractLegacyRepositoryConnector) connector).init(taskDataManager); } } taskJobFactory = new TaskJobFactory(taskListManager.getTaskList(), taskDataManager, repositoryManager, repositoryModel); taskActivityManager.addActivationListener(CONTEXT_TASK_ACTIVATION_LISTENER); taskActivityMonitor = new TaskActivityMonitor(taskActivityManager, ContextCorePlugin.getContextManager()); taskActivityMonitor.start(); saveParticipant = new ISaveParticipant() { public void doneSaving(ISaveContext context) { } public void prepareToSave(ISaveContext context) throws CoreException { } public void rollback(ISaveContext context) { } public void saving(ISaveContext context) throws CoreException { if (context.getKind() == ISaveContext.FULL_SAVE) { externalizationManager.stop(); taskDataStorageManager.stop(); } } }; ResourcesPlugin.getWorkspace().addSaveParticipant(this, saveParticipant); ActivityExternalizationParticipant ACTIVITY_EXTERNALIZTAION_PARTICIPANT = new ActivityExternalizationParticipant( externalizationManager); externalizationManager.addParticipant(ACTIVITY_EXTERNALIZTAION_PARTICIPANT); taskActivityManager.addActivityListener(ACTIVITY_EXTERNALIZTAION_PARTICIPANT); taskActivityMonitor.setExternalizationParticipant(ACTIVITY_EXTERNALIZTAION_PARTICIPANT); loadDataSources(); new TasksUiInitializationJob().schedule(); } catch (Exception e) { StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "Task list initialization failed", e)); } }
diff --git a/src/org/jruby/compiler/ASTInspector.java b/src/org/jruby/compiler/ASTInspector.java index a50b41337..a16de3b18 100644 --- a/src/org/jruby/compiler/ASTInspector.java +++ b/src/org/jruby/compiler/ASTInspector.java @@ -1,736 +1,737 @@ /* ***** 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) 2007 Charles O Nutter <[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.Collections; import java.util.HashSet; import java.util.Set; import org.jruby.ast.AndNode; import org.jruby.ast.ArgsCatNode; import org.jruby.ast.ArgsNode; import org.jruby.ast.ArgsPushNode; import org.jruby.ast.AssignableNode; import org.jruby.ast.AttrAssignNode; import org.jruby.ast.BeginNode; import org.jruby.ast.BinaryOperatorNode; import org.jruby.ast.BlockAcceptingNode; import org.jruby.ast.BlockNode; import org.jruby.ast.BlockPassNode; import org.jruby.ast.BreakNode; import org.jruby.ast.CallNode; import org.jruby.ast.CaseNode; import org.jruby.ast.Colon2Node; import org.jruby.ast.ConstNode; import org.jruby.ast.DefinedNode; import org.jruby.ast.DotNode; import org.jruby.ast.EvStrNode; import org.jruby.ast.FlipNode; import org.jruby.ast.ForNode; import org.jruby.ast.GlobalAsgnNode; import org.jruby.ast.GlobalVarNode; import org.jruby.ast.HashNode; import org.jruby.ast.IArgumentNode; import org.jruby.ast.IScopingNode; import org.jruby.ast.IfNode; import org.jruby.ast.ListNode; import org.jruby.ast.LocalAsgnNode; import org.jruby.ast.Match2Node; import org.jruby.ast.Match3Node; import org.jruby.ast.MatchNode; import org.jruby.ast.MultipleAsgn19Node; import org.jruby.ast.MultipleAsgnNode; import org.jruby.ast.NewlineNode; import org.jruby.ast.NextNode; import org.jruby.ast.Node; import org.jruby.ast.NotNode; import org.jruby.ast.OpAsgnAndNode; import org.jruby.ast.OpAsgnNode; import org.jruby.ast.OpAsgnOrNode; import org.jruby.ast.OpElementAsgnNode; import org.jruby.ast.OptArgNode; import org.jruby.ast.OrNode; import org.jruby.ast.PostExeNode; import org.jruby.ast.PreExeNode; import org.jruby.ast.ReturnNode; import org.jruby.ast.RootNode; import org.jruby.ast.SValueNode; import org.jruby.ast.SplatNode; import org.jruby.ast.SuperNode; import org.jruby.ast.ToAryNode; import org.jruby.ast.TrueNode; import org.jruby.ast.UntilNode; import org.jruby.ast.WhenNode; import org.jruby.ast.WhileNode; import org.jruby.ast.YieldNode; import org.jruby.ast.ZSuperNode; import org.jruby.ast.types.INameNode; import org.jruby.util.SafePropertyAccessor; /** * * @author headius */ public class ASTInspector { public static final int BLOCK_ARG = 0x1; // block argument to the method public static final int CLOSURE = 0x2; // closure present public static final int CLASS = 0x4; // class present public static final int METHOD = 0x8; // method table mutations, def, defs, undef, alias public static final int EVAL = 0x10; // likely call to eval public static final int FRAME_AWARE = 0x20; // makes calls that are aware of the frame public static final int FRAME_SELF = 0x40; // makes calls that are aware of the frame's self public static final int FRAME_VISIBILITY = 0x80; // makes calls that are aware of the frame's visibility public static final int FRAME_BLOCK = 0x100; // makes calls that are aware of the frame's block public static final int FRAME_NAME = 0x200; // makes calls that are aware of the frame's name public static final int BACKREF = 0x400; // makes calls that set or get backref public static final int LASTLINE = 0x800; // makes calls that set or get lastline public static final int FRAME_CLASS = 0x1000; // makes calls that are aware of the frame's class public static final int OPT_ARGS = 0x2000; // optional arguments to the method public static final int REST_ARG = 0x4000; // rest arg to the method public static final int SCOPE_AWARE = 0x8000; // makes calls that are aware of the scope public static final int ZSUPER = 0x10000; // makes a zero-argument super call public static final int CONSTANT = 0x20000; // accesses or sets constants public static final int CLASS_VAR = 0x40000; // accesses or sets class variables private int flags; // pragmas private boolean noFrame; public static Set<String> FRAME_AWARE_METHODS = Collections.synchronizedSet(new HashSet<String>()); private static Set<String> SCOPE_AWARE_METHODS = Collections.synchronizedSet(new HashSet<String>()); public static Set<String> PRAGMAS = Collections.synchronizedSet(new HashSet<String>()); static { FRAME_AWARE_METHODS.add("eval"); FRAME_AWARE_METHODS.add("module_eval"); FRAME_AWARE_METHODS.add("class_eval"); FRAME_AWARE_METHODS.add("instance_eval"); FRAME_AWARE_METHODS.add("binding"); FRAME_AWARE_METHODS.add("public"); FRAME_AWARE_METHODS.add("private"); FRAME_AWARE_METHODS.add("protected"); FRAME_AWARE_METHODS.add("module_function"); FRAME_AWARE_METHODS.add("block_given?"); FRAME_AWARE_METHODS.add("iterator?"); SCOPE_AWARE_METHODS.add("eval"); SCOPE_AWARE_METHODS.add("module_eval"); SCOPE_AWARE_METHODS.add("class_eval"); SCOPE_AWARE_METHODS.add("instance_eval"); SCOPE_AWARE_METHODS.add("binding"); SCOPE_AWARE_METHODS.add("local_variables"); PRAGMAS.add("__NOFRAME__"); } public void disable() { flags = 0xFFFFFFFF; } public static final boolean ENABLED = SafePropertyAccessor.getProperty("jruby.astInspector.enabled", "true").equals("true"); /** * Perform an inspection of a subtree or set of subtrees separate from the * parent inspection, to make independent decisions based on that subtree(s). * * @param nodes The child nodes to walk with a new inspector * @return The new inspector resulting from the walk */ public static ASTInspector subInspect(Node... nodes) { ASTInspector newInspector = new ASTInspector(); for (Node node : nodes) { newInspector.inspect(node); } return newInspector; } public boolean getFlag(int modifier) { return (flags & modifier) != 0; } public void setFlag(int modifier) { flags |= modifier; } /** * Integrate the results of a separate inspection into the state of this * inspector. * * @param other The other inspector whose state to integrate. */ public void integrate(ASTInspector other) { flags |= other.flags; } public void inspect(Node node) { // TODO: This code effectively disables all inspection-based optimizations; none of them are 100% safe yet if (!ENABLED) disable(); if (node == null) return; switch (node.nodeId) { case ALIASNODE: setFlag(METHOD); break; case ANDNODE: AndNode andNode = (AndNode)node; inspect(andNode.getFirstNode()); inspect(andNode.getSecondNode()); break; case ARGSCATNODE: ArgsCatNode argsCatNode = (ArgsCatNode)node; inspect(argsCatNode.getFirstNode()); inspect(argsCatNode.getSecondNode()); break; case ARGSPUSHNODE: ArgsPushNode argsPushNode = (ArgsPushNode)node; inspect(argsPushNode.getFirstNode()); inspect(argsPushNode.getSecondNode()); break; case ARGUMENTNODE: break; case ARRAYNODE: case BLOCKNODE: case DREGEXPNODE: case DSTRNODE: case DSYMBOLNODE: case DXSTRNODE: case LISTNODE: ListNode listNode = (ListNode)node; for (int i = 0; i < listNode.size(); i++) { inspect(listNode.get(i)); } break; case ARGSNODE: ArgsNode argsNode = (ArgsNode)node; if (argsNode.getBlock() != null) setFlag(BLOCK_ARG); if (argsNode.getOptArgs() != null) { setFlag(OPT_ARGS); inspect(argsNode.getOptArgs()); } if (argsNode.getRestArg() == -2 || argsNode.getRestArg() >= 0) setFlag(REST_ARG); break; case ATTRASSIGNNODE: AttrAssignNode attrAssignNode = (AttrAssignNode)node; setFlag(FRAME_SELF); inspect(attrAssignNode.getArgsNode()); inspect(attrAssignNode.getReceiverNode()); break; case BACKREFNODE: setFlag(BACKREF); break; case BEGINNODE: inspect(((BeginNode)node).getBodyNode()); break; case BIGNUMNODE: break; case BINARYOPERATORNODE: BinaryOperatorNode binaryOperatorNode = (BinaryOperatorNode)node; inspect(binaryOperatorNode.getFirstNode()); inspect(binaryOperatorNode.getSecondNode()); break; case BLOCKARGNODE: break; case BLOCKPASSNODE: BlockPassNode blockPassNode = (BlockPassNode)node; inspect(blockPassNode.getArgsNode()); inspect(blockPassNode.getBodyNode()); break; case BREAKNODE: inspect(((BreakNode)node).getValueNode()); break; case CALLNODE: CallNode callNode = (CallNode)node; inspect(callNode.getReceiverNode()); // check for Proc.new, an especially magic method if (callNode.getName() == "new" && callNode.getReceiverNode() instanceof ConstNode && ((ConstNode)callNode.getReceiverNode()).getName() == "Proc") { // Proc.new needs the caller's block to instantiate a proc setFlag(FRAME_BLOCK); } case FCALLNODE: inspect(((IArgumentNode)node).getArgsNode()); inspect(((BlockAcceptingNode)node).getIterNode()); case VCALLNODE: INameNode nameNode = (INameNode)node; if (FRAME_AWARE_METHODS.contains(nameNode.getName())) { setFlag(FRAME_AWARE); if (nameNode.getName().indexOf("eval") != -1) { setFlag(EVAL); } } if (SCOPE_AWARE_METHODS.contains(nameNode.getName())) { setFlag(SCOPE_AWARE); } break; case CASENODE: CaseNode caseNode = (CaseNode)node; inspect(caseNode.getCaseNode()); inspect(caseNode.getFirstWhenNode()); break; case CLASSNODE: setFlag(CLASS); break; case CLASSVARNODE: setFlag(CLASS_VAR); break; case CONSTDECLNODE: inspect(((AssignableNode)node).getValueNode()); setFlag(CONSTANT); break; case CLASSVARASGNNODE: inspect(((AssignableNode)node).getValueNode()); setFlag(CLASS_VAR); break; case CLASSVARDECLNODE: inspect(((AssignableNode)node).getValueNode()); setFlag(CLASS_VAR); break; case COLON2NODE: inspect(((Colon2Node)node).getLeftNode()); break; case COLON3NODE: break; case CONSTNODE: setFlag(CONSTANT); break; case DEFNNODE: case DEFSNODE: setFlag(METHOD); setFlag(FRAME_VISIBILITY); break; case DEFINEDNODE: switch (((DefinedNode)node).getExpressionNode().nodeId) { case CLASSVARASGNNODE: case CLASSVARDECLNODE: case CONSTDECLNODE: case DASGNNODE: case GLOBALASGNNODE: case LOCALASGNNODE: case MULTIPLEASGNNODE: case OPASGNNODE: case OPELEMENTASGNNODE: case DVARNODE: case FALSENODE: case TRUENODE: case LOCALVARNODE: case INSTVARNODE: case BACKREFNODE: case SELFNODE: case VCALLNODE: case YIELDNODE: case GLOBALVARNODE: case CONSTNODE: case FCALLNODE: case CLASSVARNODE: // ok, we have fast paths inspect(((DefinedNode)node).getExpressionNode()); break; default: // long, slow way causes disabling disable(); } break; case DOTNODE: DotNode dotNode = (DotNode)node; inspect(dotNode.getBeginNode()); inspect(dotNode.getEndNode()); break; case DASGNNODE: inspect(((AssignableNode)node).getValueNode()); break; case DVARNODE: break; case ENSURENODE: disable(); break; case EVSTRNODE: inspect(((EvStrNode)node).getBody()); break; case FALSENODE: break; case FIXNUMNODE: break; case FLIPNODE: inspect(((FlipNode)node).getBeginNode()); inspect(((FlipNode)node).getEndNode()); break; case FLOATNODE: break; case FORNODE: setFlag(CLOSURE); setFlag(SCOPE_AWARE); inspect(((ForNode)node).getIterNode()); inspect(((ForNode)node).getBodyNode()); inspect(((ForNode)node).getVarNode()); break; case GLOBALASGNNODE: GlobalAsgnNode globalAsgnNode = (GlobalAsgnNode)node; if (globalAsgnNode.getName().equals("$_")) { setFlag(LASTLINE); } else if (globalAsgnNode.getName().equals("$~")) { setFlag(BACKREF); } + inspect(globalAsgnNode.getValueNode()); break; case GLOBALVARNODE: if (((GlobalVarNode)node).getName().equals("$_")) { setFlag(LASTLINE); } else if (((GlobalVarNode)node).getName().equals("$~")) { setFlag(BACKREF); } break; case HASHNODE: HashNode hashNode = (HashNode)node; inspect(hashNode.getListNode()); break; case IFNODE: IfNode ifNode = (IfNode)node; inspect(ifNode.getCondition()); inspect(ifNode.getThenBody()); inspect(ifNode.getElseBody()); break; case INSTASGNNODE: inspect(((AssignableNode)node).getValueNode()); break; case INSTVARNODE: break; case ISCOPINGNODE: IScopingNode iscopingNode = (IScopingNode)node; inspect(iscopingNode.getCPath()); break; case ITERNODE: setFlag(CLOSURE); break; case LAMBDANODE: setFlag(CLOSURE); break; case LOCALASGNNODE: LocalAsgnNode localAsgnNode = (LocalAsgnNode)node; if (PRAGMAS.contains(localAsgnNode.getName())) { if (localAsgnNode.getName().equals("__NOFRAME__")) { noFrame = localAsgnNode.getValueNode() instanceof TrueNode; } break; } inspect(localAsgnNode.getValueNode()); break; case LOCALVARNODE: break; case MATCHNODE: inspect(((MatchNode)node).getRegexpNode()); setFlag(BACKREF); break; case MATCH2NODE: Match2Node match2Node = (Match2Node)node; inspect(match2Node.getReceiverNode()); inspect(match2Node.getValueNode()); setFlag(BACKREF); break; case MATCH3NODE: Match3Node match3Node = (Match3Node)node; inspect(match3Node.getReceiverNode()); inspect(match3Node.getValueNode()); setFlag(BACKREF); break; case MODULENODE: setFlag(CLASS); break; case MULTIPLEASGN19NODE: MultipleAsgn19Node multipleAsgn19Node = (MultipleAsgn19Node)node; inspect(multipleAsgn19Node.getPre()); inspect(multipleAsgn19Node.getPost()); inspect(multipleAsgn19Node.getRest()); inspect(multipleAsgn19Node.getValueNode()); break; case MULTIPLEASGNNODE: MultipleAsgnNode multipleAsgnNode = (MultipleAsgnNode)node; inspect(multipleAsgnNode.getArgsNode()); inspect(multipleAsgnNode.getHeadNode()); inspect(multipleAsgnNode.getValueNode()); break; case NEWLINENODE: inspect(((NewlineNode)node).getNextNode()); break; case NEXTNODE: inspect(((NextNode)node).getValueNode()); break; case NILNODE: break; case NOTNODE: inspect(((NotNode)node).getConditionNode()); break; case NTHREFNODE: break; case OPASGNANDNODE: OpAsgnAndNode opAsgnAndNode = (OpAsgnAndNode)node; inspect(opAsgnAndNode.getFirstNode()); inspect(opAsgnAndNode.getSecondNode()); break; case OPASGNNODE: OpAsgnNode opAsgnNode = (OpAsgnNode)node; inspect(opAsgnNode.getReceiverNode()); inspect(opAsgnNode.getValueNode()); break; case OPASGNORNODE: switch (((OpAsgnOrNode)node).getFirstNode().nodeId) { case CLASSVARASGNNODE: case CLASSVARDECLNODE: case CONSTDECLNODE: case DASGNNODE: case GLOBALASGNNODE: case LOCALASGNNODE: case MULTIPLEASGNNODE: case OPASGNNODE: case OPELEMENTASGNNODE: case DVARNODE: case FALSENODE: case TRUENODE: case LOCALVARNODE: case INSTVARNODE: case BACKREFNODE: case SELFNODE: case VCALLNODE: case YIELDNODE: case GLOBALVARNODE: case CONSTNODE: case FCALLNODE: case CLASSVARNODE: // ok, we have fast paths inspect(((OpAsgnOrNode)node).getSecondNode()); break; default: // long, slow way causes disabling for defined disable(); } break; case OPELEMENTASGNNODE: OpElementAsgnNode opElementAsgnNode = (OpElementAsgnNode)node; setFlag(FRAME_SELF); inspect(opElementAsgnNode.getArgsNode()); inspect(opElementAsgnNode.getReceiverNode()); inspect(opElementAsgnNode.getValueNode()); break; case OPTARGNODE: inspect(((OptArgNode)node).getValue()); break; case ORNODE: OrNode orNode = (OrNode)node; inspect(orNode.getFirstNode()); inspect(orNode.getSecondNode()); break; case POSTEXENODE: PostExeNode postExeNode = (PostExeNode)node; setFlag(CLOSURE); setFlag(SCOPE_AWARE); inspect(postExeNode.getBodyNode()); inspect(postExeNode.getVarNode()); break; case PREEXENODE: PreExeNode preExeNode = (PreExeNode)node; setFlag(CLOSURE); setFlag(SCOPE_AWARE); inspect(preExeNode.getBodyNode()); inspect(preExeNode.getVarNode()); break; case REDONODE: break; case REGEXPNODE: break; case ROOTNODE: inspect(((RootNode)node).getBodyNode()); if (((RootNode)node).getBodyNode() instanceof BlockNode) { BlockNode blockNode = (BlockNode)((RootNode)node).getBodyNode(); if (blockNode.size() > 500) { // method has more than 500 lines; we'll need to split it // and therefore need to use a heap-based scope setFlag(SCOPE_AWARE); } } break; case RESCUEBODYNODE: disable(); break; case RESCUENODE: disable(); break; case RETRYNODE: disable(); break; case RETURNNODE: inspect(((ReturnNode)node).getValueNode()); break; case SCLASSNODE: setFlag(CLASS); break; case SCOPENODE: break; case SELFNODE: break; case SPLATNODE: inspect(((SplatNode)node).getValue()); break; case STARNODE: break; case STRNODE: break; case SUPERNODE: SuperNode superNode = (SuperNode)node; inspect(superNode.getArgsNode()); inspect(superNode.getIterNode()); break; case SVALUENODE: inspect(((SValueNode)node).getValue()); break; case SYMBOLNODE: break; case TOARYNODE: inspect(((ToAryNode)node).getValue()); break; case TRUENODE: break; case UNDEFNODE: setFlag(METHOD); break; case UNTILNODE: UntilNode untilNode = (UntilNode)node; ASTInspector untilInspector = subInspect( untilNode.getConditionNode(), untilNode.getBodyNode()); // a while node could receive non-local flow control from any of these: // * a closure within the loop // * an eval within the loop // * a block-arg-based proc called within the loop if (untilInspector.getFlag(CLOSURE) || untilInspector.getFlag(EVAL)) { untilNode.containsNonlocalFlow = true; // we set scope-aware to true to force heap-based locals setFlag(SCOPE_AWARE); } integrate(untilInspector); break; case VALIASNODE: break; case WHENNODE: inspect(((WhenNode)node).getBodyNode()); inspect(((WhenNode)node).getExpressionNodes()); inspect(((WhenNode)node).getNextCase()); break; case WHILENODE: WhileNode whileNode = (WhileNode)node; ASTInspector whileInspector = subInspect( whileNode.getConditionNode(), whileNode.getBodyNode()); // a while node could receive non-local flow control from any of these: // * a closure within the loop // * an eval within the loop // * a block-arg-based proc called within the loop if (whileInspector.getFlag(CLOSURE) || whileInspector.getFlag(EVAL) || getFlag(BLOCK_ARG)) { whileNode.containsNonlocalFlow = true; // we set scope-aware to true to force heap-based locals setFlag(SCOPE_AWARE); } integrate(whileInspector); break; case XSTRNODE: break; case YIELDNODE: inspect(((YieldNode)node).getArgsNode()); break; case ZARRAYNODE: break; case ZEROARGNODE: break; case ZSUPERNODE: setFlag(SCOPE_AWARE); setFlag(ZSUPER); inspect(((ZSuperNode)node).getIterNode()); break; default: // encountered a node we don't recognize, set everything to true to disable optz assert false : "All nodes should be accounted for in AST inspector: " + node; disable(); } } public boolean hasClass() { return getFlag(CLASS); } public boolean hasClosure() { return getFlag(CLOSURE); } /** * Whether the tree under inspection contains any method-table mutations, * including def, defs, undef, and alias. * * @return True if there are mutations, false otherwise */ public boolean hasMethod() { return getFlag(METHOD); } public boolean hasFrameAwareMethods() { return getFlag( FRAME_AWARE | FRAME_BLOCK | FRAME_CLASS | FRAME_NAME | FRAME_SELF | FRAME_VISIBILITY | CLOSURE | EVAL | BACKREF | LASTLINE | ZSUPER); } public boolean hasScopeAwareMethods() { return getFlag(SCOPE_AWARE); } public boolean hasBlockArg() { return getFlag(BLOCK_ARG); } public boolean hasOptArgs() { return getFlag(OPT_ARGS); } public boolean hasRestArg() { return getFlag(REST_ARG); } public boolean hasConstant() { return getFlag(CONSTANT); } public boolean hasClassVar() { return getFlag(CLASS_VAR); } public boolean noFrame() { return noFrame; } }
true
true
public void inspect(Node node) { // TODO: This code effectively disables all inspection-based optimizations; none of them are 100% safe yet if (!ENABLED) disable(); if (node == null) return; switch (node.nodeId) { case ALIASNODE: setFlag(METHOD); break; case ANDNODE: AndNode andNode = (AndNode)node; inspect(andNode.getFirstNode()); inspect(andNode.getSecondNode()); break; case ARGSCATNODE: ArgsCatNode argsCatNode = (ArgsCatNode)node; inspect(argsCatNode.getFirstNode()); inspect(argsCatNode.getSecondNode()); break; case ARGSPUSHNODE: ArgsPushNode argsPushNode = (ArgsPushNode)node; inspect(argsPushNode.getFirstNode()); inspect(argsPushNode.getSecondNode()); break; case ARGUMENTNODE: break; case ARRAYNODE: case BLOCKNODE: case DREGEXPNODE: case DSTRNODE: case DSYMBOLNODE: case DXSTRNODE: case LISTNODE: ListNode listNode = (ListNode)node; for (int i = 0; i < listNode.size(); i++) { inspect(listNode.get(i)); } break; case ARGSNODE: ArgsNode argsNode = (ArgsNode)node; if (argsNode.getBlock() != null) setFlag(BLOCK_ARG); if (argsNode.getOptArgs() != null) { setFlag(OPT_ARGS); inspect(argsNode.getOptArgs()); } if (argsNode.getRestArg() == -2 || argsNode.getRestArg() >= 0) setFlag(REST_ARG); break; case ATTRASSIGNNODE: AttrAssignNode attrAssignNode = (AttrAssignNode)node; setFlag(FRAME_SELF); inspect(attrAssignNode.getArgsNode()); inspect(attrAssignNode.getReceiverNode()); break; case BACKREFNODE: setFlag(BACKREF); break; case BEGINNODE: inspect(((BeginNode)node).getBodyNode()); break; case BIGNUMNODE: break; case BINARYOPERATORNODE: BinaryOperatorNode binaryOperatorNode = (BinaryOperatorNode)node; inspect(binaryOperatorNode.getFirstNode()); inspect(binaryOperatorNode.getSecondNode()); break; case BLOCKARGNODE: break; case BLOCKPASSNODE: BlockPassNode blockPassNode = (BlockPassNode)node; inspect(blockPassNode.getArgsNode()); inspect(blockPassNode.getBodyNode()); break; case BREAKNODE: inspect(((BreakNode)node).getValueNode()); break; case CALLNODE: CallNode callNode = (CallNode)node; inspect(callNode.getReceiverNode()); // check for Proc.new, an especially magic method if (callNode.getName() == "new" && callNode.getReceiverNode() instanceof ConstNode && ((ConstNode)callNode.getReceiverNode()).getName() == "Proc") { // Proc.new needs the caller's block to instantiate a proc setFlag(FRAME_BLOCK); } case FCALLNODE: inspect(((IArgumentNode)node).getArgsNode()); inspect(((BlockAcceptingNode)node).getIterNode()); case VCALLNODE: INameNode nameNode = (INameNode)node; if (FRAME_AWARE_METHODS.contains(nameNode.getName())) { setFlag(FRAME_AWARE); if (nameNode.getName().indexOf("eval") != -1) { setFlag(EVAL); } } if (SCOPE_AWARE_METHODS.contains(nameNode.getName())) { setFlag(SCOPE_AWARE); } break; case CASENODE: CaseNode caseNode = (CaseNode)node; inspect(caseNode.getCaseNode()); inspect(caseNode.getFirstWhenNode()); break; case CLASSNODE: setFlag(CLASS); break; case CLASSVARNODE: setFlag(CLASS_VAR); break; case CONSTDECLNODE: inspect(((AssignableNode)node).getValueNode()); setFlag(CONSTANT); break; case CLASSVARASGNNODE: inspect(((AssignableNode)node).getValueNode()); setFlag(CLASS_VAR); break; case CLASSVARDECLNODE: inspect(((AssignableNode)node).getValueNode()); setFlag(CLASS_VAR); break; case COLON2NODE: inspect(((Colon2Node)node).getLeftNode()); break; case COLON3NODE: break; case CONSTNODE: setFlag(CONSTANT); break; case DEFNNODE: case DEFSNODE: setFlag(METHOD); setFlag(FRAME_VISIBILITY); break; case DEFINEDNODE: switch (((DefinedNode)node).getExpressionNode().nodeId) { case CLASSVARASGNNODE: case CLASSVARDECLNODE: case CONSTDECLNODE: case DASGNNODE: case GLOBALASGNNODE: case LOCALASGNNODE: case MULTIPLEASGNNODE: case OPASGNNODE: case OPELEMENTASGNNODE: case DVARNODE: case FALSENODE: case TRUENODE: case LOCALVARNODE: case INSTVARNODE: case BACKREFNODE: case SELFNODE: case VCALLNODE: case YIELDNODE: case GLOBALVARNODE: case CONSTNODE: case FCALLNODE: case CLASSVARNODE: // ok, we have fast paths inspect(((DefinedNode)node).getExpressionNode()); break; default: // long, slow way causes disabling disable(); } break; case DOTNODE: DotNode dotNode = (DotNode)node; inspect(dotNode.getBeginNode()); inspect(dotNode.getEndNode()); break; case DASGNNODE: inspect(((AssignableNode)node).getValueNode()); break; case DVARNODE: break; case ENSURENODE: disable(); break; case EVSTRNODE: inspect(((EvStrNode)node).getBody()); break; case FALSENODE: break; case FIXNUMNODE: break; case FLIPNODE: inspect(((FlipNode)node).getBeginNode()); inspect(((FlipNode)node).getEndNode()); break; case FLOATNODE: break; case FORNODE: setFlag(CLOSURE); setFlag(SCOPE_AWARE); inspect(((ForNode)node).getIterNode()); inspect(((ForNode)node).getBodyNode()); inspect(((ForNode)node).getVarNode()); break; case GLOBALASGNNODE: GlobalAsgnNode globalAsgnNode = (GlobalAsgnNode)node; if (globalAsgnNode.getName().equals("$_")) { setFlag(LASTLINE); } else if (globalAsgnNode.getName().equals("$~")) { setFlag(BACKREF); } break; case GLOBALVARNODE: if (((GlobalVarNode)node).getName().equals("$_")) { setFlag(LASTLINE); } else if (((GlobalVarNode)node).getName().equals("$~")) { setFlag(BACKREF); } break; case HASHNODE: HashNode hashNode = (HashNode)node; inspect(hashNode.getListNode()); break; case IFNODE: IfNode ifNode = (IfNode)node; inspect(ifNode.getCondition()); inspect(ifNode.getThenBody()); inspect(ifNode.getElseBody()); break; case INSTASGNNODE: inspect(((AssignableNode)node).getValueNode()); break; case INSTVARNODE: break; case ISCOPINGNODE: IScopingNode iscopingNode = (IScopingNode)node; inspect(iscopingNode.getCPath()); break; case ITERNODE: setFlag(CLOSURE); break; case LAMBDANODE: setFlag(CLOSURE); break; case LOCALASGNNODE: LocalAsgnNode localAsgnNode = (LocalAsgnNode)node; if (PRAGMAS.contains(localAsgnNode.getName())) { if (localAsgnNode.getName().equals("__NOFRAME__")) { noFrame = localAsgnNode.getValueNode() instanceof TrueNode; } break; } inspect(localAsgnNode.getValueNode()); break; case LOCALVARNODE: break; case MATCHNODE: inspect(((MatchNode)node).getRegexpNode()); setFlag(BACKREF); break; case MATCH2NODE: Match2Node match2Node = (Match2Node)node; inspect(match2Node.getReceiverNode()); inspect(match2Node.getValueNode()); setFlag(BACKREF); break; case MATCH3NODE: Match3Node match3Node = (Match3Node)node; inspect(match3Node.getReceiverNode()); inspect(match3Node.getValueNode()); setFlag(BACKREF); break; case MODULENODE: setFlag(CLASS); break; case MULTIPLEASGN19NODE: MultipleAsgn19Node multipleAsgn19Node = (MultipleAsgn19Node)node; inspect(multipleAsgn19Node.getPre()); inspect(multipleAsgn19Node.getPost()); inspect(multipleAsgn19Node.getRest()); inspect(multipleAsgn19Node.getValueNode()); break; case MULTIPLEASGNNODE: MultipleAsgnNode multipleAsgnNode = (MultipleAsgnNode)node; inspect(multipleAsgnNode.getArgsNode()); inspect(multipleAsgnNode.getHeadNode()); inspect(multipleAsgnNode.getValueNode()); break; case NEWLINENODE: inspect(((NewlineNode)node).getNextNode()); break; case NEXTNODE: inspect(((NextNode)node).getValueNode()); break; case NILNODE: break; case NOTNODE: inspect(((NotNode)node).getConditionNode()); break; case NTHREFNODE: break; case OPASGNANDNODE: OpAsgnAndNode opAsgnAndNode = (OpAsgnAndNode)node; inspect(opAsgnAndNode.getFirstNode()); inspect(opAsgnAndNode.getSecondNode()); break; case OPASGNNODE: OpAsgnNode opAsgnNode = (OpAsgnNode)node; inspect(opAsgnNode.getReceiverNode()); inspect(opAsgnNode.getValueNode()); break; case OPASGNORNODE: switch (((OpAsgnOrNode)node).getFirstNode().nodeId) { case CLASSVARASGNNODE: case CLASSVARDECLNODE: case CONSTDECLNODE: case DASGNNODE: case GLOBALASGNNODE: case LOCALASGNNODE: case MULTIPLEASGNNODE: case OPASGNNODE: case OPELEMENTASGNNODE: case DVARNODE: case FALSENODE: case TRUENODE: case LOCALVARNODE: case INSTVARNODE: case BACKREFNODE: case SELFNODE: case VCALLNODE: case YIELDNODE: case GLOBALVARNODE: case CONSTNODE: case FCALLNODE: case CLASSVARNODE: // ok, we have fast paths inspect(((OpAsgnOrNode)node).getSecondNode()); break; default: // long, slow way causes disabling for defined disable(); } break; case OPELEMENTASGNNODE: OpElementAsgnNode opElementAsgnNode = (OpElementAsgnNode)node; setFlag(FRAME_SELF); inspect(opElementAsgnNode.getArgsNode()); inspect(opElementAsgnNode.getReceiverNode()); inspect(opElementAsgnNode.getValueNode()); break; case OPTARGNODE: inspect(((OptArgNode)node).getValue()); break; case ORNODE: OrNode orNode = (OrNode)node; inspect(orNode.getFirstNode()); inspect(orNode.getSecondNode()); break; case POSTEXENODE: PostExeNode postExeNode = (PostExeNode)node; setFlag(CLOSURE); setFlag(SCOPE_AWARE); inspect(postExeNode.getBodyNode()); inspect(postExeNode.getVarNode()); break; case PREEXENODE: PreExeNode preExeNode = (PreExeNode)node; setFlag(CLOSURE); setFlag(SCOPE_AWARE); inspect(preExeNode.getBodyNode()); inspect(preExeNode.getVarNode()); break; case REDONODE: break; case REGEXPNODE: break; case ROOTNODE: inspect(((RootNode)node).getBodyNode()); if (((RootNode)node).getBodyNode() instanceof BlockNode) { BlockNode blockNode = (BlockNode)((RootNode)node).getBodyNode(); if (blockNode.size() > 500) { // method has more than 500 lines; we'll need to split it // and therefore need to use a heap-based scope setFlag(SCOPE_AWARE); } } break; case RESCUEBODYNODE: disable(); break; case RESCUENODE: disable(); break; case RETRYNODE: disable(); break; case RETURNNODE: inspect(((ReturnNode)node).getValueNode()); break; case SCLASSNODE: setFlag(CLASS); break; case SCOPENODE: break; case SELFNODE: break; case SPLATNODE: inspect(((SplatNode)node).getValue()); break; case STARNODE: break; case STRNODE: break; case SUPERNODE: SuperNode superNode = (SuperNode)node; inspect(superNode.getArgsNode()); inspect(superNode.getIterNode()); break; case SVALUENODE: inspect(((SValueNode)node).getValue()); break; case SYMBOLNODE: break; case TOARYNODE: inspect(((ToAryNode)node).getValue()); break; case TRUENODE: break; case UNDEFNODE: setFlag(METHOD); break; case UNTILNODE: UntilNode untilNode = (UntilNode)node; ASTInspector untilInspector = subInspect( untilNode.getConditionNode(), untilNode.getBodyNode()); // a while node could receive non-local flow control from any of these: // * a closure within the loop // * an eval within the loop // * a block-arg-based proc called within the loop if (untilInspector.getFlag(CLOSURE) || untilInspector.getFlag(EVAL)) { untilNode.containsNonlocalFlow = true; // we set scope-aware to true to force heap-based locals setFlag(SCOPE_AWARE); } integrate(untilInspector); break; case VALIASNODE: break; case WHENNODE: inspect(((WhenNode)node).getBodyNode()); inspect(((WhenNode)node).getExpressionNodes()); inspect(((WhenNode)node).getNextCase()); break; case WHILENODE: WhileNode whileNode = (WhileNode)node; ASTInspector whileInspector = subInspect( whileNode.getConditionNode(), whileNode.getBodyNode()); // a while node could receive non-local flow control from any of these: // * a closure within the loop // * an eval within the loop // * a block-arg-based proc called within the loop if (whileInspector.getFlag(CLOSURE) || whileInspector.getFlag(EVAL) || getFlag(BLOCK_ARG)) { whileNode.containsNonlocalFlow = true; // we set scope-aware to true to force heap-based locals setFlag(SCOPE_AWARE); } integrate(whileInspector); break; case XSTRNODE: break; case YIELDNODE: inspect(((YieldNode)node).getArgsNode()); break; case ZARRAYNODE: break; case ZEROARGNODE: break; case ZSUPERNODE: setFlag(SCOPE_AWARE); setFlag(ZSUPER); inspect(((ZSuperNode)node).getIterNode()); break; default: // encountered a node we don't recognize, set everything to true to disable optz assert false : "All nodes should be accounted for in AST inspector: " + node; disable(); } }
public void inspect(Node node) { // TODO: This code effectively disables all inspection-based optimizations; none of them are 100% safe yet if (!ENABLED) disable(); if (node == null) return; switch (node.nodeId) { case ALIASNODE: setFlag(METHOD); break; case ANDNODE: AndNode andNode = (AndNode)node; inspect(andNode.getFirstNode()); inspect(andNode.getSecondNode()); break; case ARGSCATNODE: ArgsCatNode argsCatNode = (ArgsCatNode)node; inspect(argsCatNode.getFirstNode()); inspect(argsCatNode.getSecondNode()); break; case ARGSPUSHNODE: ArgsPushNode argsPushNode = (ArgsPushNode)node; inspect(argsPushNode.getFirstNode()); inspect(argsPushNode.getSecondNode()); break; case ARGUMENTNODE: break; case ARRAYNODE: case BLOCKNODE: case DREGEXPNODE: case DSTRNODE: case DSYMBOLNODE: case DXSTRNODE: case LISTNODE: ListNode listNode = (ListNode)node; for (int i = 0; i < listNode.size(); i++) { inspect(listNode.get(i)); } break; case ARGSNODE: ArgsNode argsNode = (ArgsNode)node; if (argsNode.getBlock() != null) setFlag(BLOCK_ARG); if (argsNode.getOptArgs() != null) { setFlag(OPT_ARGS); inspect(argsNode.getOptArgs()); } if (argsNode.getRestArg() == -2 || argsNode.getRestArg() >= 0) setFlag(REST_ARG); break; case ATTRASSIGNNODE: AttrAssignNode attrAssignNode = (AttrAssignNode)node; setFlag(FRAME_SELF); inspect(attrAssignNode.getArgsNode()); inspect(attrAssignNode.getReceiverNode()); break; case BACKREFNODE: setFlag(BACKREF); break; case BEGINNODE: inspect(((BeginNode)node).getBodyNode()); break; case BIGNUMNODE: break; case BINARYOPERATORNODE: BinaryOperatorNode binaryOperatorNode = (BinaryOperatorNode)node; inspect(binaryOperatorNode.getFirstNode()); inspect(binaryOperatorNode.getSecondNode()); break; case BLOCKARGNODE: break; case BLOCKPASSNODE: BlockPassNode blockPassNode = (BlockPassNode)node; inspect(blockPassNode.getArgsNode()); inspect(blockPassNode.getBodyNode()); break; case BREAKNODE: inspect(((BreakNode)node).getValueNode()); break; case CALLNODE: CallNode callNode = (CallNode)node; inspect(callNode.getReceiverNode()); // check for Proc.new, an especially magic method if (callNode.getName() == "new" && callNode.getReceiverNode() instanceof ConstNode && ((ConstNode)callNode.getReceiverNode()).getName() == "Proc") { // Proc.new needs the caller's block to instantiate a proc setFlag(FRAME_BLOCK); } case FCALLNODE: inspect(((IArgumentNode)node).getArgsNode()); inspect(((BlockAcceptingNode)node).getIterNode()); case VCALLNODE: INameNode nameNode = (INameNode)node; if (FRAME_AWARE_METHODS.contains(nameNode.getName())) { setFlag(FRAME_AWARE); if (nameNode.getName().indexOf("eval") != -1) { setFlag(EVAL); } } if (SCOPE_AWARE_METHODS.contains(nameNode.getName())) { setFlag(SCOPE_AWARE); } break; case CASENODE: CaseNode caseNode = (CaseNode)node; inspect(caseNode.getCaseNode()); inspect(caseNode.getFirstWhenNode()); break; case CLASSNODE: setFlag(CLASS); break; case CLASSVARNODE: setFlag(CLASS_VAR); break; case CONSTDECLNODE: inspect(((AssignableNode)node).getValueNode()); setFlag(CONSTANT); break; case CLASSVARASGNNODE: inspect(((AssignableNode)node).getValueNode()); setFlag(CLASS_VAR); break; case CLASSVARDECLNODE: inspect(((AssignableNode)node).getValueNode()); setFlag(CLASS_VAR); break; case COLON2NODE: inspect(((Colon2Node)node).getLeftNode()); break; case COLON3NODE: break; case CONSTNODE: setFlag(CONSTANT); break; case DEFNNODE: case DEFSNODE: setFlag(METHOD); setFlag(FRAME_VISIBILITY); break; case DEFINEDNODE: switch (((DefinedNode)node).getExpressionNode().nodeId) { case CLASSVARASGNNODE: case CLASSVARDECLNODE: case CONSTDECLNODE: case DASGNNODE: case GLOBALASGNNODE: case LOCALASGNNODE: case MULTIPLEASGNNODE: case OPASGNNODE: case OPELEMENTASGNNODE: case DVARNODE: case FALSENODE: case TRUENODE: case LOCALVARNODE: case INSTVARNODE: case BACKREFNODE: case SELFNODE: case VCALLNODE: case YIELDNODE: case GLOBALVARNODE: case CONSTNODE: case FCALLNODE: case CLASSVARNODE: // ok, we have fast paths inspect(((DefinedNode)node).getExpressionNode()); break; default: // long, slow way causes disabling disable(); } break; case DOTNODE: DotNode dotNode = (DotNode)node; inspect(dotNode.getBeginNode()); inspect(dotNode.getEndNode()); break; case DASGNNODE: inspect(((AssignableNode)node).getValueNode()); break; case DVARNODE: break; case ENSURENODE: disable(); break; case EVSTRNODE: inspect(((EvStrNode)node).getBody()); break; case FALSENODE: break; case FIXNUMNODE: break; case FLIPNODE: inspect(((FlipNode)node).getBeginNode()); inspect(((FlipNode)node).getEndNode()); break; case FLOATNODE: break; case FORNODE: setFlag(CLOSURE); setFlag(SCOPE_AWARE); inspect(((ForNode)node).getIterNode()); inspect(((ForNode)node).getBodyNode()); inspect(((ForNode)node).getVarNode()); break; case GLOBALASGNNODE: GlobalAsgnNode globalAsgnNode = (GlobalAsgnNode)node; if (globalAsgnNode.getName().equals("$_")) { setFlag(LASTLINE); } else if (globalAsgnNode.getName().equals("$~")) { setFlag(BACKREF); } inspect(globalAsgnNode.getValueNode()); break; case GLOBALVARNODE: if (((GlobalVarNode)node).getName().equals("$_")) { setFlag(LASTLINE); } else if (((GlobalVarNode)node).getName().equals("$~")) { setFlag(BACKREF); } break; case HASHNODE: HashNode hashNode = (HashNode)node; inspect(hashNode.getListNode()); break; case IFNODE: IfNode ifNode = (IfNode)node; inspect(ifNode.getCondition()); inspect(ifNode.getThenBody()); inspect(ifNode.getElseBody()); break; case INSTASGNNODE: inspect(((AssignableNode)node).getValueNode()); break; case INSTVARNODE: break; case ISCOPINGNODE: IScopingNode iscopingNode = (IScopingNode)node; inspect(iscopingNode.getCPath()); break; case ITERNODE: setFlag(CLOSURE); break; case LAMBDANODE: setFlag(CLOSURE); break; case LOCALASGNNODE: LocalAsgnNode localAsgnNode = (LocalAsgnNode)node; if (PRAGMAS.contains(localAsgnNode.getName())) { if (localAsgnNode.getName().equals("__NOFRAME__")) { noFrame = localAsgnNode.getValueNode() instanceof TrueNode; } break; } inspect(localAsgnNode.getValueNode()); break; case LOCALVARNODE: break; case MATCHNODE: inspect(((MatchNode)node).getRegexpNode()); setFlag(BACKREF); break; case MATCH2NODE: Match2Node match2Node = (Match2Node)node; inspect(match2Node.getReceiverNode()); inspect(match2Node.getValueNode()); setFlag(BACKREF); break; case MATCH3NODE: Match3Node match3Node = (Match3Node)node; inspect(match3Node.getReceiverNode()); inspect(match3Node.getValueNode()); setFlag(BACKREF); break; case MODULENODE: setFlag(CLASS); break; case MULTIPLEASGN19NODE: MultipleAsgn19Node multipleAsgn19Node = (MultipleAsgn19Node)node; inspect(multipleAsgn19Node.getPre()); inspect(multipleAsgn19Node.getPost()); inspect(multipleAsgn19Node.getRest()); inspect(multipleAsgn19Node.getValueNode()); break; case MULTIPLEASGNNODE: MultipleAsgnNode multipleAsgnNode = (MultipleAsgnNode)node; inspect(multipleAsgnNode.getArgsNode()); inspect(multipleAsgnNode.getHeadNode()); inspect(multipleAsgnNode.getValueNode()); break; case NEWLINENODE: inspect(((NewlineNode)node).getNextNode()); break; case NEXTNODE: inspect(((NextNode)node).getValueNode()); break; case NILNODE: break; case NOTNODE: inspect(((NotNode)node).getConditionNode()); break; case NTHREFNODE: break; case OPASGNANDNODE: OpAsgnAndNode opAsgnAndNode = (OpAsgnAndNode)node; inspect(opAsgnAndNode.getFirstNode()); inspect(opAsgnAndNode.getSecondNode()); break; case OPASGNNODE: OpAsgnNode opAsgnNode = (OpAsgnNode)node; inspect(opAsgnNode.getReceiverNode()); inspect(opAsgnNode.getValueNode()); break; case OPASGNORNODE: switch (((OpAsgnOrNode)node).getFirstNode().nodeId) { case CLASSVARASGNNODE: case CLASSVARDECLNODE: case CONSTDECLNODE: case DASGNNODE: case GLOBALASGNNODE: case LOCALASGNNODE: case MULTIPLEASGNNODE: case OPASGNNODE: case OPELEMENTASGNNODE: case DVARNODE: case FALSENODE: case TRUENODE: case LOCALVARNODE: case INSTVARNODE: case BACKREFNODE: case SELFNODE: case VCALLNODE: case YIELDNODE: case GLOBALVARNODE: case CONSTNODE: case FCALLNODE: case CLASSVARNODE: // ok, we have fast paths inspect(((OpAsgnOrNode)node).getSecondNode()); break; default: // long, slow way causes disabling for defined disable(); } break; case OPELEMENTASGNNODE: OpElementAsgnNode opElementAsgnNode = (OpElementAsgnNode)node; setFlag(FRAME_SELF); inspect(opElementAsgnNode.getArgsNode()); inspect(opElementAsgnNode.getReceiverNode()); inspect(opElementAsgnNode.getValueNode()); break; case OPTARGNODE: inspect(((OptArgNode)node).getValue()); break; case ORNODE: OrNode orNode = (OrNode)node; inspect(orNode.getFirstNode()); inspect(orNode.getSecondNode()); break; case POSTEXENODE: PostExeNode postExeNode = (PostExeNode)node; setFlag(CLOSURE); setFlag(SCOPE_AWARE); inspect(postExeNode.getBodyNode()); inspect(postExeNode.getVarNode()); break; case PREEXENODE: PreExeNode preExeNode = (PreExeNode)node; setFlag(CLOSURE); setFlag(SCOPE_AWARE); inspect(preExeNode.getBodyNode()); inspect(preExeNode.getVarNode()); break; case REDONODE: break; case REGEXPNODE: break; case ROOTNODE: inspect(((RootNode)node).getBodyNode()); if (((RootNode)node).getBodyNode() instanceof BlockNode) { BlockNode blockNode = (BlockNode)((RootNode)node).getBodyNode(); if (blockNode.size() > 500) { // method has more than 500 lines; we'll need to split it // and therefore need to use a heap-based scope setFlag(SCOPE_AWARE); } } break; case RESCUEBODYNODE: disable(); break; case RESCUENODE: disable(); break; case RETRYNODE: disable(); break; case RETURNNODE: inspect(((ReturnNode)node).getValueNode()); break; case SCLASSNODE: setFlag(CLASS); break; case SCOPENODE: break; case SELFNODE: break; case SPLATNODE: inspect(((SplatNode)node).getValue()); break; case STARNODE: break; case STRNODE: break; case SUPERNODE: SuperNode superNode = (SuperNode)node; inspect(superNode.getArgsNode()); inspect(superNode.getIterNode()); break; case SVALUENODE: inspect(((SValueNode)node).getValue()); break; case SYMBOLNODE: break; case TOARYNODE: inspect(((ToAryNode)node).getValue()); break; case TRUENODE: break; case UNDEFNODE: setFlag(METHOD); break; case UNTILNODE: UntilNode untilNode = (UntilNode)node; ASTInspector untilInspector = subInspect( untilNode.getConditionNode(), untilNode.getBodyNode()); // a while node could receive non-local flow control from any of these: // * a closure within the loop // * an eval within the loop // * a block-arg-based proc called within the loop if (untilInspector.getFlag(CLOSURE) || untilInspector.getFlag(EVAL)) { untilNode.containsNonlocalFlow = true; // we set scope-aware to true to force heap-based locals setFlag(SCOPE_AWARE); } integrate(untilInspector); break; case VALIASNODE: break; case WHENNODE: inspect(((WhenNode)node).getBodyNode()); inspect(((WhenNode)node).getExpressionNodes()); inspect(((WhenNode)node).getNextCase()); break; case WHILENODE: WhileNode whileNode = (WhileNode)node; ASTInspector whileInspector = subInspect( whileNode.getConditionNode(), whileNode.getBodyNode()); // a while node could receive non-local flow control from any of these: // * a closure within the loop // * an eval within the loop // * a block-arg-based proc called within the loop if (whileInspector.getFlag(CLOSURE) || whileInspector.getFlag(EVAL) || getFlag(BLOCK_ARG)) { whileNode.containsNonlocalFlow = true; // we set scope-aware to true to force heap-based locals setFlag(SCOPE_AWARE); } integrate(whileInspector); break; case XSTRNODE: break; case YIELDNODE: inspect(((YieldNode)node).getArgsNode()); break; case ZARRAYNODE: break; case ZEROARGNODE: break; case ZSUPERNODE: setFlag(SCOPE_AWARE); setFlag(ZSUPER); inspect(((ZSuperNode)node).getIterNode()); break; default: // encountered a node we don't recognize, set everything to true to disable optz assert false : "All nodes should be accounted for in AST inspector: " + node; disable(); } }
diff --git a/tools/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/ProjectResources.java b/tools/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/ProjectResources.java index 9052672d..dce26228 100644 --- a/tools/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/ProjectResources.java +++ b/tools/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/ProjectResources.java @@ -1,832 +1,832 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Eclipse 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/org/documents/epl-v10.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 com.android.ide.eclipse.adt.internal.resources.manager; import com.android.ide.eclipse.adt.internal.resources.IResourceRepository; import com.android.ide.eclipse.adt.internal.resources.ResourceItem; import com.android.ide.eclipse.adt.internal.resources.ResourceType; import com.android.ide.eclipse.adt.internal.resources.configurations.FolderConfiguration; import com.android.ide.eclipse.adt.internal.resources.configurations.LanguageQualifier; import com.android.ide.eclipse.adt.internal.resources.configurations.RegionQualifier; import com.android.ide.eclipse.adt.internal.resources.configurations.ResourceQualifier; import com.android.ide.eclipse.adt.internal.resources.manager.files.IAbstractFolder; import com.android.layoutlib.api.IResourceValue; import com.android.layoutlib.utils.ResourceValue; import org.eclipse.core.resources.IFolder; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; /** * Represents the resources of a project. This is a file view of the resources, with handling * for the alternate resource types. For a compiled view use CompiledResources. */ public class ProjectResources implements IResourceRepository { private final HashMap<ResourceFolderType, List<ResourceFolder>> mFolderMap = new HashMap<ResourceFolderType, List<ResourceFolder>>(); private final HashMap<ResourceType, List<ProjectResourceItem>> mResourceMap = new HashMap<ResourceType, List<ProjectResourceItem>>(); /** Map of (name, id) for resources of type {@link ResourceType#ID} coming from R.java */ private Map<String, Map<String, Integer>> mResourceValueMap; /** Map of (id, [name, resType]) for all resources coming from R.java */ private Map<Integer, String[]> mResIdValueToNameMap; /** Map of (int[], name) for styleable resources coming from R.java */ private Map<IntArrayWrapper, String> mStyleableValueToNameMap; /** Cached list of {@link IdResourceItem}. This is mix of IdResourceItem created by * {@link MultiResourceFile} for ids coming from XML files under res/values and * {@link IdResourceItem} created manually, from the list coming from R.java */ private final ArrayList<IdResourceItem> mIdResourceList = new ArrayList<IdResourceItem>(); private final boolean mIsFrameworkRepository; private final IntArrayWrapper mWrapper = new IntArrayWrapper(null); public ProjectResources(boolean isFrameworkRepository) { mIsFrameworkRepository = isFrameworkRepository; } public boolean isSystemRepository() { return mIsFrameworkRepository; } /** * Adds a Folder Configuration to the project. * @param type The resource type. * @param config The resource configuration. * @param folder The workspace folder object. * @return the {@link ResourceFolder} object associated to this folder. */ protected ResourceFolder add(ResourceFolderType type, FolderConfiguration config, IAbstractFolder folder) { // get the list for the resource type List<ResourceFolder> list = mFolderMap.get(type); if (list == null) { list = new ArrayList<ResourceFolder>(); ResourceFolder cf = new ResourceFolder(type, config, folder, mIsFrameworkRepository); list.add(cf); mFolderMap.put(type, list); return cf; } // look for an already existing folder configuration. for (ResourceFolder cFolder : list) { if (cFolder.mConfiguration.equals(config)) { // config already exist. Nothing to be done really, besides making sure // the IFolder object is up to date. cFolder.mFolder = folder; return cFolder; } } // If we arrive here, this means we didn't find a matching configuration. // So we add one. ResourceFolder cf = new ResourceFolder(type, config, folder, mIsFrameworkRepository); list.add(cf); return cf; } /** * Removes a {@link ResourceFolder} associated with the specified {@link IAbstractFolder}. * @param type The type of the folder * @param folder the IFolder object. */ protected void removeFolder(ResourceFolderType type, IFolder folder) { // get the list of folders for the resource type. List<ResourceFolder> list = mFolderMap.get(type); if (list != null) { int count = list.size(); for (int i = 0 ; i < count ; i++) { ResourceFolder resFolder = list.get(i); if (resFolder.getFolder().getIFolder().equals(folder)) { // we found the matching ResourceFolder. we need to remove it. list.remove(i); // we now need to invalidate this resource type. // The easiest way is to touch one of the other folders of the same type. if (list.size() > 0) { list.get(0).touch(); } else { // if the list is now empty, and we have a single ResouceType out of this // ResourceFolderType, then we are done. // However, if another ResourceFolderType can generate similar ResourceType // than this, we need to update those ResourceTypes as well. // For instance, if the last "drawable-*" folder is deleted, we need to // refresh the ResourceItem associated with ResourceType.DRAWABLE. // Those can be found in ResourceFolderType.DRAWABLE but also in // ResourceFolderType.VALUES. // If we don't find a single folder to touch, then it's fine, as the top // level items (the list of generated resource types) is not cached // (for now) // get the lists of ResourceTypes generated by this ResourceFolderType ResourceType[] resTypes = FolderTypeRelationship.getRelatedResourceTypes( type); // for each of those, make sure to find one folder to touch so that the // list of ResourceItem associated with the type is rebuilt. for (ResourceType resType : resTypes) { // get the list of folder that can generate this type ResourceFolderType[] folderTypes = FolderTypeRelationship.getRelatedFolders(resType); // we only need to touch one folder in any of those (since it's one // folder per type, not per folder type). for (ResourceFolderType folderType : folderTypes) { List<ResourceFolder> resFolders = mFolderMap.get(folderType); if (resFolders != null && resFolders.size() > 0) { resFolders.get(0).touch(); break; } } } } // we're done updating/touching, we can stop break; } } } } /** * Returns a list of {@link ResourceFolder} for a specific {@link ResourceFolderType}. * @param type The {@link ResourceFolderType} */ public List<ResourceFolder> getFolders(ResourceFolderType type) { return mFolderMap.get(type); } /* (non-Javadoc) * @see com.android.ide.eclipse.editors.resources.IResourceRepository#getAvailableResourceTypes() */ public ResourceType[] getAvailableResourceTypes() { ArrayList<ResourceType> list = new ArrayList<ResourceType>(); // For each key, we check if there's a single ResourceType match. // If not, we look for the actual content to give us the resource type. for (ResourceFolderType folderType : mFolderMap.keySet()) { ResourceType types[] = FolderTypeRelationship.getRelatedResourceTypes(folderType); if (types.length == 1) { // before we add it we check if it's not already present, since a ResourceType // could be created from multiple folders, even for the folders that only create // one type of resource (drawable for instance, can be created from drawable/ and // values/) if (list.indexOf(types[0]) == -1) { list.add(types[0]); } } else { // there isn't a single resource type out of this folder, so we look for all // content. List<ResourceFolder> folders = mFolderMap.get(folderType); if (folders != null) { for (ResourceFolder folder : folders) { Collection<ResourceType> folderContent = folder.getResourceTypes(); // then we add them, but only if they aren't already in the list. for (ResourceType folderResType : folderContent) { if (list.indexOf(folderResType) == -1) { list.add(folderResType); } } } } } } // in case ResourceType.ID haven't been added yet because there's no id defined // in XML, we check on the list of compiled id resources. if (list.indexOf(ResourceType.ID) == -1 && mResourceValueMap != null) { Map<String, Integer> map = mResourceValueMap.get(ResourceType.ID.getName()); if (map != null && map.size() > 0) { list.add(ResourceType.ID); } } // at this point the list is full of ResourceType defined in the files. // We need to sort it. Collections.sort(list); return list.toArray(new ResourceType[list.size()]); } /* (non-Javadoc) * @see com.android.ide.eclipse.editors.resources.IResourceRepository#getResources(com.android.ide.eclipse.common.resources.ResourceType) */ public ProjectResourceItem[] getResources(ResourceType type) { checkAndUpdate(type); if (type == ResourceType.ID) { synchronized (mIdResourceList) { return mIdResourceList.toArray(new ProjectResourceItem[mIdResourceList.size()]); } } List<ProjectResourceItem> items = mResourceMap.get(type); return items.toArray(new ProjectResourceItem[items.size()]); } /* (non-Javadoc) * @see com.android.ide.eclipse.editors.resources.IResourceRepository#hasResources(com.android.ide.eclipse.common.resources.ResourceType) */ public boolean hasResources(ResourceType type) { checkAndUpdate(type); if (type == ResourceType.ID) { synchronized (mIdResourceList) { return mIdResourceList.size() > 0; } } List<ProjectResourceItem> items = mResourceMap.get(type); return (items != null && items.size() > 0); } /** * Returns the {@link ResourceFolder} associated with a {@link IFolder}. * @param folder The {@link IFolder} object. * @return the {@link ResourceFolder} or null if it was not found. */ public ResourceFolder getResourceFolder(IFolder folder) { for (List<ResourceFolder> list : mFolderMap.values()) { for (ResourceFolder resFolder : list) { if (resFolder.getFolder().getIFolder().equals(folder)) { return resFolder; } } } return null; } /** * Returns the {@link ResourceFile} matching the given name, {@link ResourceFolderType} and * configuration. * <p/>This only works with files generating one resource named after the file (for instance, * layouts, bitmap based drawable, xml, anims). * @return the matching file or <code>null</code> if no match was found. */ public ResourceFile getMatchingFile(String name, ResourceFolderType type, FolderConfiguration config) { // get the folders for the given type List<ResourceFolder> folders = mFolderMap.get(type); // look for folders containing a file with the given name. ArrayList<ResourceFolder> matchingFolders = new ArrayList<ResourceFolder>(); // remove the folders that do not have a file with the given name, or if their config // is incompatible. for (int i = 0 ; i < folders.size(); i++) { ResourceFolder folder = folders.get(i); if (folder.hasFile(name) == true) { matchingFolders.add(folder); } } // from those, get the folder with a config matching the given reference configuration. Resource match = findMatchingConfiguredResource(matchingFolders, config); // do we have a matching folder? if (match instanceof ResourceFolder) { // get the ResourceFile from the filename return ((ResourceFolder)match).getFile(name); } return null; } /** * Returns the resources values matching a given {@link FolderConfiguration}. * @param referenceConfig the configuration that each value must match. */ public Map<String, Map<String, IResourceValue>> getConfiguredResources( FolderConfiguration referenceConfig) { Map<String, Map<String, IResourceValue>> map = new HashMap<String, Map<String, IResourceValue>>(); // special case for Id since there's a mix of compiled id (declared inline) and id declared // in the XML files. if (mIdResourceList.size() > 0) { Map<String, IResourceValue> idMap = new HashMap<String, IResourceValue>(); String idType = ResourceType.ID.getName(); for (IdResourceItem id : mIdResourceList) { // FIXME: cache the ResourceValue! idMap.put(id.getName(), new ResourceValue(idType, id.getName(), mIsFrameworkRepository)); } map.put(ResourceType.ID.getName(), idMap); } Set<ResourceType> keys = mResourceMap.keySet(); for (ResourceType key : keys) { // we don't process ID resources since we already did it above. if (key != ResourceType.ID) { map.put(key.getName(), getConfiguredResource(key, referenceConfig)); } } return map; } /** * Loads all the resources. Essentially this forces to load the values from the * {@link ResourceFile} objects to make sure they are up to date and loaded * in {@link #mResourceMap}. */ public void loadAll() { // gets all the resource types available. ResourceType[] types = getAvailableResourceTypes(); // loop on them and load them for (ResourceType type: types) { checkAndUpdate(type); } } /** * Resolves a compiled resource id into the resource name and type * @param id * @return an array of 2 strings { name, type } or null if the id could not be resolved */ public String[] resolveResourceValue(int id) { if (mResIdValueToNameMap != null) { return mResIdValueToNameMap.get(id); } return null; } /** * Resolves a compiled resource id of type int[] into the resource name. */ public String resolveResourceValue(int[] id) { if (mStyleableValueToNameMap != null) { mWrapper.set(id); return mStyleableValueToNameMap.get(mWrapper); } return null; } /** * Returns the value of a resource by its type and name. */ public Integer getResourceValue(String type, String name) { if (mResourceValueMap != null) { Map<String, Integer> map = mResourceValueMap.get(type); if (map != null) { return map.get(name); } } return null; } /** * Returns the sorted list of languages used in the resources. */ public SortedSet<String> getLanguages() { SortedSet<String> set = new TreeSet<String>(); Collection<List<ResourceFolder>> folderList = mFolderMap.values(); for (List<ResourceFolder> folderSubList : folderList) { for (ResourceFolder folder : folderSubList) { FolderConfiguration config = folder.getConfiguration(); LanguageQualifier lang = config.getLanguageQualifier(); if (lang != null) { set.add(lang.getStringValue()); } } } return set; } /** * Returns the sorted list of regions used in the resources with the given language. * @param currentLanguage the current language the region must be associated with. */ public SortedSet<String> getRegions(String currentLanguage) { SortedSet<String> set = new TreeSet<String>(); Collection<List<ResourceFolder>> folderList = mFolderMap.values(); for (List<ResourceFolder> folderSubList : folderList) { for (ResourceFolder folder : folderSubList) { FolderConfiguration config = folder.getConfiguration(); // get the language LanguageQualifier lang = config.getLanguageQualifier(); if (lang != null && lang.getStringValue().equals(currentLanguage)) { RegionQualifier region = config.getRegionQualifier(); if (region != null) { set.add(region.getStringValue()); } } } } return set; } /** * Returns a map of (resource name, resource value) for the given {@link ResourceType}. * <p/>The values returned are taken from the resource files best matching a given * {@link FolderConfiguration}. * @param type the type of the resources. * @param referenceConfig the configuration to best match. */ private Map<String, IResourceValue> getConfiguredResource(ResourceType type, FolderConfiguration referenceConfig) { // get the resource item for the given type List<ProjectResourceItem> items = mResourceMap.get(type); // create the map HashMap<String, IResourceValue> map = new HashMap<String, IResourceValue>(); for (ProjectResourceItem item : items) { // get the source files generating this resource List<ResourceFile> list = item.getSourceFileList(); // look for the best match for the given configuration Resource match = findMatchingConfiguredResource(list, referenceConfig); if (match instanceof ResourceFile) { ResourceFile matchResFile = (ResourceFile)match; // get the value of this configured resource. IResourceValue value = matchResFile.getValue(type, item.getName()); if (value != null) { map.put(item.getName(), value); } } } return map; } /** * Returns the best matching {@link Resource}. * @param resources the list of {@link Resource} to choose from. * @param referenceConfig the {@link FolderConfiguration} to match. * @see http://d.android.com/guide/topics/resources/resources-i18n.html#best-match */ private Resource findMatchingConfiguredResource(List<? extends Resource> resources, FolderConfiguration referenceConfig) { // // 1: eliminate resources that contradict the reference configuration // 2: pick next qualifier type // 3: check if any resources use this qualifier, if no, back to 2, else move on to 4. // 4: eliminate resources that don't use this qualifier. // 5: if more than one resource left, go back to 2. // // The precedence of the qualifiers is more important than the number of qualifiers that // exactly match the device. // 1: eliminate resources that contradict ArrayList<Resource> matchingResources = new ArrayList<Resource>(); for (int i = 0 ; i < resources.size(); i++) { Resource res = resources.get(i); if (res.getConfiguration().isMatchFor(referenceConfig)) { matchingResources.add(res); } } // if there is only one match, just take it if (matchingResources.size() == 1) { return matchingResources.get(0); } else if (matchingResources.size() == 0) { return null; } // 2. Loop on the qualifiers, and eliminate matches final int count = FolderConfiguration.getQualifierCount(); for (int q = 0 ; q < count ; q++) { // look to see if one resource has this qualifier. // At the same time also record the best match value for the qualifier (if applicable). // The reference value, to find the best match. // Note that this qualifier could be null. In which case any qualifier found in the // possible match, will all be considered best match. ResourceQualifier referenceQualifier = referenceConfig.getQualifier(q); boolean found = false; ResourceQualifier bestMatch = null; // this is to store the best match. for (Resource res : matchingResources) { ResourceQualifier qualifier = res.getConfiguration().getQualifier(q); if (qualifier != null) { // set the flag. found = true; // Now check for a best match. If the reference qualifier is null , // any qualifier is a "best" match (we don't need to record all of them. // Instead the non compatible ones are removed below) if (referenceQualifier != null) { if (qualifier.isBetterMatchThan(bestMatch, referenceQualifier)) { bestMatch = qualifier; } } } } // 4. If a resources has a qualifier at the current index, remove all the resources that // do not have one, or whose qualifier value does not equal the best match found above // unless there's no reference qualifier, in which case they are all considered // "best" match. if (found) { for (int i = 0 ; i < matchingResources.size(); ) { Resource res = matchingResources.get(i); ResourceQualifier qualifier = res.getConfiguration().getQualifier(q); if (qualifier == null) { // this resources has no qualifier of this type: rejected. matchingResources.remove(res); } else if (referenceQualifier != null && bestMatch != null && bestMatch.equals(qualifier) == false) { // there's a reference qualifier and there is a better match for it than // this resource, so we reject it. matchingResources.remove(res); } else { // looks like we keep this resource, move on to the next one. i++; } } // at this point we may have run out of matching resources before going // through all the qualifiers. if (matchingResources.size() < 2) { break; } } } // Because we accept resources whose configuration have qualifiers where the reference // configuration doesn't, we can end up with more than one match. In this case, we just // take the first one. if (matchingResources.size() == 0) { return null; } - return matchingResources.get(1); + return matchingResources.get(0); } /** * Checks if the list of {@link ResourceItem}s for the specified {@link ResourceType} needs * to be updated. * @param type the Resource Type. */ private void checkAndUpdate(ResourceType type) { // get the list of folder that can output this type ResourceFolderType[] folderTypes = FolderTypeRelationship.getRelatedFolders(type); for (ResourceFolderType folderType : folderTypes) { List<ResourceFolder> folders = mFolderMap.get(folderType); if (folders != null) { for (ResourceFolder folder : folders) { if (folder.isTouched()) { // if this folder is touched we need to update all the types that can // be generated from a file in this folder. // This will include 'type' obviously. ResourceType[] resTypes = FolderTypeRelationship.getRelatedResourceTypes( folderType); for (ResourceType resType : resTypes) { update(resType); } return; } } } } } /** * Updates the list of {@link ResourceItem} objects associated with a {@link ResourceType}. * This will reset the touch status of all the folders that can generate this resource type. * @param type the Resource Type. */ private void update(ResourceType type) { // get the cache list, and lets make a backup List<ProjectResourceItem> items = mResourceMap.get(type); List<ProjectResourceItem> backup = new ArrayList<ProjectResourceItem>(); if (items == null) { items = new ArrayList<ProjectResourceItem>(); mResourceMap.put(type, items); } else { // backup the list backup.addAll(items); // we reset the list itself. items.clear(); } // get the list of folder that can output this type ResourceFolderType[] folderTypes = FolderTypeRelationship.getRelatedFolders(type); for (ResourceFolderType folderType : folderTypes) { List<ResourceFolder> folders = mFolderMap.get(folderType); if (folders != null) { for (ResourceFolder folder : folders) { items.addAll(folder.getResources(type, this)); folder.resetTouch(); } } } // now items contains the new list. We "merge" it with the backup list. // Basically, we need to keep the old instances of ResourceItem (where applicable), // but replace them by the content of the new items. // This will let the resource explorer keep the expanded state of the nodes whose data // is a ResourceItem object. if (backup.size() > 0) { // this is not going to change as we're only replacing instances. int count = items.size(); for (int i = 0 ; i < count;) { // get the "new" item ProjectResourceItem item = items.get(i); // look for a similar item in the old list. ProjectResourceItem foundOldItem = null; for (ProjectResourceItem oldItem : backup) { if (oldItem.getName().equals(item.getName())) { foundOldItem = oldItem; break; } } if (foundOldItem != null) { // erase the data of the old item with the data from the new one. foundOldItem.replaceWith(item); // remove the old and new item from their respective lists items.remove(i); backup.remove(foundOldItem); // add the old item to the new list items.add(foundOldItem); } else { // this is a new item, we skip to the next object i++; } } } // if this is the ResourceType.ID, we create the actual list, from this list and // the compiled resource list. if (type == ResourceType.ID) { mergeIdResources(); } else { // else this is the list that will actually be displayed, so we sort it. Collections.sort(items); } } /** * Looks up an existing {@link ProjectResourceItem} by {@link ResourceType} and name. * @param type the Resource Type. * @param name the Resource name. * @return the existing ResourceItem or null if no match was found. */ protected ProjectResourceItem findResourceItem(ResourceType type, String name) { List<ProjectResourceItem> list = mResourceMap.get(type); for (ProjectResourceItem item : list) { if (name.equals(item.getName())) { return item; } } return null; } /** * Sets compiled resource information. * @param resIdValueToNameMap a map of compiled resource id to resource name. * The map is acquired by the {@link ProjectResources} object. * @param styleableValueMap * @param resourceValueMap a map of (name, id) for resources of type {@link ResourceType#ID}. * The list is acquired by the {@link ProjectResources} object. */ void setCompiledResources(Map<Integer, String[]> resIdValueToNameMap, Map<IntArrayWrapper, String> styleableValueMap, Map<String, Map<String, Integer>> resourceValueMap) { mResourceValueMap = resourceValueMap; mResIdValueToNameMap = resIdValueToNameMap; mStyleableValueToNameMap = styleableValueMap; mergeIdResources(); } /** * Merges the list of ID resource coming from R.java and the list of ID resources * coming from XML declaration into the cached list {@link #mIdResourceList}. */ void mergeIdResources() { // get the list of IDs coming from XML declaration. Those ids are present in // mCompiledIdResources already, so we'll need to use those instead of creating // new IdResourceItem List<ProjectResourceItem> xmlIdResources = mResourceMap.get(ResourceType.ID); synchronized (mIdResourceList) { // copy the currently cached items. ArrayList<IdResourceItem> oldItems = new ArrayList<IdResourceItem>(); oldItems.addAll(mIdResourceList); // empty the current list mIdResourceList.clear(); // get the list of compile id resources. Map<String, Integer> idMap = null; if (mResourceValueMap != null) { idMap = mResourceValueMap.get(ResourceType.ID.getName()); } if (idMap == null) { if (xmlIdResources != null) { for (ProjectResourceItem resourceItem : xmlIdResources) { // check the actual class just for safety. if (resourceItem instanceof IdResourceItem) { mIdResourceList.add((IdResourceItem)resourceItem); } } } } else { // loop on the full list of id, and look for a match in the old list, // in the list coming from XML (in case a new XML item was created.) Set<String> idSet = idMap.keySet(); idLoop: for (String idResource : idSet) { // first look in the XML list in case an id went from inline to XML declared. if (xmlIdResources != null) { for (ProjectResourceItem resourceItem : xmlIdResources) { if (resourceItem instanceof IdResourceItem && resourceItem.getName().equals(idResource)) { mIdResourceList.add((IdResourceItem)resourceItem); continue idLoop; } } } // if we haven't found it, look in the old items. int count = oldItems.size(); for (int i = 0 ; i < count ; i++) { IdResourceItem resourceItem = oldItems.get(i); if (resourceItem.getName().equals(idResource)) { oldItems.remove(i); mIdResourceList.add(resourceItem); continue idLoop; } } // if we haven't found it, it looks like it's a new id that was // declared inline. mIdResourceList.add(new IdResourceItem(idResource, true /* isDeclaredInline */)); } } // now we sort the list Collections.sort(mIdResourceList); } } }
true
true
private Resource findMatchingConfiguredResource(List<? extends Resource> resources, FolderConfiguration referenceConfig) { // // 1: eliminate resources that contradict the reference configuration // 2: pick next qualifier type // 3: check if any resources use this qualifier, if no, back to 2, else move on to 4. // 4: eliminate resources that don't use this qualifier. // 5: if more than one resource left, go back to 2. // // The precedence of the qualifiers is more important than the number of qualifiers that // exactly match the device. // 1: eliminate resources that contradict ArrayList<Resource> matchingResources = new ArrayList<Resource>(); for (int i = 0 ; i < resources.size(); i++) { Resource res = resources.get(i); if (res.getConfiguration().isMatchFor(referenceConfig)) { matchingResources.add(res); } } // if there is only one match, just take it if (matchingResources.size() == 1) { return matchingResources.get(0); } else if (matchingResources.size() == 0) { return null; } // 2. Loop on the qualifiers, and eliminate matches final int count = FolderConfiguration.getQualifierCount(); for (int q = 0 ; q < count ; q++) { // look to see if one resource has this qualifier. // At the same time also record the best match value for the qualifier (if applicable). // The reference value, to find the best match. // Note that this qualifier could be null. In which case any qualifier found in the // possible match, will all be considered best match. ResourceQualifier referenceQualifier = referenceConfig.getQualifier(q); boolean found = false; ResourceQualifier bestMatch = null; // this is to store the best match. for (Resource res : matchingResources) { ResourceQualifier qualifier = res.getConfiguration().getQualifier(q); if (qualifier != null) { // set the flag. found = true; // Now check for a best match. If the reference qualifier is null , // any qualifier is a "best" match (we don't need to record all of them. // Instead the non compatible ones are removed below) if (referenceQualifier != null) { if (qualifier.isBetterMatchThan(bestMatch, referenceQualifier)) { bestMatch = qualifier; } } } } // 4. If a resources has a qualifier at the current index, remove all the resources that // do not have one, or whose qualifier value does not equal the best match found above // unless there's no reference qualifier, in which case they are all considered // "best" match. if (found) { for (int i = 0 ; i < matchingResources.size(); ) { Resource res = matchingResources.get(i); ResourceQualifier qualifier = res.getConfiguration().getQualifier(q); if (qualifier == null) { // this resources has no qualifier of this type: rejected. matchingResources.remove(res); } else if (referenceQualifier != null && bestMatch != null && bestMatch.equals(qualifier) == false) { // there's a reference qualifier and there is a better match for it than // this resource, so we reject it. matchingResources.remove(res); } else { // looks like we keep this resource, move on to the next one. i++; } } // at this point we may have run out of matching resources before going // through all the qualifiers. if (matchingResources.size() < 2) { break; } } } // Because we accept resources whose configuration have qualifiers where the reference // configuration doesn't, we can end up with more than one match. In this case, we just // take the first one. if (matchingResources.size() == 0) { return null; } return matchingResources.get(1); }
private Resource findMatchingConfiguredResource(List<? extends Resource> resources, FolderConfiguration referenceConfig) { // // 1: eliminate resources that contradict the reference configuration // 2: pick next qualifier type // 3: check if any resources use this qualifier, if no, back to 2, else move on to 4. // 4: eliminate resources that don't use this qualifier. // 5: if more than one resource left, go back to 2. // // The precedence of the qualifiers is more important than the number of qualifiers that // exactly match the device. // 1: eliminate resources that contradict ArrayList<Resource> matchingResources = new ArrayList<Resource>(); for (int i = 0 ; i < resources.size(); i++) { Resource res = resources.get(i); if (res.getConfiguration().isMatchFor(referenceConfig)) { matchingResources.add(res); } } // if there is only one match, just take it if (matchingResources.size() == 1) { return matchingResources.get(0); } else if (matchingResources.size() == 0) { return null; } // 2. Loop on the qualifiers, and eliminate matches final int count = FolderConfiguration.getQualifierCount(); for (int q = 0 ; q < count ; q++) { // look to see if one resource has this qualifier. // At the same time also record the best match value for the qualifier (if applicable). // The reference value, to find the best match. // Note that this qualifier could be null. In which case any qualifier found in the // possible match, will all be considered best match. ResourceQualifier referenceQualifier = referenceConfig.getQualifier(q); boolean found = false; ResourceQualifier bestMatch = null; // this is to store the best match. for (Resource res : matchingResources) { ResourceQualifier qualifier = res.getConfiguration().getQualifier(q); if (qualifier != null) { // set the flag. found = true; // Now check for a best match. If the reference qualifier is null , // any qualifier is a "best" match (we don't need to record all of them. // Instead the non compatible ones are removed below) if (referenceQualifier != null) { if (qualifier.isBetterMatchThan(bestMatch, referenceQualifier)) { bestMatch = qualifier; } } } } // 4. If a resources has a qualifier at the current index, remove all the resources that // do not have one, or whose qualifier value does not equal the best match found above // unless there's no reference qualifier, in which case they are all considered // "best" match. if (found) { for (int i = 0 ; i < matchingResources.size(); ) { Resource res = matchingResources.get(i); ResourceQualifier qualifier = res.getConfiguration().getQualifier(q); if (qualifier == null) { // this resources has no qualifier of this type: rejected. matchingResources.remove(res); } else if (referenceQualifier != null && bestMatch != null && bestMatch.equals(qualifier) == false) { // there's a reference qualifier and there is a better match for it than // this resource, so we reject it. matchingResources.remove(res); } else { // looks like we keep this resource, move on to the next one. i++; } } // at this point we may have run out of matching resources before going // through all the qualifiers. if (matchingResources.size() < 2) { break; } } } // Because we accept resources whose configuration have qualifiers where the reference // configuration doesn't, we can end up with more than one match. In this case, we just // take the first one. if (matchingResources.size() == 0) { return null; } return matchingResources.get(0); }
diff --git a/unifi-litas-esis-parent/unifi-litas-esis-pain-client/src/main/java/lt/itdbaltics/unifi/gateway/pain/CustomerCreditTransferBuilder.java b/unifi-litas-esis-parent/unifi-litas-esis-pain-client/src/main/java/lt/itdbaltics/unifi/gateway/pain/CustomerCreditTransferBuilder.java index 4b6f8c2..4bc6393 100644 --- a/unifi-litas-esis-parent/unifi-litas-esis-pain-client/src/main/java/lt/itdbaltics/unifi/gateway/pain/CustomerCreditTransferBuilder.java +++ b/unifi-litas-esis-parent/unifi-litas-esis-pain-client/src/main/java/lt/itdbaltics/unifi/gateway/pain/CustomerCreditTransferBuilder.java @@ -1,389 +1,389 @@ package lt.itdbaltics.unifi.gateway.pain; import iso.std.iso._20022.tech.xsd.pain_001_001.AccountIdentification4Choice; import iso.std.iso._20022.tech.xsd.pain_001_001.ActiveOrHistoricCurrencyAndAmount; import iso.std.iso._20022.tech.xsd.pain_001_001.AmountType3Choice; import iso.std.iso._20022.tech.xsd.pain_001_001.BranchAndFinancialInstitutionIdentification4; import iso.std.iso._20022.tech.xsd.pain_001_001.CashAccount16; import iso.std.iso._20022.tech.xsd.pain_001_001.CreditTransferTransactionInformation10; import iso.std.iso._20022.tech.xsd.pain_001_001.CustomerCreditTransferInitiationV03; import iso.std.iso._20022.tech.xsd.pain_001_001.FinancialInstitutionIdentification7; import iso.std.iso._20022.tech.xsd.pain_001_001.GenericOrganisationIdentification1; import iso.std.iso._20022.tech.xsd.pain_001_001.GenericPersonIdentification1; import iso.std.iso._20022.tech.xsd.pain_001_001.GroupHeader32; import iso.std.iso._20022.tech.xsd.pain_001_001.OrganisationIdentification4; import iso.std.iso._20022.tech.xsd.pain_001_001.OrganisationIdentificationSchemeName1Choice; import iso.std.iso._20022.tech.xsd.pain_001_001.Party6Choice; import iso.std.iso._20022.tech.xsd.pain_001_001.PartyIdentification32; import iso.std.iso._20022.tech.xsd.pain_001_001.PaymentIdentification1; import iso.std.iso._20022.tech.xsd.pain_001_001.PaymentInstructionInformation3; import iso.std.iso._20022.tech.xsd.pain_001_001.PaymentMethod3Code; import iso.std.iso._20022.tech.xsd.pain_001_001.PaymentTypeInformation19; import iso.std.iso._20022.tech.xsd.pain_001_001.PersonIdentification5; import iso.std.iso._20022.tech.xsd.pain_001_001.PersonIdentificationSchemeName1Choice; import iso.std.iso._20022.tech.xsd.pain_001_001.Purpose2Choice; import iso.std.iso._20022.tech.xsd.pain_001_001.RemittanceInformation5; import iso.std.iso._20022.tech.xsd.pain_001_001.ServiceLevel8Choice; import java.math.BigDecimal; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.List; import java.util.UUID; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import lt.lba.xmlns._2011._11.unifi.customercredittransferinitiation.v03.SignableDocumentType; /** * * Build <code>SignableDocument</code> JAXB type * out of the provided list of LITAS-ESIS v1.2 Mokesis payments. * * XAdES Signature part of the <code>SignableDocument</code> is not supported. * Only <code>CustomerCreditTransferInitiationV03</code> part (Document) is support currently. * * Each payment in the <code>List</code> corresponds to the * <code>PaymentInformation</code> item in the resulting JAXB graph. * * @author vgoldin * */ public class CustomerCreditTransferBuilder { private static final String SVCLVL_CODE_URGENT = "URGP"; private static final String SVCLVL_CODE_NONURGENT = "NURG"; private static final String PERSON_ID_CODE_CUST = "CUST"; private static final String ULTIMATE_PARTY_ID_CODE_IBAN = "IBAN"; private static final String ESIS_DATE_FORMAT = "yyyyMMdd"; public static SignableDocumentType convertToSignableDocumentType(List<LitasPaymentDto> rows) { if (rows == null || rows.size() < 1) { throw new IllegalArgumentException("List of LITAS-ESIS payments should be provided with at least one payment in the list."); } XMLGregorianCalendar createDate = createXMLGregorianCalendar(new Date()); GroupHeader32 header = new GroupHeader32(); header.setMsgId(UUID.randomUUID().toString().replaceAll("-", "")); header.setCreDtTm(createDate); header.setNbOfTxs(Integer.toString(rows.size())); CustomerCreditTransferInitiationV03 credit = new CustomerCreditTransferInitiationV03(); credit.setGrpHdr(header); Iterator<LitasPaymentDto> it = rows.iterator(); while (it.hasNext()) { LitasPaymentDto row = it.next(); PaymentTypeInformation19 type = new PaymentTypeInformation19(); ServiceLevel8Choice svcLvl = new ServiceLevel8Choice(); int priority = Integer.valueOf(row.getPriority()); if (priority == 1) { svcLvl.setCd(SVCLVL_CODE_NONURGENT); } else if (priority == 2) { svcLvl.setCd(SVCLVL_CODE_URGENT); } type.setSvcLvl(svcLvl); // -- create new transfer payment instruction PaymentInstructionInformation3 instr = new PaymentInstructionInformation3(); instr.setPmtInfId(UUID.randomUUID().toString().replaceAll("-", "")); instr.setPmtMtd(PaymentMethod3Code.TRF); instr.setPmtTpInf(type); // -- set requested execution date String reqdExctnDtStr = row.getValueDate(); if (hasValue(reqdExctnDtStr)) { instr.setReqdExctnDt(getReqdExctnDt(reqdExctnDtStr)); } // -- set debtor account AccountIdentification4Choice dbtrAcctIdIBAN = new AccountIdentification4Choice(); dbtrAcctIdIBAN.setIBAN(row.getPayerAccount()); CashAccount16 dbtrAcct = new CashAccount16(); dbtrAcct.setId(dbtrAcctIdIBAN); instr.setDbtrAcct(dbtrAcct); // -- set debtor PartyIdentification32 dbtr = createParty(row.getPayerName(), row.getPayerId(), row.getCustomerCodeInBeneficiaryIs(), PERSON_ID_CODE_CUST); instr.setDbtr(dbtr); // -- set debtor agent String dbtrAgtFinInstnIdBICStr = row.getPayerCreditInstitution(); if (hasValue(dbtrAgtFinInstnIdBICStr)) { instr.setDbtrAgt(getFinInstnId(dbtrAgtFinInstnIdBICStr)); } // -- set ultimate debtor PartyIdentification32 ultmtDbtr = createParty(row.getOriginatorName(), row.getOriginatorId(), row.getOriginatorAccount(), ULTIMATE_PARTY_ID_CODE_IBAN); if (ultmtDbtr != null) { instr.setUltmtDbtr(ultmtDbtr); } // -- set creditor account AccountIdentification4Choice cdtrAcctIdIBAN = new AccountIdentification4Choice(); cdtrAcctIdIBAN.setIBAN(row.getBeneficiaryAccount()); CreditTransferTransactionInformation10 cdtTrfTxInf = new CreditTransferTransactionInformation10(); // -- set credit transfer number String cdtTrfTxInfPmtIdStr = row.getDocumentNumber(); PaymentIdentification1 pmtId = new PaymentIdentification1(); pmtId.setInstrId(cdtTrfTxInfPmtIdStr); pmtId.setEndToEndId(cdtTrfTxInfPmtIdStr); cdtTrfTxInf.setPmtId(pmtId); // -- set creditor PartyIdentification32 cdtr = createParty(row.getBenificiaryName(), row.getBenificiaryId(), row.getCustomerCodeInPayerIs(), PERSON_ID_CODE_CUST); cdtTrfTxInf.setCdtr(cdtr); // -- set creditor agent String cdtrAgtFinInstnIdBICStr = row.getBenificiaryCreditInsitution(); if (hasValue(cdtrAgtFinInstnIdBICStr)) { cdtTrfTxInf.setCdtrAgt(getFinInstnId(cdtrAgtFinInstnIdBICStr)); } // -- set ultimate creditor - PartyIdentification32 ultmtCdtr = createParty(row.getBenificiaryName(), row.getBenificiaryPartyId(), + PartyIdentification32 ultmtCdtr = createParty(row.getBenificiaryPartyName(), row.getBenificiaryPartyId(), row.getBeneficiaryPartyAccount(), ULTIMATE_PARTY_ID_CODE_IBAN); if (ultmtCdtr != null) { cdtTrfTxInf.setUltmtCdtr(ultmtCdtr); } // -- set amount AmountType3Choice amt = createAmount(row.getAmount(), row.getCurrencyCode()); cdtTrfTxInf.setAmt(amt); // -- set purpose code (purpose is not the same as remittance! // Remittance is to identify particular instruction relation to the // particular invoice, whenever purpose is a static value, defining // the category of the payment) String purpPrtryStr = row.getReferenceNo(); if (hasValue(purpPrtryStr)) { Purpose2Choice purp = new Purpose2Choice(); purp.setPrtry(purpPrtryStr); cdtTrfTxInf.setPurp(purp); } // -- set unstructured remittance information RemittanceInformation5 rmtInf = createRmtInf(row.getPaymentDetails()); cdtTrfTxInf.setRmtInf(rmtInf); // -- add credit transfer transaction information (credit part) to // the instruction instr.getCdtTrfTxInf().add(cdtTrfTxInf); // -- add instruction to the list of instructions in the current // document credit.getPmtInf().add(instr); } iso.std.iso._20022.tech.xsd.pain_001_001.Document document = new iso.std.iso._20022.tech.xsd.pain_001_001.Document(); document.setCstmrCdtTrfInitn(credit); SignableDocumentType signableType = new SignableDocumentType(); signableType.setDocument(document); return signableType; } private static XMLGregorianCalendar createXMLGregorianCalendar(Date currentDateTime) { GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(currentDateTime); XMLGregorianCalendar createDate; try { createDate = DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar); } catch (DatatypeConfigurationException e) { throw new RuntimeException(e); } return createDate; } private static RemittanceInformation5 createRmtInf(String string) { RemittanceInformation5 rmtInf = new RemittanceInformation5(); // -- maximum allowed length is 300, splitting the string into chunks of // 140 each if (string.length() > 140) { String s1 = string.substring(0, 140); rmtInf.getUstrd().add(s1); String s2 = string.substring(140); rmtInf.getUstrd().add(s2.substring(0, 140)); if (s2.length() > 140) { String s3 = s2.substring(140); if (s3.length() > 140) { s3 = s3.substring(0, 140); } rmtInf.getUstrd().add(s3); } } else { rmtInf.getUstrd().add(string); } return rmtInf; } private static AmountType3Choice createAmount(String instdAmtStr, String instdAmtCcy) { String d = instdAmtStr.substring(0, instdAmtStr.length() - 2) + "." + instdAmtStr.substring(instdAmtStr.length() - 2); BigDecimal amount = BigDecimal.valueOf(Double.valueOf(d)); AmountType3Choice amt = new AmountType3Choice(); ActiveOrHistoricCurrencyAndAmount instdAmt = new ActiveOrHistoricCurrencyAndAmount(); instdAmt.setValue(amount); instdAmt.setCcy(instdAmtCcy); amt.setInstdAmt(instdAmt); return amt; } private static PartyIdentification32 createParty(String partyNm, String partyMainId, String partyAdditionalId, String partyAdditionalIdCode) { PartyIdentification32 party = null; if (hasValue(partyNm) || hasValue(partyMainId) || hasValue(partyAdditionalId)) { party = new PartyIdentification32(); if (hasValue(partyNm)) { party.setNm(partyNm); } Party6Choice partyId = createPartyId(partyMainId, partyAdditionalId, partyAdditionalIdCode); if (partyId != null) { party.setId(partyId); } } return party; } private static BranchAndFinancialInstitutionIdentification4 getFinInstnId(String finInstnIdBICStr) { BranchAndFinancialInstitutionIdentification4 finInstn = new BranchAndFinancialInstitutionIdentification4(); FinancialInstitutionIdentification7 finInstnIdBIC = new FinancialInstitutionIdentification7(); finInstnIdBIC.setBIC(finInstnIdBICStr); finInstn.setFinInstnId(finInstnIdBIC); return finInstn; } private static Party6Choice createPartyId(String partyIdOtherIdStr, String partyIdOtherIdAdditionalStr, String additionalSchmeNmCodeCdStr) { Party6Choice partyIdOtherId = null; if (hasValue(partyIdOtherIdStr) || hasValue(partyIdOtherIdAdditionalStr)) { partyIdOtherId = new Party6Choice(); if (hasValue(partyIdOtherIdStr) && partyIdOtherIdStr.length() == 11) { PersonIdentification5 prvtId = new PersonIdentification5(); GenericPersonIdentification1 otherId = new GenericPersonIdentification1(); otherId.setId(partyIdOtherIdStr); prvtId.getOthr().add(otherId); if (hasValue(partyIdOtherIdAdditionalStr)) { GenericPersonIdentification1 otherCustId = getPersonAdditionalId(partyIdOtherIdAdditionalStr, additionalSchmeNmCodeCdStr); prvtId.getOthr().add(otherCustId); } partyIdOtherId.setPrvtId(prvtId); } else { OrganisationIdentification4 orgId = new OrganisationIdentification4(); if (hasValue(partyIdOtherIdStr)) { GenericOrganisationIdentification1 otherId = new GenericOrganisationIdentification1(); otherId.setId(partyIdOtherIdStr); orgId.getOthr().add(otherId); } if (hasValue(partyIdOtherIdAdditionalStr)) { GenericOrganisationIdentification1 otherCustId = getOrganisationCustId(partyIdOtherIdAdditionalStr, additionalSchmeNmCodeCdStr); orgId.getOthr().add(otherCustId); } partyIdOtherId.setOrgId(orgId); } } return partyIdOtherId; } private static boolean hasValue(String str) { return str != null && !str.isEmpty(); } private static GenericOrganisationIdentification1 getOrganisationCustId(String partyIdOtherIdCustStr, String schmeNmCodeCdStr) { GenericOrganisationIdentification1 otherCustId = new GenericOrganisationIdentification1(); otherCustId.setId(partyIdOtherIdCustStr); OrganisationIdentificationSchemeName1Choice schmeNmCodeCd = new OrganisationIdentificationSchemeName1Choice(); if (!isProprietaryCode(schmeNmCodeCdStr)) { schmeNmCodeCd.setCd(schmeNmCodeCdStr); } else { schmeNmCodeCd.setPrtry(schmeNmCodeCdStr); } otherCustId.setSchmeNm(schmeNmCodeCd); return otherCustId; } private static GenericPersonIdentification1 getPersonAdditionalId(String otherIdAdditionalStr, String schmeNmCodeCdStr) { GenericPersonIdentification1 otherAdditionalId = new GenericPersonIdentification1(); otherAdditionalId.setId(otherIdAdditionalStr); PersonIdentificationSchemeName1Choice schmeNmCodeCd = new PersonIdentificationSchemeName1Choice(); if (!isProprietaryCode(schmeNmCodeCdStr)) { schmeNmCodeCd.setCd(schmeNmCodeCdStr); } else { schmeNmCodeCd.setPrtry(schmeNmCodeCdStr); } otherAdditionalId.setSchmeNm(schmeNmCodeCd); return otherAdditionalId; } private static boolean isProprietaryCode(String schmeNmCodeCdStr) { // -- in the future we can create a list of used Codes from external // list and check against the list instead return !schmeNmCodeCdStr.equals(PERSON_ID_CODE_CUST); } private static XMLGregorianCalendar getReqdExctnDt(String reqdExctnDtStr) { XMLGregorianCalendar reqdExctnDt = null; try { DateFormat formatter = new SimpleDateFormat(ESIS_DATE_FORMAT); Date date = (Date) formatter.parse(reqdExctnDtStr); GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(date); reqdExctnDt = DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar); } catch (ParseException e) { throw new RuntimeException(e); } catch (DatatypeConfigurationException e) { throw new RuntimeException(e); } return reqdExctnDt; } }
true
true
public static SignableDocumentType convertToSignableDocumentType(List<LitasPaymentDto> rows) { if (rows == null || rows.size() < 1) { throw new IllegalArgumentException("List of LITAS-ESIS payments should be provided with at least one payment in the list."); } XMLGregorianCalendar createDate = createXMLGregorianCalendar(new Date()); GroupHeader32 header = new GroupHeader32(); header.setMsgId(UUID.randomUUID().toString().replaceAll("-", "")); header.setCreDtTm(createDate); header.setNbOfTxs(Integer.toString(rows.size())); CustomerCreditTransferInitiationV03 credit = new CustomerCreditTransferInitiationV03(); credit.setGrpHdr(header); Iterator<LitasPaymentDto> it = rows.iterator(); while (it.hasNext()) { LitasPaymentDto row = it.next(); PaymentTypeInformation19 type = new PaymentTypeInformation19(); ServiceLevel8Choice svcLvl = new ServiceLevel8Choice(); int priority = Integer.valueOf(row.getPriority()); if (priority == 1) { svcLvl.setCd(SVCLVL_CODE_NONURGENT); } else if (priority == 2) { svcLvl.setCd(SVCLVL_CODE_URGENT); } type.setSvcLvl(svcLvl); // -- create new transfer payment instruction PaymentInstructionInformation3 instr = new PaymentInstructionInformation3(); instr.setPmtInfId(UUID.randomUUID().toString().replaceAll("-", "")); instr.setPmtMtd(PaymentMethod3Code.TRF); instr.setPmtTpInf(type); // -- set requested execution date String reqdExctnDtStr = row.getValueDate(); if (hasValue(reqdExctnDtStr)) { instr.setReqdExctnDt(getReqdExctnDt(reqdExctnDtStr)); } // -- set debtor account AccountIdentification4Choice dbtrAcctIdIBAN = new AccountIdentification4Choice(); dbtrAcctIdIBAN.setIBAN(row.getPayerAccount()); CashAccount16 dbtrAcct = new CashAccount16(); dbtrAcct.setId(dbtrAcctIdIBAN); instr.setDbtrAcct(dbtrAcct); // -- set debtor PartyIdentification32 dbtr = createParty(row.getPayerName(), row.getPayerId(), row.getCustomerCodeInBeneficiaryIs(), PERSON_ID_CODE_CUST); instr.setDbtr(dbtr); // -- set debtor agent String dbtrAgtFinInstnIdBICStr = row.getPayerCreditInstitution(); if (hasValue(dbtrAgtFinInstnIdBICStr)) { instr.setDbtrAgt(getFinInstnId(dbtrAgtFinInstnIdBICStr)); } // -- set ultimate debtor PartyIdentification32 ultmtDbtr = createParty(row.getOriginatorName(), row.getOriginatorId(), row.getOriginatorAccount(), ULTIMATE_PARTY_ID_CODE_IBAN); if (ultmtDbtr != null) { instr.setUltmtDbtr(ultmtDbtr); } // -- set creditor account AccountIdentification4Choice cdtrAcctIdIBAN = new AccountIdentification4Choice(); cdtrAcctIdIBAN.setIBAN(row.getBeneficiaryAccount()); CreditTransferTransactionInformation10 cdtTrfTxInf = new CreditTransferTransactionInformation10(); // -- set credit transfer number String cdtTrfTxInfPmtIdStr = row.getDocumentNumber(); PaymentIdentification1 pmtId = new PaymentIdentification1(); pmtId.setInstrId(cdtTrfTxInfPmtIdStr); pmtId.setEndToEndId(cdtTrfTxInfPmtIdStr); cdtTrfTxInf.setPmtId(pmtId); // -- set creditor PartyIdentification32 cdtr = createParty(row.getBenificiaryName(), row.getBenificiaryId(), row.getCustomerCodeInPayerIs(), PERSON_ID_CODE_CUST); cdtTrfTxInf.setCdtr(cdtr); // -- set creditor agent String cdtrAgtFinInstnIdBICStr = row.getBenificiaryCreditInsitution(); if (hasValue(cdtrAgtFinInstnIdBICStr)) { cdtTrfTxInf.setCdtrAgt(getFinInstnId(cdtrAgtFinInstnIdBICStr)); } // -- set ultimate creditor PartyIdentification32 ultmtCdtr = createParty(row.getBenificiaryName(), row.getBenificiaryPartyId(), row.getBeneficiaryPartyAccount(), ULTIMATE_PARTY_ID_CODE_IBAN); if (ultmtCdtr != null) { cdtTrfTxInf.setUltmtCdtr(ultmtCdtr); } // -- set amount AmountType3Choice amt = createAmount(row.getAmount(), row.getCurrencyCode()); cdtTrfTxInf.setAmt(amt); // -- set purpose code (purpose is not the same as remittance! // Remittance is to identify particular instruction relation to the // particular invoice, whenever purpose is a static value, defining // the category of the payment) String purpPrtryStr = row.getReferenceNo(); if (hasValue(purpPrtryStr)) { Purpose2Choice purp = new Purpose2Choice(); purp.setPrtry(purpPrtryStr); cdtTrfTxInf.setPurp(purp); } // -- set unstructured remittance information RemittanceInformation5 rmtInf = createRmtInf(row.getPaymentDetails()); cdtTrfTxInf.setRmtInf(rmtInf); // -- add credit transfer transaction information (credit part) to // the instruction instr.getCdtTrfTxInf().add(cdtTrfTxInf); // -- add instruction to the list of instructions in the current // document credit.getPmtInf().add(instr); } iso.std.iso._20022.tech.xsd.pain_001_001.Document document = new iso.std.iso._20022.tech.xsd.pain_001_001.Document(); document.setCstmrCdtTrfInitn(credit); SignableDocumentType signableType = new SignableDocumentType(); signableType.setDocument(document); return signableType; }
public static SignableDocumentType convertToSignableDocumentType(List<LitasPaymentDto> rows) { if (rows == null || rows.size() < 1) { throw new IllegalArgumentException("List of LITAS-ESIS payments should be provided with at least one payment in the list."); } XMLGregorianCalendar createDate = createXMLGregorianCalendar(new Date()); GroupHeader32 header = new GroupHeader32(); header.setMsgId(UUID.randomUUID().toString().replaceAll("-", "")); header.setCreDtTm(createDate); header.setNbOfTxs(Integer.toString(rows.size())); CustomerCreditTransferInitiationV03 credit = new CustomerCreditTransferInitiationV03(); credit.setGrpHdr(header); Iterator<LitasPaymentDto> it = rows.iterator(); while (it.hasNext()) { LitasPaymentDto row = it.next(); PaymentTypeInformation19 type = new PaymentTypeInformation19(); ServiceLevel8Choice svcLvl = new ServiceLevel8Choice(); int priority = Integer.valueOf(row.getPriority()); if (priority == 1) { svcLvl.setCd(SVCLVL_CODE_NONURGENT); } else if (priority == 2) { svcLvl.setCd(SVCLVL_CODE_URGENT); } type.setSvcLvl(svcLvl); // -- create new transfer payment instruction PaymentInstructionInformation3 instr = new PaymentInstructionInformation3(); instr.setPmtInfId(UUID.randomUUID().toString().replaceAll("-", "")); instr.setPmtMtd(PaymentMethod3Code.TRF); instr.setPmtTpInf(type); // -- set requested execution date String reqdExctnDtStr = row.getValueDate(); if (hasValue(reqdExctnDtStr)) { instr.setReqdExctnDt(getReqdExctnDt(reqdExctnDtStr)); } // -- set debtor account AccountIdentification4Choice dbtrAcctIdIBAN = new AccountIdentification4Choice(); dbtrAcctIdIBAN.setIBAN(row.getPayerAccount()); CashAccount16 dbtrAcct = new CashAccount16(); dbtrAcct.setId(dbtrAcctIdIBAN); instr.setDbtrAcct(dbtrAcct); // -- set debtor PartyIdentification32 dbtr = createParty(row.getPayerName(), row.getPayerId(), row.getCustomerCodeInBeneficiaryIs(), PERSON_ID_CODE_CUST); instr.setDbtr(dbtr); // -- set debtor agent String dbtrAgtFinInstnIdBICStr = row.getPayerCreditInstitution(); if (hasValue(dbtrAgtFinInstnIdBICStr)) { instr.setDbtrAgt(getFinInstnId(dbtrAgtFinInstnIdBICStr)); } // -- set ultimate debtor PartyIdentification32 ultmtDbtr = createParty(row.getOriginatorName(), row.getOriginatorId(), row.getOriginatorAccount(), ULTIMATE_PARTY_ID_CODE_IBAN); if (ultmtDbtr != null) { instr.setUltmtDbtr(ultmtDbtr); } // -- set creditor account AccountIdentification4Choice cdtrAcctIdIBAN = new AccountIdentification4Choice(); cdtrAcctIdIBAN.setIBAN(row.getBeneficiaryAccount()); CreditTransferTransactionInformation10 cdtTrfTxInf = new CreditTransferTransactionInformation10(); // -- set credit transfer number String cdtTrfTxInfPmtIdStr = row.getDocumentNumber(); PaymentIdentification1 pmtId = new PaymentIdentification1(); pmtId.setInstrId(cdtTrfTxInfPmtIdStr); pmtId.setEndToEndId(cdtTrfTxInfPmtIdStr); cdtTrfTxInf.setPmtId(pmtId); // -- set creditor PartyIdentification32 cdtr = createParty(row.getBenificiaryName(), row.getBenificiaryId(), row.getCustomerCodeInPayerIs(), PERSON_ID_CODE_CUST); cdtTrfTxInf.setCdtr(cdtr); // -- set creditor agent String cdtrAgtFinInstnIdBICStr = row.getBenificiaryCreditInsitution(); if (hasValue(cdtrAgtFinInstnIdBICStr)) { cdtTrfTxInf.setCdtrAgt(getFinInstnId(cdtrAgtFinInstnIdBICStr)); } // -- set ultimate creditor PartyIdentification32 ultmtCdtr = createParty(row.getBenificiaryPartyName(), row.getBenificiaryPartyId(), row.getBeneficiaryPartyAccount(), ULTIMATE_PARTY_ID_CODE_IBAN); if (ultmtCdtr != null) { cdtTrfTxInf.setUltmtCdtr(ultmtCdtr); } // -- set amount AmountType3Choice amt = createAmount(row.getAmount(), row.getCurrencyCode()); cdtTrfTxInf.setAmt(amt); // -- set purpose code (purpose is not the same as remittance! // Remittance is to identify particular instruction relation to the // particular invoice, whenever purpose is a static value, defining // the category of the payment) String purpPrtryStr = row.getReferenceNo(); if (hasValue(purpPrtryStr)) { Purpose2Choice purp = new Purpose2Choice(); purp.setPrtry(purpPrtryStr); cdtTrfTxInf.setPurp(purp); } // -- set unstructured remittance information RemittanceInformation5 rmtInf = createRmtInf(row.getPaymentDetails()); cdtTrfTxInf.setRmtInf(rmtInf); // -- add credit transfer transaction information (credit part) to // the instruction instr.getCdtTrfTxInf().add(cdtTrfTxInf); // -- add instruction to the list of instructions in the current // document credit.getPmtInf().add(instr); } iso.std.iso._20022.tech.xsd.pain_001_001.Document document = new iso.std.iso._20022.tech.xsd.pain_001_001.Document(); document.setCstmrCdtTrfInitn(credit); SignableDocumentType signableType = new SignableDocumentType(); signableType.setDocument(document); return signableType; }
diff --git a/bundles/org.eclipse.core.filesystem/src/org/eclipse/core/internal/filesystem/NullFileStore.java b/bundles/org.eclipse.core.filesystem/src/org/eclipse/core/internal/filesystem/NullFileStore.java index d2b24a2f3..9929ea782 100644 --- a/bundles/org.eclipse.core.filesystem/src/org/eclipse/core/internal/filesystem/NullFileStore.java +++ b/bundles/org.eclipse.core.filesystem/src/org/eclipse/core/internal/filesystem/NullFileStore.java @@ -1,107 +1,108 @@ /******************************************************************************* * Copyright (c) 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 *******************************************************************************/ package org.eclipse.core.internal.filesystem; import java.io.*; import java.net.URI; import java.net.URISyntaxException; import org.eclipse.core.filesystem.*; import org.eclipse.core.filesystem.provider.FileInfo; import org.eclipse.core.filesystem.provider.FileStore; import org.eclipse.core.runtime.*; /** * A null file store represents a file whose location is unknown, * such as a location based on an undefined variable. This store * acts much like /dev/null on *nix: writes are ignored, reads return * empty streams, and modifications such as delete, mkdir, will fail. */ public class NullFileStore extends FileStore { private IPath path; /** * Creates a null file store * @param path The path of the file in this store */ public NullFileStore(IPath path) { this.path = path; } public IFileInfo[] childInfos(int options, IProgressMonitor monitor) { return EMPTY_FILE_INFO_ARRAY; } public String[] childNames(int options, IProgressMonitor monitor) { return EMPTY_STRING_ARRAY; } public void delete(int options, IProgressMonitor monitor) throws CoreException { //super implementation will always fail super.delete(options, monitor); } public IFileInfo fetchInfo(int options, IProgressMonitor monitor) { FileInfo result = new FileInfo(getName()); result.setExists(false); return result; } public IFileStore getChild(String name) { return new NullFileStore(path.append(name)); } public IFileSystem getFileSystem() { return NullFileSystem.getInstance(); } public String getName() { return String.valueOf(path.lastSegment()); } public IFileStore getParent() { return path.segmentCount() == 0 ? null : new NullFileStore(path.removeLastSegments(1)); } public IFileStore mkdir(int options, IProgressMonitor monitor) throws CoreException { //super implementation will always fail return super.mkdir(options, monitor); } public InputStream openInputStream(int options, IProgressMonitor monitor) { return new ByteArrayInputStream(new byte[0]); } public OutputStream openOutputStream(int options, IProgressMonitor monitor) { return new OutputStream() { public void write(int b) { //do nothing } }; } public void putInfo(IFileInfo info, int options, IProgressMonitor monitor) throws CoreException { //super implementation will always fail super.putInfo(info, options, monitor); } public String toString() { return path.toString(); } public URI toURI() { try { - return new URI(EFS.SCHEME_NULL, null, path.toString(), null); + return new URI(EFS.SCHEME_NULL, null, path.isEmpty() ? "/" : path.toString(), null); //$NON-NLS-1$ } catch (URISyntaxException e) { - //should not happen - throw new Error(e); + //should never happen + Policy.log(IStatus.ERROR, "Invalid URI", e); //$NON-NLS-1$ + return null; } } }
false
true
public URI toURI() { try { return new URI(EFS.SCHEME_NULL, null, path.toString(), null); } catch (URISyntaxException e) { //should not happen throw new Error(e); } }
public URI toURI() { try { return new URI(EFS.SCHEME_NULL, null, path.isEmpty() ? "/" : path.toString(), null); //$NON-NLS-1$ } catch (URISyntaxException e) { //should never happen Policy.log(IStatus.ERROR, "Invalid URI", e); //$NON-NLS-1$ return null; } }
diff --git a/src/classviewer/changes/EdxModelAdapter.java b/src/classviewer/changes/EdxModelAdapter.java index bd909ac..a165f51 100644 --- a/src/classviewer/changes/EdxModelAdapter.java +++ b/src/classviewer/changes/EdxModelAdapter.java @@ -1,541 +1,541 @@ package classviewer.changes; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.URL; import java.net.URLConnection; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import classviewer.model.CourseModel; import classviewer.model.CourseRec; import classviewer.model.OffRec; import classviewer.model.Status; /** * EdX html is weird. I could not find an off-the-shelf parser that would * convert it into DOM, so here is a hackish solution. * * Only doing additions and modifications for universities and classes. * * @author TK */ public class EdxModelAdapter { /** Class records bundled by class id */ private HashMap<String, ArrayList<EdxRecord>> records = new HashMap<String, ArrayList<EdxRecord>>(); private static SSLSocketFactory sslSocketFactory; static { // We will use this to deal with PKIX cert exceptions makeAllTrustingManager(); } /** Read everything into a string buffer */ private StringBuffer readIntoBuffer(Reader reader) throws IOException { StringBuffer b = new StringBuffer(); BufferedReader br = new BufferedReader(reader); String s = br.readLine(); while (s != null) { b.append(s + "\n"); // keep /n there for easier debugging s = br.readLine(); } return b; } /** * Find next article from the given offset. An article should have XML tag * "article" and "class" attribute "course". Return -1 if not found. */ private int findNextArticle(StringBuffer all, int offset) throws IOException { // Until we find something or run out of file // while (offset < all.length()) { int off = all.indexOf("course-tile", offset); return off; // if (off < 0) // return -1; // // Closing > after this // int close = all.indexOf("</article>", off); // if (close < 0) // throw new IOException("Article tag at " + off // + " does not close. Broken file?"); // // Now look for class before the closing. Assume no spaces between // // the attribute name and the value // int cl = all.indexOf("<h1><span>", off); // if (cl > 0 && cl < close) // return off; // // Otherwise move past close // offset = close + 1; // } // // Ran out of file // return -1; } /** * Extract course info from the chunk of the buffer between start and end. * * @return */ private EdxRecord parseCourse(String all, String edxBase) throws IOException { // final String toID = "<article id=\""; final String toUrl = "<a href=\""; final String toNew = "<div class=\"new-course-ribbon\">"; final String toNumber = "<h2 class=\"title course-title\">"; final String toDesc = "course-subtitle copy-detail\">"; final String toDate = "Starts:</span>"; final String toUni = "<li><strong>"; int idx, end; boolean isNew = all.indexOf(toNew) > 0; idx = all.indexOf(toUrl); if (idx < 0) throw new IOException("No URL for course " + all); end = all.indexOf("\"", idx + toUrl.length()); String home = all.substring(idx + toUrl.length(), end); idx = all.indexOf(toNumber); if (idx < 0) throw new IOException("No number for course " + all); end = all.indexOf("<", idx + toNumber.length()); if (end < 0) throw new IOException("Tag at " + idx + " does not close " + all); String courseId = all.substring(idx + toNumber.length(), end).trim(); if (courseId.endsWith(":")) courseId = courseId.substring(0, courseId.length()-1); // assuming it's </strong><a ... idx = all.indexOf(">", end + 15); end = all.indexOf("<", idx); if (end < 0) throw new IOException("No title end at " + idx + " in " + all); String name = cleanStr(all.substring(idx + 1, end).trim()); idx = all.indexOf(toDesc); if (idx < 0) throw new IOException("No description for course " + all); // idx = all.indexOf("<p>", idx); // if (idx < 0) // throw new IOException("No <p> in description for course " + all); end = all.indexOf("<", idx+2); if (end < 0) throw new IOException("Tag at " + idx + " does not close " + all); String descr = cleanStr(all.substring(idx + toDesc.length(), end).trim()); idx = all.indexOf(toDate); if (idx < 0) throw new IOException("No date for course " + all); end = all.indexOf("</", idx + toDate.length() + 1); if (end < 0) throw new IOException("Tag at " + idx + " does not close " + all); String dateStr = all.substring(idx + toDate.length(), end).trim(); idx = all.indexOf(toUni); if (idx < 0) throw new IOException("No university for course " + all); end = all.indexOf("</", idx); if (end < 0) throw new IOException("Tag at " + idx + " does not close " + all); String univer = all.substring(idx + toUni.length(), end).trim(); // Drop spaces in the university name. Otherwise we have problems // forming space-separated attribute string. Also, get rid of // "University of " univer = univer.replace("University of ", ""); univer = univer.replace(" ", ""); // System.out.println(courseId + ", " + name + "\n\t" + descr + "\n\t" // + univer + ", " + date + ", " + isNew); Date start = EdxRecord.parseDate(dateStr); int duration = 1; // TODO they seem to have dropped end date // if (home != null && start != null) { // String endStr = extractEndDate(edxBase, home); // Date endDate = EdxRecord.parseDate(endStr); // if (endDate != null) { // long mills = endDate.getTime() - start.getTime(); // duration = Math.round(mills / (1000 * 3600 * 24 * 7.0f)); // } // } return new EdxRecord(courseId, name, descr, univer, start, duration, home, isNew); } private String cleanStr(String str) { str = str.replace("&amp;", "&"); return str; } /* <article class="course-tile"><div class="left-col"> <div class="new-course-ribbon"></div><div class="top"><div class="title"> <h1><span>24.00x:</span> Introduction to Philosophy: God, Knowledge and Consciousness</h1> </div> <div class="subtitle">This course will focus on big questions. You will learn how to ask them and how to answer them. <a class="go-to-course" href="/course/mit/24-00x/introduction-philosophy-god/888">more</a> </div></div><div class="bottom"> <div class="detail"><ul class="clearfix"><li> <span class="bold-title">Starts:</span> <span class="date-display-single">1 Oct 2013</span> </li><li> • </li><li><div class="instructor-list"> <span class="bold-title">Instructors:</span> Caspar Hare</div></li> <li> • </li><li class="school-list">MITx</li></ul></div></div></div> <div class="right-col"> <div class="image"> <img src="https://www.edx.org/sites/default/files/styles/course_tile_image/public/2400x_262x136.jpg?itok=y3n29SDS" width="277" height="136" alt="Introduction to Philosophy: God, Knowledge and Consciousness" /> </div><div class="actions clearfix"> <div class="action"><div class="iframe iframe-register action-register-course"> <iframe src="https://courses.edx.org/mktg/MITx/24.00x/2013_SOND"></iframe> </div></div></div></div><div class="clearfix"></div> <div style="hidden" class="course-link" href="/course/mit/24-00x/introduction-philosophy-god/888"></div> </article> </div><div class="views-row views-row-2 views-row-even"> <!-- This is the template for every row in Courses Page --> */ /** Assuming everything is in a string buffer, pick out classes */ private HashMap<String, ArrayList<EdxRecord>> readHtml(StringBuffer all, String baseUrl) throws IOException { int offset = 0; final int END = all.length(); while (offset < END) { // Start of the next course description, if any int start = findNextArticle(all, offset); if (start < 0) break; // End of this article, will miss the last big blue button int end = all.indexOf("<div class=\"col-both-courses\">", offset); if (end < 0) { System.err.println("Article at " + offset + " is not closed"); end = END; } // Parse this particular course info EdxRecord rec = parseCourse(all.substring(start, end), baseUrl); ArrayList<EdxRecord> list = records.get(rec.getCourseId()); if (list == null) { list = new ArrayList<EdxRecord>(); records.put(rec.getCourseId(), list); } list.add(rec); // Move past the end offset = end + 10; } return records; } // Borrowed from https://code.google.com/p/misc-utils/wiki/JavaHttpsUrl private static void makeAllTrustingManager() { // Create a trust manager that does not validate certificate chains final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(final X509Certificate[] chain, final String authType) { } @Override public void checkServerTrusted(final X509Certificate[] chain, final String authType) { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } } }; // Install the all-trusting trust manager try { SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); // Create an ssl socket factory with our all-trusting manager sslSocketFactory = sslContext.getSocketFactory(); } catch (NoSuchAlgorithmException | KeyManagementException e) { throw new RuntimeException(e); } } /** * This is the main read method called from the application. It puts data * into internal structure */ public void parse(String edxUrl, boolean ignoreSSL) throws IOException { records.clear(); int page = 0; while (true) { URL url = new URL(edxUrl + "/course-list/allschools/allsubjects/allcourses" + ((page == 0) ? "" : ("?page=" + page))); // All set up, we can get a resource through https now: URLConnection urlCon = url.openConnection(); // Tell the url connection object to use our socket factory which // bypasses security checks if (ignoreSSL) ((HttpsURLConnection) urlCon) .setSSLSocketFactory(sslSocketFactory); InputStream stream = urlCon.getInputStream(); InputStreamReader reader = new InputStreamReader(stream); StringBuffer buffer = readIntoBuffer(reader); stream.close(); if (buffer.indexOf("courses-no-result-title") > 0) break; int before = records.size(); readHtml(buffer, edxUrl); if (records.size() == before) { System.out.println("Found no records and no stop sign in page " + page); break; } page++; } } /** * Compare the internal structure produced by the parse method to the given * model and return the set of differences */ public ArrayList<Change> collectChanges(CourseModel courseModel, int tooOldInDays) { // Build a date before which we do not remove offerings Date tooOld = new Date( new Date().getTime() - 24*3600000l*tooOldInDays ); System.out.println("Will keep all offerings older than " + tooOldInDays + " days: " + tooOld); ArrayList<Change> res = new ArrayList<Change>(); // There are no categories for Edx, but there are universities. For // categories we'll just set EdX, unless manually specified otherwise HashSet<String> uniFromFile = new HashSet<String>(); // Just check the first record. Assume the list is not empty for (ArrayList<EdxRecord> lr : records.values()) uniFromFile.add(lr.get(0).getUniversity()); for (String u : uniFromFile) { if (courseModel.getUniversity(u) == null) res.add(new DescChange(DescChange.UNIVERSITY, Change.ADD, "EdX University", null, makeUniJsonForId(u))); } // EdX is not particularly consistent with naming, hence this hack. // Note that this will only work for simplification of ids. ArrayList<String> names = new ArrayList<String>(records.keySet()); for (String s : names) { CourseRec oldRec = courseModel.getClassByShortName(s); if (oldRec != null) continue; String s1 = s.replace(" ", "").replace("-", ""); oldRec = courseModel.getClassByShortName(s1); if (oldRec != null) { ArrayList<EdxRecord> list = records.remove(s); for (EdxRecord r : list) r.setCourseId(s1); ArrayList<EdxRecord> list1 = records.get(s1); if (list1 == null) records.put(s1, list); else list1.addAll(list); } } // Go over all course bundles, pick those that don't yet exist for (ArrayList<EdxRecord> list : records.values()) { String courseId = list.get(0).getCourseId(); CourseRec oldRec = courseModel.getClassByShortName(courseId); if (oldRec == null) { res.add(new EdxCourseChange(Change.ADD, null, null, list, courseModel)); } else { diffCourse(list, oldRec, res, courseModel, tooOld); } } return res; } private void diffCourse(ArrayList<EdxRecord> list, CourseRec oldRec, ArrayList<Change> res, CourseModel model, Date tooOld) { // The only things we have here are: name, description, offerings String s1 = list.get(0).getName(); String s2 = oldRec.getName(); if (s1 == null && s2 != null || s1 != null && !s1.equals(s2)) res.add(new EdxCourseChange(Change.MODIFY, "Name", oldRec, list, model)); s1 = list.get(0).getDescription(); s2 = oldRec.getDescription(); if (s1 == null && s2 != null || s1 != null && !s1.equals(s2)) res.add(new EdxCourseChange(Change.MODIFY, "Description", oldRec, list, model)); // Compare offerings by date ArrayList<Date> existing = new ArrayList<Date>(); ArrayList<Date> incoming = new ArrayList<Date>(); for (EdxRecord r : list) if (r.getStart() != null) incoming.add(r.getStart()); else System.err.println("New EdX offering without start date: " + r); for (OffRec r : oldRec.getOfferings()) if (r.getStart() != null) existing.add(r.getStart()); else System.err.println("Existing EdX offering without start date: " + r); // Differences ArrayList<Date> deleted = new ArrayList<Date>(existing); deleted.removeAll(incoming); ArrayList<Date> added = new ArrayList<Date>(incoming); added.removeAll(existing); // Remove deletes that are too old for (Iterator<Date> it = deleted.iterator(); it.hasNext(); ) { Date d = it.next(); if (d.before(tooOld)) it.remove(); } // Possible date shift? if (deleted.size() == 1 && added.size() == 1) { OffRec rr = null; for (OffRec r : oldRec.getOfferings()) - if (r.getStart().equals(deleted.get(0))) { + if (r.getStart() != null && r.getStart().equals(deleted.get(0))) { rr = r; break; } EdxRecord er = null; for (EdxRecord r : list) if (r.getStart().equals(added.get(0))) { er = r; break; } // EdxOfferingChange(String type, CourseRec course, String field, OffRec offering, EdxRecord record res.add(new EdxOfferingChange(Change.MODIFY, oldRec, "Start", rr, er)); deleted.clear(); added.clear(); } // Prune deleted things that are actually done: never delete those records for (OffRec r : oldRec.getOfferings()) if (deleted.contains(r.getStart()) && (Status.DONE.equals(r.getStatus()) || Status.REGISTERED .equals(r.getStatus()))) { deleted.remove(r.getStart()); } // Deleted for (OffRec r : oldRec.getOfferings()) if (deleted.contains(r.getStart())) res.add(new EdxOfferingChange(Change.DELETE, oldRec, null, r, null)); // Added for (EdxRecord r : list) if (added.contains(r.getStart())) res.add(new EdxOfferingChange(Change.ADD, oldRec, null, null, r)); // For the intersection check duration. No need to check the start date, // since it's the key. TODO They no longer have duration // diff = new ArrayList<Date>(existing); // diff.retainAll(incoming); // for (EdxRecord r : list) // if (diff.contains(r.getStart())) { // // Locate corresponding existing // OffRec r1 = null; // for (OffRec r2 : oldRec.getOfferings()) // if (r2.getStart().equals(r.getStart())) // r1 = r2; // assert (r1 != null); // // if (r1.getDuration() != r.getDuration()) { // res.add(new EdxOfferingChange(Change.MODIFY, oldRec, // "Duration", r1, r)); // } // } } private HashMap<String, Object> makeUniJsonForId(String u) { HashMap<String, Object> res = new HashMap<String, Object>(); res.put("name", u); res.put("short_name", u); res.put("description", u + " on EdX"); return res; } public String extractEndDate(String baseUrl, String home) { final String tag = "<span class=\"final-date\">"; String addr = baseUrl + home; try { URL url = new URL(addr); InputStream stream = url.openStream(); InputStreamReader reader = new InputStreamReader(stream); StringBuffer buffer = readIntoBuffer(reader); stream.close(); int idx = buffer.indexOf(tag); if (idx < 0) return null; int end = buffer.indexOf("</span>", idx); return buffer.substring(idx + tag.length(), end).trim(); } catch (Exception e) { System.err.println("Cannot get end date from " + addr); } return null; } public boolean loadClassDuration(String baseURL, OffRec off, boolean ignoreSSL) throws IOException { String tail = off.getLink(); if (tail == null) return false; URL url = new URL(baseURL + tail); // All set up, we can get a resource through https now: URLConnection urlCon = url.openConnection(); // Tell the url connection object to use our socket factory which // bypasses security checks if (ignoreSSL) ((HttpsURLConnection) urlCon).setSSLSocketFactory(sslSocketFactory); InputStream stream = urlCon.getInputStream(); InputStreamReader reader = new InputStreamReader(stream); StringBuffer buffer = readIntoBuffer(reader); stream.close(); // We are looking for the number of weeks. This code is specific to the // EdX format final String startLabel = "Course Length:"; int start = buffer.indexOf(startLabel); if (start < 0) { return false; } start += startLabel.length(); int end = buffer.indexOf(" week", start); if (end < 0) { return false; } // This slice should end with the number we are looking for String slice = buffer.substring(start, end).trim(); for (start = slice.length() - 1; start >= 0 && Character.isDigit(slice.charAt(start)); start--) ; int weeks = Integer.parseInt(slice.substring(start + 1)); off.setDuration(weeks); return true; } }
true
true
private void diffCourse(ArrayList<EdxRecord> list, CourseRec oldRec, ArrayList<Change> res, CourseModel model, Date tooOld) { // The only things we have here are: name, description, offerings String s1 = list.get(0).getName(); String s2 = oldRec.getName(); if (s1 == null && s2 != null || s1 != null && !s1.equals(s2)) res.add(new EdxCourseChange(Change.MODIFY, "Name", oldRec, list, model)); s1 = list.get(0).getDescription(); s2 = oldRec.getDescription(); if (s1 == null && s2 != null || s1 != null && !s1.equals(s2)) res.add(new EdxCourseChange(Change.MODIFY, "Description", oldRec, list, model)); // Compare offerings by date ArrayList<Date> existing = new ArrayList<Date>(); ArrayList<Date> incoming = new ArrayList<Date>(); for (EdxRecord r : list) if (r.getStart() != null) incoming.add(r.getStart()); else System.err.println("New EdX offering without start date: " + r); for (OffRec r : oldRec.getOfferings()) if (r.getStart() != null) existing.add(r.getStart()); else System.err.println("Existing EdX offering without start date: " + r); // Differences ArrayList<Date> deleted = new ArrayList<Date>(existing); deleted.removeAll(incoming); ArrayList<Date> added = new ArrayList<Date>(incoming); added.removeAll(existing); // Remove deletes that are too old for (Iterator<Date> it = deleted.iterator(); it.hasNext(); ) { Date d = it.next(); if (d.before(tooOld)) it.remove(); } // Possible date shift? if (deleted.size() == 1 && added.size() == 1) { OffRec rr = null; for (OffRec r : oldRec.getOfferings()) if (r.getStart().equals(deleted.get(0))) { rr = r; break; } EdxRecord er = null; for (EdxRecord r : list) if (r.getStart().equals(added.get(0))) { er = r; break; } // EdxOfferingChange(String type, CourseRec course, String field, OffRec offering, EdxRecord record res.add(new EdxOfferingChange(Change.MODIFY, oldRec, "Start", rr, er)); deleted.clear(); added.clear(); } // Prune deleted things that are actually done: never delete those records for (OffRec r : oldRec.getOfferings()) if (deleted.contains(r.getStart()) && (Status.DONE.equals(r.getStatus()) || Status.REGISTERED .equals(r.getStatus()))) { deleted.remove(r.getStart()); } // Deleted for (OffRec r : oldRec.getOfferings()) if (deleted.contains(r.getStart())) res.add(new EdxOfferingChange(Change.DELETE, oldRec, null, r, null)); // Added for (EdxRecord r : list) if (added.contains(r.getStart())) res.add(new EdxOfferingChange(Change.ADD, oldRec, null, null, r)); // For the intersection check duration. No need to check the start date, // since it's the key. TODO They no longer have duration // diff = new ArrayList<Date>(existing); // diff.retainAll(incoming); // for (EdxRecord r : list) // if (diff.contains(r.getStart())) { // // Locate corresponding existing // OffRec r1 = null; // for (OffRec r2 : oldRec.getOfferings()) // if (r2.getStart().equals(r.getStart())) // r1 = r2; // assert (r1 != null); // // if (r1.getDuration() != r.getDuration()) { // res.add(new EdxOfferingChange(Change.MODIFY, oldRec, // "Duration", r1, r)); // } // } }
private void diffCourse(ArrayList<EdxRecord> list, CourseRec oldRec, ArrayList<Change> res, CourseModel model, Date tooOld) { // The only things we have here are: name, description, offerings String s1 = list.get(0).getName(); String s2 = oldRec.getName(); if (s1 == null && s2 != null || s1 != null && !s1.equals(s2)) res.add(new EdxCourseChange(Change.MODIFY, "Name", oldRec, list, model)); s1 = list.get(0).getDescription(); s2 = oldRec.getDescription(); if (s1 == null && s2 != null || s1 != null && !s1.equals(s2)) res.add(new EdxCourseChange(Change.MODIFY, "Description", oldRec, list, model)); // Compare offerings by date ArrayList<Date> existing = new ArrayList<Date>(); ArrayList<Date> incoming = new ArrayList<Date>(); for (EdxRecord r : list) if (r.getStart() != null) incoming.add(r.getStart()); else System.err.println("New EdX offering without start date: " + r); for (OffRec r : oldRec.getOfferings()) if (r.getStart() != null) existing.add(r.getStart()); else System.err.println("Existing EdX offering without start date: " + r); // Differences ArrayList<Date> deleted = new ArrayList<Date>(existing); deleted.removeAll(incoming); ArrayList<Date> added = new ArrayList<Date>(incoming); added.removeAll(existing); // Remove deletes that are too old for (Iterator<Date> it = deleted.iterator(); it.hasNext(); ) { Date d = it.next(); if (d.before(tooOld)) it.remove(); } // Possible date shift? if (deleted.size() == 1 && added.size() == 1) { OffRec rr = null; for (OffRec r : oldRec.getOfferings()) if (r.getStart() != null && r.getStart().equals(deleted.get(0))) { rr = r; break; } EdxRecord er = null; for (EdxRecord r : list) if (r.getStart().equals(added.get(0))) { er = r; break; } // EdxOfferingChange(String type, CourseRec course, String field, OffRec offering, EdxRecord record res.add(new EdxOfferingChange(Change.MODIFY, oldRec, "Start", rr, er)); deleted.clear(); added.clear(); } // Prune deleted things that are actually done: never delete those records for (OffRec r : oldRec.getOfferings()) if (deleted.contains(r.getStart()) && (Status.DONE.equals(r.getStatus()) || Status.REGISTERED .equals(r.getStatus()))) { deleted.remove(r.getStart()); } // Deleted for (OffRec r : oldRec.getOfferings()) if (deleted.contains(r.getStart())) res.add(new EdxOfferingChange(Change.DELETE, oldRec, null, r, null)); // Added for (EdxRecord r : list) if (added.contains(r.getStart())) res.add(new EdxOfferingChange(Change.ADD, oldRec, null, null, r)); // For the intersection check duration. No need to check the start date, // since it's the key. TODO They no longer have duration // diff = new ArrayList<Date>(existing); // diff.retainAll(incoming); // for (EdxRecord r : list) // if (diff.contains(r.getStart())) { // // Locate corresponding existing // OffRec r1 = null; // for (OffRec r2 : oldRec.getOfferings()) // if (r2.getStart().equals(r.getStart())) // r1 = r2; // assert (r1 != null); // // if (r1.getDuration() != r.getDuration()) { // res.add(new EdxOfferingChange(Change.MODIFY, oldRec, // "Duration", r1, r)); // } // } }
diff --git a/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/PackageHtmlCheck.java b/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/PackageHtmlCheck.java index c6a3428e..11b97d8d 100644 --- a/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/PackageHtmlCheck.java +++ b/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/PackageHtmlCheck.java @@ -1,68 +1,70 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2002 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; import java.io.File; import java.util.Iterator; import java.util.Set; import com.puppycrawl.tools.checkstyle.api.MessageDispatcher; import com.puppycrawl.tools.checkstyle.api.LocalizedMessage; import com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck; /** * <p> * Checks that all packages have a package documentation. * </p> * <p> * An example of how to configure the check is: * </p> * <pre> * &lt;module name="PackageHtml"/&gt; * </pre> * @author lkuehne */ public class PackageHtmlCheck extends AbstractFileSetCheck { /** * Checks that each java file in the fileset has a package.html sibling * and fires errors for the missing files. * @param aFiles a set of files */ public void process(File[] aFiles) { Set directories = getParentDirs(aFiles); for (Iterator it = directories.iterator(); it.hasNext();) { File dir = (File) it.next(); File packageHtml = new File(dir, "package.html"); MessageDispatcher dispatcher = getMessageDispatcher(); final String path = packageHtml.getPath(); dispatcher.fireFileStarted(path); if (!packageHtml.exists()) { LocalizedMessage[] errors = new LocalizedMessage[1]; - final String bundle = - this.getClass().getPackage().getName() + ".messages"; + final String className = getClass().getName(); + final int pkgEndIndex = className.lastIndexOf('.'); + final String pkgName = className.substring(0, pkgEndIndex); + final String bundle = pkgName + ".messages"; errors[0] = new LocalizedMessage( 0, bundle, "javadoc.packageHtml", null); getMessageDispatcher().fireErrors(path, errors); } dispatcher.fireFileFinished(path); } } }
true
true
public void process(File[] aFiles) { Set directories = getParentDirs(aFiles); for (Iterator it = directories.iterator(); it.hasNext();) { File dir = (File) it.next(); File packageHtml = new File(dir, "package.html"); MessageDispatcher dispatcher = getMessageDispatcher(); final String path = packageHtml.getPath(); dispatcher.fireFileStarted(path); if (!packageHtml.exists()) { LocalizedMessage[] errors = new LocalizedMessage[1]; final String bundle = this.getClass().getPackage().getName() + ".messages"; errors[0] = new LocalizedMessage( 0, bundle, "javadoc.packageHtml", null); getMessageDispatcher().fireErrors(path, errors); } dispatcher.fireFileFinished(path); } }
public void process(File[] aFiles) { Set directories = getParentDirs(aFiles); for (Iterator it = directories.iterator(); it.hasNext();) { File dir = (File) it.next(); File packageHtml = new File(dir, "package.html"); MessageDispatcher dispatcher = getMessageDispatcher(); final String path = packageHtml.getPath(); dispatcher.fireFileStarted(path); if (!packageHtml.exists()) { LocalizedMessage[] errors = new LocalizedMessage[1]; final String className = getClass().getName(); final int pkgEndIndex = className.lastIndexOf('.'); final String pkgName = className.substring(0, pkgEndIndex); final String bundle = pkgName + ".messages"; errors[0] = new LocalizedMessage( 0, bundle, "javadoc.packageHtml", null); getMessageDispatcher().fireErrors(path, errors); } dispatcher.fireFileFinished(path); } }
diff --git a/src/test/java/org/jenkinsci/plugins/pretestedintegration/PretestedIntegrationPreCheckoutTest.java b/src/test/java/org/jenkinsci/plugins/pretestedintegration/PretestedIntegrationPreCheckoutTest.java index a8a41da..2fbd69b 100644 --- a/src/test/java/org/jenkinsci/plugins/pretestedintegration/PretestedIntegrationPreCheckoutTest.java +++ b/src/test/java/org/jenkinsci/plugins/pretestedintegration/PretestedIntegrationPreCheckoutTest.java @@ -1,299 +1,299 @@ package org.jenkinsci.plugins.pretestedintegration; import java.io.File; import java.io.IOException; import java.lang.reflect.Constructor; import java.util.Scanner; import static org.mockito.Mockito.*; public class PretestedIntegrationPreCheckoutTest extends PretestedIntegrationTestCase { public void testShouldCreateInstance() throws Exception { Constructor <?> c = PretestedIntegrationPreCheckout.class - .getConstructor(String.class); + .getConstructor(); Object inst = c.newInstance(); assertNotNull(inst); } // public void testShouldReturnRepositoryUrl() throws Exception { // String repositoryUrl = "foo"; // PretestedIntegrationPreCheckout instance = new PretestedIntegrationPreCheckout(repositoryUrl); // assertNotNull(instance); // assertEquals(instance.getStageRepository(), repositoryUrl); // } // /** * Tests the validateConfiguration method in the */ // public void testShouldValidateConfiguration() throws Exception { // File tmp = setup(true, true); // // //Given a valid local repository // File stage = new File(tmp,"stage"); // //When i test for validation // PretestedIntegrationPreCheckout.DescriptorImpl descriptor = new PretestedIntegrationPreCheckout.DescriptorImpl(); // boolean isValid = descriptor.validateConfiguration(stage.getAbsolutePath()); // //Then the validation method should return true // assertTrue(isValid); // // //Given a remote repository // //When i validate it // //Then the validation method should return true // //TODO: Make test cases with shh:// and http:// // // } /** * Test if the a new repository is correctly initialised */ // public void testShouldFailValidateConfiguration() throws Exception{ // PretestedIntegrationPreCheckout.DescriptorImpl descriptor = new PretestedIntegrationPreCheckout.DescriptorImpl(); // // File tmp = getTempFile(); // assertFalse(descriptor.validateConfiguration(tmp.getAbsolutePath())); // // //Given an empty directory, e.g. no .hg/ // //When i test for validity // //Then the validation method should throw an InvalidRepositoryException exception // // //Given an empty valid repository e.g. hg init // //When i test for validity // //Then the validation method should return false // // //Given a repository without the hook // //When I test for validity // //Then the validation method should return false // // //Given a repository without the hgrc file // //When I test for validity // //Then the validation method should return false // // //Given a repository with a hgrc file // //And the changegroup hook does not exist // //Then the validation method should return false // } // public void testShouldGiveDotHgDirectory() throws Exception { // //Given a local filepath // String relativePath = "some/local/directory"; // String relativePathEndingWithSlash = relativePath + "/"; // //When I try to get the configuration directory for the repository // //Then the path is // //PretestedIntegrationPreCheckout buildWrapper = new PretestedIntegrationPreCheckout(""); // // PretestedIntegrationPreCheckout.DescriptorImpl descriptor = new PretestedIntegrationPreCheckout.DescriptorImpl(); // // //buildWrapper.getDescriptor(); // // assertEquals(new File(relativePath + "/.hg"), descriptor.configurationDirectory(relativePath)); // assertEquals(new File(relativePathEndingWithSlash + ".hg"), descriptor.configurationDirectory(relativePathEndingWithSlash)); // } // // public void testShouldSetupRepositoryDirectoryExists() throws Exception { // //Some initial setup // PretestedIntegrationPreCheckout.DescriptorImpl descriptor = new PretestedIntegrationPreCheckout.DescriptorImpl(); // // //Given a directory that does exist // File tmp = createTempDirectory(); // //When I invoke the setup method // boolean setupResult = descriptor.setupRepositoryDirectory(tmp); // //Then the setup method should return true // assertTrue(setupResult); // //And the directory should still exist // assertTrue(tmp.exists()); // } // // public void testShouldSetupRepositoryDirectoryNotExists() throws Exception { // //Some initial setup // PretestedIntegrationPreCheckout.DescriptorImpl descriptor = new PretestedIntegrationPreCheckout.DescriptorImpl(); // // //Given a directory that does not exist // File tmp = getTempFile(); // //When I invoke the setup method // boolean setupResult = descriptor.setupRepositoryDirectory(tmp); // //Then the setup method should return true // assertTrue(setupResult); // //And the directory should exist afterwards // assertTrue(tmp.exists()); // // //cleanup the results // } // // public void testShouldFailSetupDirectory() throws Exception { // PretestedIntegrationPreCheckout.DescriptorImpl descriptor = new PretestedIntegrationPreCheckout.DescriptorImpl(); // // File tmp = createTempDirectory(); // tmp.setWritable(false); // File newDir = new File(tmp,"foo"); // // boolean setupResult = descriptor.setupRepositoryDirectory(newDir); // assertFalse(setupResult); // assertFalse(newDir.exists()); // } // // public void testShouldUpdateConfigurationHgrcNotExists() throws Exception { // PretestedIntegrationPreCheckout.DescriptorImpl descriptor = new PretestedIntegrationPreCheckout.DescriptorImpl(); // // //Given that the repository is correctly setup // File tmp = getTempFile(); // File repoDir = new File(tmp,".hg"); // repoDir.mkdirs(); // // File hgrc = new File(repoDir,"hgrc"); // //And that the hgrc does not exist // assertFalse(hgrc.exists()); // //When the the configuration is updated // boolean updateResult = descriptor.writeConfiguration(tmp.getAbsolutePath()); // //And the configuration succeeds // assertTrue(updateResult); // //Then the hgrc file should exist // assertTrue(hgrc.exists()); // //And the hgrc file should contain a new hook // Scanner scanner = new Scanner(hgrc); // assertNotNull(scanner.findWithinHorizon("[hooks]", 0)); // assertNotNull(scanner.findWithinHorizon("changegroup = python:.hg/hg_changegroup_hook.py:run", 0)); // } // // public void testShouldUpdateConfigurationHgrcExists() throws Exception { // PretestedIntegrationPreCheckout.DescriptorImpl descriptor = new PretestedIntegrationPreCheckout.DescriptorImpl(); // // //Setup the directory // File tmp = getTempFile(); // File repoDir = new File(tmp,".hg"); // repoDir.mkdirs(); // // File hgrc = new File(repoDir,"hgrc"); // assertTrue(hgrc.createNewFile()); // boolean updateResult = descriptor.writeConfiguration(tmp.getAbsolutePath()); // assertTrue(updateResult); // assertTrue(hgrc.exists()); // Scanner scanner = new Scanner(hgrc); // assertNotNull(scanner.findWithinHorizon("[hooks]", 0)); // assertNotNull(scanner.findWithinHorizon("changegroup = python:.hg/hg_changegroup_hook.py:run", 0)); // } // // public void testShouldFailUpdateConfigurationHgrcNotCreatable() throws Exception { // PretestedIntegrationPreCheckout.DescriptorImpl descriptor = new PretestedIntegrationPreCheckout.DescriptorImpl(); // // //Setup the directory // File tmp = getTempFile(); // File repoDir = new File(tmp,".hg"); // repoDir.mkdirs(); // repoDir.setWritable(false); // // File hgrc = new File(repoDir,"hgrc"); // boolean updateResult = descriptor.writeConfiguration(tmp.getAbsolutePath()); // assertFalse(updateResult); // assertFalse(hgrc.exists()); // repoDir.setWritable(true); // } // // public void testShouldFailUpdateConfigurationHgrcNotWritable() throws Exception { // PretestedIntegrationPreCheckout.DescriptorImpl descriptor = new PretestedIntegrationPreCheckout.DescriptorImpl(); // // //Setup the directory // File tmp = getTempFile(); // File repoDir = new File(tmp,".hg"); // repoDir.mkdirs(); // // File hgrc = new File(repoDir,"hgrc"); // hgrc.createNewFile(); // hgrc.setWritable(false); // boolean updateResult = descriptor.writeConfiguration(tmp.getAbsolutePath()); // assertFalse(updateResult); // hgrc.setWritable(true); // // } // // public void testShouldUpdateHook() throws Exception { // PretestedIntegrationPreCheckout.DescriptorImpl descriptor = new PretestedIntegrationPreCheckout.DescriptorImpl(); // File tmp = createTempDirectory(); // boolean updateResult = descriptor.writeHook(tmp, "localhost:8080", "foo"); // assertTrue(updateResult); // //File repoDir = new File(tmp,".hg"); // File hook = new File(tmp, "hg_changegroup_hook.py"); // assertTrue(hook.exists()); // //Check stuff about the contents of the hook file maybe? // } // // public void testShouldFailUpdateHookDirNotExists() throws Exception { // PretestedIntegrationPreCheckout.DescriptorImpl descriptor = spy(new PretestedIntegrationPreCheckout.DescriptorImpl()); // // File tmp = getTempFile(); // // try{ // boolean updateResult = descriptor.writeHook(tmp, "localhost:8080", "foo"); // fail("IOException expected. updateResult: " + updateResult); // } catch (IOException e){ // // } // // File hook = new File(tmp, "hg_changegroup_hook.py"); // assertFalse(hook.exists()); // // } // // public void testShouldFailUpdateHookDirNotWritable() throws Exception { // PretestedIntegrationPreCheckout.DescriptorImpl descriptor = spy(new PretestedIntegrationPreCheckout.DescriptorImpl()); // // File tmp = getTempFile(); // tmp.mkdirs(); // tmp.setWritable(false); // // try{ // boolean updateResult = descriptor.writeHook(tmp, "localhost:8080", "foo"); // fail("IOException expected. updateResult: " + updateResult); // } catch (IOException e){ // // } // // File hook = new File(tmp, "hg_changegroup_hook.py"); // assertFalse(hook.exists()); // tmp.setWritable(true); // } // // public void testShouldFailUpdateHookFileNotWritable() throws Exception { // PretestedIntegrationPreCheckout.DescriptorImpl descriptor = spy(new PretestedIntegrationPreCheckout.DescriptorImpl()); // // File tmp = getTempFile(); // tmp.mkdirs(); // File hook = new File(tmp, "hg_changegroup_hook.py"); // // hook.setWritable(false); // // try{ // boolean updateResult = descriptor.writeHook(hook, "localhost:8080", "foo"); // fail("IOException expected. updateResult: " + updateResult); // } catch (IOException e){ // // } // // assertFalse(hook.exists()); // hook.setWritable(true); // } // /* public void testShouldConfigureStageRepository() throws Exception { File tmp = setup(); //Given a valid hg directory String path = tmp.getAbsolutePath(); hg("init", path); //When the doUpdateRepository method is invoked PretestedIntegrationPreCheckout buildWrapper = new PretestedIntegrationPreCheckout(tmp.getAbsolutePath()); PretestedIntegrationPreCheckout.DescriptorImpl mockedDescriptor = mock(PretestedIntegrationPreCheckout.DescriptorImpl.class); // (PretestedIntegrationPreCheckout.DescriptorImpl) buildWrapper.getDescriptor(); when(mockedDescriptor.getJenkinsRootUrl()).thenReturn("localhost:8080"); FormValidation response = mockedDescriptor.doUpdateRepository(tmp.getAbsolutePath(), ""); //Then a valid staging repository should be configured assertEquals(mockedDescriptor.getJenkinsRootUrl(), "localhost:8080"); assertNotNull(); //assertSame(response.kind,FormValidation.Kind.OK); assertTrue(mockedDescriptor.validateConfiguration(path)); //Todo - check the actual state }*/ }
true
true
public void testShouldCreateInstance() throws Exception { Constructor <?> c = PretestedIntegrationPreCheckout.class .getConstructor(String.class); Object inst = c.newInstance(); assertNotNull(inst); }
public void testShouldCreateInstance() throws Exception { Constructor <?> c = PretestedIntegrationPreCheckout.class .getConstructor(); Object inst = c.newInstance(); assertNotNull(inst); }
diff --git a/src/main/java/net/aufdemrand/denizen/objects/dLocation.java b/src/main/java/net/aufdemrand/denizen/objects/dLocation.java index 71007c272..d6b058fe9 100644 --- a/src/main/java/net/aufdemrand/denizen/objects/dLocation.java +++ b/src/main/java/net/aufdemrand/denizen/objects/dLocation.java @@ -1,1042 +1,1042 @@ package net.aufdemrand.denizen.objects; import net.aufdemrand.denizen.objects.dPlayer; import net.aufdemrand.denizen.tags.Attribute; import net.aufdemrand.denizen.utilities.DenizenAPI; import net.aufdemrand.denizen.utilities.Utilities; import net.aufdemrand.denizen.utilities.debugging.dB; import net.aufdemrand.denizen.utilities.depends.Depends; import net.aufdemrand.denizen.utilities.depends.WorldGuardUtilities; import net.aufdemrand.denizen.utilities.entity.Rotation; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.inventory.InventoryHolder; import org.bukkit.World; import org.bukkit.block.Sign; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class dLocation extends org.bukkit.Location implements dObject { // This pattern correctly reads both 0.9 and 0.8 notables final static Pattern notablePattern = Pattern.compile("(\\w+)[;,]((-?\\d+\\.?\\d*,){3,5}\\w+)", Pattern.CASE_INSENSITIVE); ///////////////////// // STATIC METHODS ///////////////// public static Map<String, dLocation> uniqueObjects = new HashMap<String, dLocation>(); public static boolean isSaved(String id) { return uniqueObjects.containsKey(id.toUpperCase()); } public static boolean isSaved(dLocation location) { return uniqueObjects.containsValue(location); } public static boolean isSaved(Location location) { for (Map.Entry<String, dLocation> i : uniqueObjects.entrySet()) if (i.getValue() == location) return true; return uniqueObjects.containsValue(location); } public static dLocation getSaved(String id) { if (uniqueObjects.containsKey(id.toUpperCase())) return uniqueObjects.get(id.toUpperCase()); else return null; } public static String getSaved(dLocation location) { for (Map.Entry<String, dLocation> i : uniqueObjects.entrySet()) { if (i.getValue().getBlockX() != location.getBlockX()) continue; if (i.getValue().getBlockY() != location.getBlockY()) continue; if (i.getValue().getBlockZ() != location.getBlockZ()) continue; if (!i.getValue().getWorld().getName().equals(location.getWorld().getName())) continue; return i.getKey(); } return null; } public static String getSaved(Location location) { dLocation dLoc = new dLocation(location); return getSaved(dLoc); } public static void saveAs(dLocation location, String id) { if (location == null) return; uniqueObjects.put(id.toUpperCase(), location); } public static void remove(String id) { uniqueObjects.remove(id.toUpperCase()); } /* * Called on server startup or /denizen reload locations. Should probably not be called manually. */ public static void _recallLocations() { List<String> loclist = DenizenAPI.getCurrentInstance().getSaves().getStringList("dScript.Locations"); uniqueObjects.clear(); for (String location : loclist) { Matcher m = notablePattern.matcher(location); if (m.matches()) { String id = m.group(1); dLocation loc = valueOf(m.group(2)); uniqueObjects.put(id, loc); } } } /* * Called by Denizen internally on a server shutdown or /denizen save. Should probably * not be called manually. */ public static void _saveLocations() { List<String> loclist = new ArrayList<String>(); for (Map.Entry<String, dLocation> entry : uniqueObjects.entrySet()) // Save locations in the horizontal centers of blocks loclist.add(entry.getKey() + ";" + (entry.getValue().getBlockX() + 0.5) + "," + entry.getValue().getBlockY() + "," + (entry.getValue().getBlockZ() + 0.5) + "," + entry.getValue().getYaw() + "," + entry.getValue().getPitch() + "," + entry.getValue().getWorld().getName()); DenizenAPI.getCurrentInstance().getSaves().set("dScript.Locations", loclist); } ////////////////// // OBJECT FETCHER //////////////// /** * Gets a Location Object from a string form of id,x,y,z,world * or a dScript argument (location:)x,y,z,world. If including an Id, * this location will persist and can be recalled at any time. * * @param string the string or dScript argument String * @return a Location, or null if incorrectly formatted * */ @ObjectFetcher("l") public static dLocation valueOf(String string) { if (string == null) return null; //////// // Match @object format for saved dLocations Matcher m; final Pattern item_by_saved = Pattern.compile("(l@)(.+)"); m = item_by_saved.matcher(string); if (m.matches() && isSaved(m.group(2))) return getSaved(m.group(2)); //////// // Match location formats // Split values String[] split = string.replace("l@", "").split(","); if (split.length == 4) // If 4 values, standard dScript location format // x,y,z,world try { return new dLocation(Bukkit.getWorld(split[3]), Double.valueOf(split[0]), Double.valueOf(split[1]), Double.valueOf(split[2])); } catch(Exception e) { return null; } else if (split.length == 6) // If 6 values, location with pitch/yaw // x,y,z,yaw,pitch,world try { return new dLocation(Bukkit.getWorld(split[5]), Double.valueOf(split[0]), Double.valueOf(split[1]), Double.valueOf(split[2]), Float.valueOf(split[3]), Float.valueOf(split[4])); } catch(Exception e) { return null; } dB.log("valueOf dLocation returning null: " + string); return null; } public static boolean matches(String string) { final Pattern location_by_saved = Pattern.compile("(l@)(.+)"); Matcher m = location_by_saved.matcher(string); if (m.matches()) return true; final Pattern location = Pattern.compile("(-?\\d+\\.?\\d*,){3,5}\\w+", Pattern.CASE_INSENSITIVE); m = location.matcher(string); return m.matches(); } /** * Turns a Bukkit Location into a Location, which has some helpful methods * for working with dScript. * * @param location the Bukkit Location to reference */ public dLocation(Location location) { // Just save the yaw and pitch as they are; don't check if they are // higher than 0, because Minecraft yaws are weird and can have // negative values super(location.getWorld(), location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch()); } /** * Turns a world and coordinates into a Location, which has some helpful methods * for working with dScript. If working with temporary locations, this is * a much better method to use than {@link #dLocation(org.bukkit.World, double, double, double)}. * * @param world the world in which the location resides * @param x x-coordinate of the location * @param y y-coordinate of the location * @param z z-coordinate of the location * */ public dLocation(World world, double x, double y, double z) { super(world, x, y, z); } public dLocation(World world, double x, double y, double z, float yaw, float pitch) { super(world, x, y, z, pitch, yaw); } @Override public void setPitch(float pitch) { super.setPitch(pitch); } @Override public void setYaw(float yaw) { super.setYaw(yaw); } public dLocation rememberAs(String id) { dLocation.saveAs(this, id); return this; } String prefix = "Location"; @Override public String getObjectType() { return "Location"; } @Override public String getPrefix() { return prefix; } @Override public dLocation setPrefix(String prefix) { this.prefix = prefix; return this; } @Override public String debug() { return (isSaved(this) ? "<G>" + prefix + "='<A>" + getSaved(this) + "(<Y>" + identify()+ "<A>)<G>' " : "<G>" + prefix + "='<Y>" + identify() + "<G>' "); } @Override public boolean isUnique() { return isSaved(this); } @Override public String identify() { if (isSaved(this)) return "l@" + getSaved(this); else if (getYaw() != 0.0 && getPitch() != 0.0) return "l@" + getX() + "," + getY() + "," + getZ() + "," + getPitch() + "," + getYaw() + "," + getWorld().getName(); else return "l@" + getX() + "," + getY() + "," + getZ() + "," + getWorld().getName(); } @Override public String toString() { return identify(); } @Override public String getAttribute(Attribute attribute) { if (attribute == null) return null; // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns the formatted biome name at the location. // --> if (attribute.startsWith("biome.formatted")) return new Element(getBlock().getBiome().name().toLowerCase().replace('_', ' ')) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the current humidity at the location. // --> if (attribute.startsWith("biome.humidity")) return new Element(getBlock().getHumidity()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the current temperature at the location. // --> if (attribute.startsWith("biome.temperature")) return new Element(getBlock().getTemperature()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns the biome name at the location. // --> if (attribute.startsWith("biome")) return new Element(getBlock().getBiome().name()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns dLocation // @description // Returns the location of the block below the location. // --> if (attribute.startsWith("block.below")) return new dLocation(this.add(0,-1,0)) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns dLocation // @description // Returns the location of the block above the location. // --> if (attribute.startsWith("block.above")) return new dLocation(this.add(0,1,0)) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected][x,y,z]> // @returns dLocation // @description // Returns the location with the specified coordinates added to it. // --> if (attribute.startsWith("add")) { if (attribute.hasContext(1) && attribute.getContext(1).split(",").length == 3) { String[] ints = attribute.getContext(1).split(",", 3); if ((aH.matchesDouble(ints[0]) || aH.matchesInteger(ints[0])) && (aH.matchesDouble(ints[1]) || aH.matchesInteger(ints[1])) && (aH.matchesDouble(ints[2]) || aH.matchesInteger(ints[2]))) { return new dLocation(this.clone().add(Double.valueOf(ints[0]), Double.valueOf(ints[1]), Double.valueOf(ints[2]))).getAttribute(attribute.fulfill(1)); } } } // <--[tag] // @attribute <[email protected]_pose[<entity>/<yaw>,<pitch>]> // @returns dLocation // @description // Returns the location with pitch and yaw. // --> if (attribute.startsWith("with_pose")) { String context = attribute.getContext(1); Float pitch = 0f; Float yaw = 0f; if (dEntity.matches(context)) { dEntity ent = dEntity.valueOf(context); if (ent.isSpawned()) { pitch = ent.getBukkitEntity().getLocation().getPitch(); yaw = ent.getBukkitEntity().getLocation().getYaw(); } } else if (context.split(",").length == 2) { String[] split = context.split(","); pitch = Float.valueOf(split[0]); yaw = Float.valueOf(split[1]); } dLocation loc = dLocation.valueOf(identify()); loc.setPitch(pitch); loc.setYaw(yaw); return loc.getAttribute(attribute.fulfill(1)); } if (attribute.startsWith("find") || attribute.startsWith("nearest")) { attribute.fulfill(1); // <--[tag] // @attribute <[email protected][<block>|...].within[X]> // @returns dList // @description // Returns a list of matching blocks within a radius. // --> if (attribute.startsWith("blocks") && attribute.getAttribute(2).startsWith("within") && attribute.hasContext(2)) { ArrayList<dLocation> found = new ArrayList<dLocation>(); int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10; List<dObject> materials = new ArrayList<dObject>(); if (attribute.hasContext(1)) materials = dList.valueOf(attribute.getContext(1)).filter(dMaterial.class); // dB.log(materials + " " + radius + " "); attribute.fulfill(2); for (int x = -(radius); x <= radius; x++) for (int y = -(radius); y <= radius; y++) for (int z = -(radius); z <= radius; z++) if (!materials.isEmpty()) { for (dObject material : materials) if (((dMaterial) material).matchesMaterialData(getBlock() .getRelative(x,y,z).getType().getNewData(getBlock() .getRelative(x,y,z).getData()))) found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation())); } else found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation())); Collections.sort(found, new Comparator<dLocation>() { @Override public int compare(dLocation loc1, dLocation loc2) { return (int) (distanceSquared(loc1) - distanceSquared(loc2)); } }); return new dList(found).getAttribute(attribute); } // <--[tag] // @attribute <[email protected]_blocks[<block>|...].within[X]> // @returns dList // @description // Returns a list of matching surface blocks within a radius. // --> else if (attribute.startsWith("surface_blocks") && attribute.getAttribute(2).startsWith("within") && attribute.hasContext(2)) { ArrayList<dLocation> found = new ArrayList<dLocation>(); int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10; List<dObject> materials = new ArrayList<dObject>(); if (attribute.hasContext(1)) materials = dList.valueOf(attribute.getContext(1)).filter(dMaterial.class); attribute.fulfill(2); for (int x = -(radius); x <= radius; x++) for (int y = -(radius); y <= radius; y++) for (int z = -(radius); z <= radius; z++) if (!materials.isEmpty()) { for (dObject material : materials) if (((dMaterial) material).matchesMaterialData(getBlock() .getRelative(x,y,z).getType().getNewData(getBlock() .getRelative(x,y,z).getData()))) { Location l = getBlock().getRelative(x,y,z).getLocation(); if (l.add(0,1,0).getBlock().getType() == Material.AIR && l.add(0,1,0).getBlock().getType() == Material.AIR) found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation())); } } else { Location l = getBlock().getRelative(x,y,z).getLocation(); if (l.add(0,1,0).getBlock().getType() == Material.AIR && l.add(0,1,0).getBlock().getType() == Material.AIR) found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation())); } Collections.sort(found, new Comparator<dLocation>() { @Override public int compare(dLocation loc1, dLocation loc2) { return (int) (distanceSquared(loc1) - distanceSquared(loc2)); } }); return new dList(found).getAttribute(attribute); } // <--[tag] // @attribute <[email protected][X]> // @returns dList // @description // Returns a list of players within a radius. // --> else if (attribute.startsWith("players") && attribute.getAttribute(2).startsWith("within") && attribute.hasContext(2)) { ArrayList<dPlayer> found = new ArrayList<dPlayer>(); int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10; attribute.fulfill(2); for (Player player : Bukkit.getOnlinePlayers()) if (!player.isDead() && Utilities.checkLocation(this, player.getLocation(), radius)) found.add(new dPlayer(player)); Collections.sort(found, new Comparator<dPlayer>() { @Override public int compare(dPlayer pl1, dPlayer pl2) { return (int) (distanceSquared(pl1.getLocation()) - distanceSquared(pl2.getLocation())); } }); return new dList(found).getAttribute(attribute); } // <--[tag] // @attribute <[email protected][X]> // @returns dList // @description // Returns a list of NPCs within a radius. // --> else if (attribute.startsWith("npcs") && attribute.getAttribute(2).startsWith("within") && attribute.hasContext(2)) { ArrayList<dNPC> found = new ArrayList<dNPC>(); int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10; attribute.fulfill(2); for (dNPC npc : DenizenAPI.getSpawnedNPCs()) if (Utilities.checkLocation(this, npc.getLocation(), radius)) found.add(npc); Collections.sort(found, new Comparator<dNPC>() { @Override public int compare(dNPC npc1, dNPC npc2) { return (int) (distanceSquared(npc1.getLocation()) - distanceSquared(npc2.getLocation())); } }); return new dList(found).getAttribute(attribute); } // <--[tag] // @attribute <[email protected][X]> // @returns dList // @description // Returns a list of entities within a radius. // --> else if (attribute.startsWith("entities") && attribute.getAttribute(2).startsWith("within") && attribute.hasContext(2)) { ArrayList<dEntity> found = new ArrayList<dEntity>(); int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10; attribute.fulfill(2); for (Entity entity : getWorld().getEntities()) if (Utilities.checkLocation(this, entity.getLocation(), radius)) found.add(new dEntity(entity)); Collections.sort(found, new Comparator<dEntity>() { @Override public int compare(dEntity ent1, dEntity ent2) { return (int) (distanceSquared(ent1.getBukkitEntity().getLocation()) - distanceSquared(ent2.getBukkitEntity().getLocation())); } }); return new dList(found).getAttribute(attribute); } // <--[tag] // @attribute <[email protected]_entities.within[X]> // @returns dList // @description // Returns a list of living entities within a radius. // --> else if (attribute.startsWith("living_entities") && attribute.getAttribute(2).startsWith("within") && attribute.hasContext(2)) { ArrayList<dEntity> found = new ArrayList<dEntity>(); int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10; attribute.fulfill(2); for (Entity entity : getWorld().getEntities()) if (entity instanceof LivingEntity && Utilities.checkLocation(this, entity.getLocation(), radius)) found.add(new dEntity(entity)); Collections.sort(found, new Comparator<dEntity>() { @Override public int compare(dEntity ent1, dEntity ent2) { return (int) (distanceSquared(ent1.getBukkitEntity().getLocation()) - distanceSquared(ent2.getBukkitEntity().getLocation())); } }); return new dList(found).getAttribute(attribute); } return new Element("null").getAttribute(attribute); } // <--[tag] // @attribute <[email protected]> // @returns dInventory // @description // Returns the dInventory of the block at the location. If the // block is not a container, returns null. // --> if (attribute.startsWith("inventory")) { if (getBlock().getState() instanceof InventoryHolder) return new dInventory(getBlock().getState()).getAttribute(attribute.fulfill(1)); return new Element("null").getAttribute(attribute); } // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns the Bukkit material name of the block at the location. // --> if (attribute.startsWith("block.material")) return dMaterial.getMaterialFrom(getBlock().getType(), getBlock().getData()).getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns dLocation // @description // Returns the location's direction as a one-length vector. // --> if (attribute.startsWith("direction.vector")) { double xzLen = Math.cos((getPitch() % 360) * (Math.PI/180)); double nx = xzLen * Math.cos(getYaw() * (Math.PI/180)); double ny = Math.sin(getPitch() * (Math.PI/180)); double nz = xzLen * Math.sin(-getYaw() * (Math.PI/180)); return new dLocation(getWorld(), -nx, -ny, nz).getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected][<location>]> // @returns Element // @description // Returns the compass direction between two locations. // If no second location is specified, returns the direction of the location. // --> if (attribute.startsWith("direction")) { // Get the cardinal direction from this location to another if (attribute.hasContext(1) && dLocation.matches(attribute.getContext(1))) { // Subtract this location's vector from the other location's vector, // not the other way around return new Element(Rotation.getCardinal(Rotation.getYaw (dLocation.valueOf(attribute.getContext(1)).toVector().subtract(this.toVector()) .normalize()))) .getAttribute(attribute.fulfill(1)); } // Get a cardinal direction from this location's yaw else { return new Element(Rotation.getCardinal(getYaw())) .getAttribute(attribute.fulfill(1)); } } // <--[tag] // @attribute <[email protected][<location>]> // @returns Element(Number) // @description // Returns the distance between 2 locations. // --> if (attribute.startsWith("distance")) { if (attribute.hasContext(1) && dLocation.matches(attribute.getContext(1))) { dLocation toLocation = dLocation.valueOf(attribute.getContext(1)); // <--[tag] // @attribute <[email protected][<location>].horizontal> // @returns Element(Number) // @description // Returns the horizontal distance between 2 locations. // --> if (attribute.getAttribute(2).startsWith("horizontal")) { // <--[tag] // @attribute <[email protected][<location>].horizontal.multiworld> // @returns Element(Number) // @description // Returns the horizontal distance between 2 multiworld locations. // --> if (attribute.getAttribute(3).startsWith("multiworld")) return new Element(Math.sqrt( Math.pow(this.getX() - toLocation.getX(), 2) + Math.pow(this.getZ() - toLocation.getZ(), 2))) .getAttribute(attribute.fulfill(3)); else if (this.getWorld() == toLocation.getWorld()) return new Element(Math.sqrt( Math.pow(this.getX() - toLocation.getX(), 2) + Math.pow(this.getZ() - toLocation.getZ(), 2))) .getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected][<location>].vertical> // @returns Element(Number) // @description // Returns the vertical distance between 2 locations. // --> else if (attribute.getAttribute(2).startsWith("vertical")) { // <--[tag] // @attribute <[email protected][<location>].vertical.multiworld> // @returns Element(Number) // @description // Returns the vertical distance between 2 multiworld locations. // --> if (attribute.getAttribute(3).startsWith("multiworld")) return new Element(Math.abs(this.getY() - toLocation.getY())) .getAttribute(attribute.fulfill(3)); else if (this.getWorld() == toLocation.getWorld()) return new Element(Math.abs(this.getY() - toLocation.getY())) .getAttribute(attribute.fulfill(2)); } else return new Element(this.distance(toLocation)) .getAttribute(attribute.fulfill(1)); } } // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns a simple formatted version of the dLocation. // EG: x,y,z,world // --> if (attribute.startsWith("simple")) return new Element(getBlockX() + "," + getBlockY() + "," + getBlockZ() + "," + getWorld().getName()).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns the formatted simple version of the dLocation. // EG: X 'x', Y 'y', Z 'z', in world 'world' // --> if (attribute.startsWith("formatted.simple")) return new Element("X '" + getBlockX() + "', Y '" + getBlockY() + "', Z '" + getBlockZ() + "', in world '" + getWorld().getName() + "'").getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns the formatted version of the dLocation. // EG: 'X 'x.x', Y 'y.y', Z 'z.z', in world 'world' // --> if (attribute.startsWith("formatted")) return new Element("X '" + getX() + "', Y '" + getY() + "', Z '" + getZ() + "', in world '" + getWorld().getName() + "'").getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_liquid> // @returns Element(Boolean) // @description // Returns whether block at the location is a liquid. // --> if (attribute.startsWith("is_liquid")) return new Element(getBlock().isLiquid()).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the amount of light from light blocks that is // on the location. // --> if (attribute.startsWith("light.from_blocks") || attribute.startsWith("light.blocks")) return new Element(getBlock().getLightFromBlocks()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the amount of light from the sky that is // on the location. // --> if (attribute.startsWith("light.from_sky") || attribute.startsWith("light.sky")) return new Element(getBlock().getLightFromSky()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the total amount of light on the location. // --> if (attribute.startsWith("light")) return new Element(getBlock().getLightLevel()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the pitch of the object at the location. // --> if (attribute.startsWith("pitch")) { return new Element(getPitch()).getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the raw yaw of the object at the location. // --> if (attribute.startsWith("yaw.raw")) { return new Element(getYaw()) .getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the normalized yaw of the object at the location. // --> if (attribute.startsWith("yaw")) { return new Element(Rotation.normalizeYaw(getYaw())) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected][<entity>/<location>]> // @returns Element(Boolean) // @description // Returns whether the location's yaw is facing another // entity or location. // --> if (attribute.startsWith("facing")) { if (attribute.hasContext(1)) { // The default number of degrees if there is no degrees attribute int degrees = 45; // The attribute to fulfill from int attributePos = 1; // <--[tag] // @attribute <location.facing[<entity>/<location>].degrees[X]> // @returns Element(Boolean) // @description // Returns whether the location's yaw is facing another // entity or location, within a specified degree range. // --> if (attribute.getAttribute(2).startsWith("degrees") && attribute.hasContext(2) && aH.matchesInteger(attribute.getContext(2))) { degrees = attribute.getIntContext(2); attributePos++; } if (dLocation.matches(attribute.getContext(1))) { return new Element(Rotation.isFacingLocation (this, dLocation.valueOf(attribute.getContext(1)), degrees)) .getAttribute(attribute.fulfill(attributePos)); } else if (dEntity.matches(attribute.getContext(1))) { return new Element(Rotation.isFacingLocation (this, dEntity.valueOf(attribute.getContext(1)) .getBukkitEntity().getLocation(), degrees)) .getAttribute(attribute.fulfill(attributePos)); } } } // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the current redstone power level of a block. // --> if (attribute.startsWith("power")) return new Element(getBlock().getBlockPower()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_region[<name>|...]> // @returns Element(Boolean) // @description // If a region name or list of names is specified, returns whether the // location is in one of the listed regions, otherwise returns whether // the location is in any region. // --> if (attribute.startsWith("in_region")) { if (Depends.worldGuard == null) { dB.echoError("Cannot check region! WorldGuard is not loaded!"); return null; } // Check if the player is in the specified region if (attribute.hasContext(1)) { dList region_list = dList.valueOf(attribute.getContext(1)); for(String region: region_list) if(WorldGuardUtilities.inRegion(this, region)) return Element.TRUE.getAttribute(attribute.fulfill(1)); return Element.FALSE.getAttribute(attribute.fulfill(1)); } // Check if the player is in any region else { return new Element(WorldGuardUtilities.inRegion(this)) .getAttribute(attribute.fulfill(1)); } } // <--[tag] // @attribute <[email protected]> // @returns dList // @description // Returns a list of regions that the location is in. // --> if (attribute.startsWith("regions")) { if (Depends.worldGuard == null) { dB.echoError("Cannot check region! WorldGuard is not loaded!"); return null; } return new dList(WorldGuardUtilities.getRegions(this)) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns dWorld // @description // Returns the world that the location is in. // --> if (attribute.startsWith("world")) { return dWorld.mirrorBukkitWorld(getWorld()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <location.block.x> // @returns Element(Number) // @description // Returns the X coordinate of the block. // --> if (attribute.startsWith("block.x")) { return new Element(getBlockX()).getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the Y coordinate of the block. // --> if (attribute.startsWith("block.y")) { return new Element(getBlockY()).getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the Z coordinate of the block. // --> if (attribute.startsWith("block.z")) { return new Element(getBlockZ()).getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the X coordinate of the location. // --> if (attribute.startsWith("x")) { return new Element(getX()).getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the Y coordinate of the location. // --> if (attribute.startsWith("y")) { return new Element(getY()).getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the Z coordinate of the location. // --> if (attribute.startsWith("z")) { return new Element(getZ()).getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_contents> // @returns dList // @description // Returns a list of lines on a sign. // --> if (attribute.startsWith("block.sign_contents")) { if (getBlock().getState() instanceof Sign) { return new dList(Arrays.asList(((Sign) getBlock().getState()).getLines())) .getAttribute(attribute.fulfill(2)); } else return "null"; } // <--[tag] // @attribute <[email protected]> // @returns dLocation // @description - // Returns the location of the highest block at the location that isn't air. + // Returns the location of the highest block at the location that isn't solid. // --> if (attribute.startsWith("highest")) { - return new dLocation(getWorld().getHighestBlockAt(this).getLocation()) + return new dLocation(getWorld().getHighestBlockAt(this).getLocation().add(0, -1, 0)) .getAttribute(attribute.fulfill(1)); } return new Element(identify()).getAttribute(attribute); } }
false
true
public String getAttribute(Attribute attribute) { if (attribute == null) return null; // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns the formatted biome name at the location. // --> if (attribute.startsWith("biome.formatted")) return new Element(getBlock().getBiome().name().toLowerCase().replace('_', ' ')) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the current humidity at the location. // --> if (attribute.startsWith("biome.humidity")) return new Element(getBlock().getHumidity()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the current temperature at the location. // --> if (attribute.startsWith("biome.temperature")) return new Element(getBlock().getTemperature()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns the biome name at the location. // --> if (attribute.startsWith("biome")) return new Element(getBlock().getBiome().name()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns dLocation // @description // Returns the location of the block below the location. // --> if (attribute.startsWith("block.below")) return new dLocation(this.add(0,-1,0)) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns dLocation // @description // Returns the location of the block above the location. // --> if (attribute.startsWith("block.above")) return new dLocation(this.add(0,1,0)) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected][x,y,z]> // @returns dLocation // @description // Returns the location with the specified coordinates added to it. // --> if (attribute.startsWith("add")) { if (attribute.hasContext(1) && attribute.getContext(1).split(",").length == 3) { String[] ints = attribute.getContext(1).split(",", 3); if ((aH.matchesDouble(ints[0]) || aH.matchesInteger(ints[0])) && (aH.matchesDouble(ints[1]) || aH.matchesInteger(ints[1])) && (aH.matchesDouble(ints[2]) || aH.matchesInteger(ints[2]))) { return new dLocation(this.clone().add(Double.valueOf(ints[0]), Double.valueOf(ints[1]), Double.valueOf(ints[2]))).getAttribute(attribute.fulfill(1)); } } } // <--[tag] // @attribute <[email protected]_pose[<entity>/<yaw>,<pitch>]> // @returns dLocation // @description // Returns the location with pitch and yaw. // --> if (attribute.startsWith("with_pose")) { String context = attribute.getContext(1); Float pitch = 0f; Float yaw = 0f; if (dEntity.matches(context)) { dEntity ent = dEntity.valueOf(context); if (ent.isSpawned()) { pitch = ent.getBukkitEntity().getLocation().getPitch(); yaw = ent.getBukkitEntity().getLocation().getYaw(); } } else if (context.split(",").length == 2) { String[] split = context.split(","); pitch = Float.valueOf(split[0]); yaw = Float.valueOf(split[1]); } dLocation loc = dLocation.valueOf(identify()); loc.setPitch(pitch); loc.setYaw(yaw); return loc.getAttribute(attribute.fulfill(1)); } if (attribute.startsWith("find") || attribute.startsWith("nearest")) { attribute.fulfill(1); // <--[tag] // @attribute <[email protected][<block>|...].within[X]> // @returns dList // @description // Returns a list of matching blocks within a radius. // --> if (attribute.startsWith("blocks") && attribute.getAttribute(2).startsWith("within") && attribute.hasContext(2)) { ArrayList<dLocation> found = new ArrayList<dLocation>(); int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10; List<dObject> materials = new ArrayList<dObject>(); if (attribute.hasContext(1)) materials = dList.valueOf(attribute.getContext(1)).filter(dMaterial.class); // dB.log(materials + " " + radius + " "); attribute.fulfill(2); for (int x = -(radius); x <= radius; x++) for (int y = -(radius); y <= radius; y++) for (int z = -(radius); z <= radius; z++) if (!materials.isEmpty()) { for (dObject material : materials) if (((dMaterial) material).matchesMaterialData(getBlock() .getRelative(x,y,z).getType().getNewData(getBlock() .getRelative(x,y,z).getData()))) found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation())); } else found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation())); Collections.sort(found, new Comparator<dLocation>() { @Override public int compare(dLocation loc1, dLocation loc2) { return (int) (distanceSquared(loc1) - distanceSquared(loc2)); } }); return new dList(found).getAttribute(attribute); } // <--[tag] // @attribute <[email protected]_blocks[<block>|...].within[X]> // @returns dList // @description // Returns a list of matching surface blocks within a radius. // --> else if (attribute.startsWith("surface_blocks") && attribute.getAttribute(2).startsWith("within") && attribute.hasContext(2)) { ArrayList<dLocation> found = new ArrayList<dLocation>(); int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10; List<dObject> materials = new ArrayList<dObject>(); if (attribute.hasContext(1)) materials = dList.valueOf(attribute.getContext(1)).filter(dMaterial.class); attribute.fulfill(2); for (int x = -(radius); x <= radius; x++) for (int y = -(radius); y <= radius; y++) for (int z = -(radius); z <= radius; z++) if (!materials.isEmpty()) { for (dObject material : materials) if (((dMaterial) material).matchesMaterialData(getBlock() .getRelative(x,y,z).getType().getNewData(getBlock() .getRelative(x,y,z).getData()))) { Location l = getBlock().getRelative(x,y,z).getLocation(); if (l.add(0,1,0).getBlock().getType() == Material.AIR && l.add(0,1,0).getBlock().getType() == Material.AIR) found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation())); } } else { Location l = getBlock().getRelative(x,y,z).getLocation(); if (l.add(0,1,0).getBlock().getType() == Material.AIR && l.add(0,1,0).getBlock().getType() == Material.AIR) found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation())); } Collections.sort(found, new Comparator<dLocation>() { @Override public int compare(dLocation loc1, dLocation loc2) { return (int) (distanceSquared(loc1) - distanceSquared(loc2)); } }); return new dList(found).getAttribute(attribute); } // <--[tag] // @attribute <[email protected][X]> // @returns dList // @description // Returns a list of players within a radius. // --> else if (attribute.startsWith("players") && attribute.getAttribute(2).startsWith("within") && attribute.hasContext(2)) { ArrayList<dPlayer> found = new ArrayList<dPlayer>(); int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10; attribute.fulfill(2); for (Player player : Bukkit.getOnlinePlayers()) if (!player.isDead() && Utilities.checkLocation(this, player.getLocation(), radius)) found.add(new dPlayer(player)); Collections.sort(found, new Comparator<dPlayer>() { @Override public int compare(dPlayer pl1, dPlayer pl2) { return (int) (distanceSquared(pl1.getLocation()) - distanceSquared(pl2.getLocation())); } }); return new dList(found).getAttribute(attribute); } // <--[tag] // @attribute <[email protected][X]> // @returns dList // @description // Returns a list of NPCs within a radius. // --> else if (attribute.startsWith("npcs") && attribute.getAttribute(2).startsWith("within") && attribute.hasContext(2)) { ArrayList<dNPC> found = new ArrayList<dNPC>(); int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10; attribute.fulfill(2); for (dNPC npc : DenizenAPI.getSpawnedNPCs()) if (Utilities.checkLocation(this, npc.getLocation(), radius)) found.add(npc); Collections.sort(found, new Comparator<dNPC>() { @Override public int compare(dNPC npc1, dNPC npc2) { return (int) (distanceSquared(npc1.getLocation()) - distanceSquared(npc2.getLocation())); } }); return new dList(found).getAttribute(attribute); } // <--[tag] // @attribute <[email protected][X]> // @returns dList // @description // Returns a list of entities within a radius. // --> else if (attribute.startsWith("entities") && attribute.getAttribute(2).startsWith("within") && attribute.hasContext(2)) { ArrayList<dEntity> found = new ArrayList<dEntity>(); int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10; attribute.fulfill(2); for (Entity entity : getWorld().getEntities()) if (Utilities.checkLocation(this, entity.getLocation(), radius)) found.add(new dEntity(entity)); Collections.sort(found, new Comparator<dEntity>() { @Override public int compare(dEntity ent1, dEntity ent2) { return (int) (distanceSquared(ent1.getBukkitEntity().getLocation()) - distanceSquared(ent2.getBukkitEntity().getLocation())); } }); return new dList(found).getAttribute(attribute); } // <--[tag] // @attribute <[email protected]_entities.within[X]> // @returns dList // @description // Returns a list of living entities within a radius. // --> else if (attribute.startsWith("living_entities") && attribute.getAttribute(2).startsWith("within") && attribute.hasContext(2)) { ArrayList<dEntity> found = new ArrayList<dEntity>(); int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10; attribute.fulfill(2); for (Entity entity : getWorld().getEntities()) if (entity instanceof LivingEntity && Utilities.checkLocation(this, entity.getLocation(), radius)) found.add(new dEntity(entity)); Collections.sort(found, new Comparator<dEntity>() { @Override public int compare(dEntity ent1, dEntity ent2) { return (int) (distanceSquared(ent1.getBukkitEntity().getLocation()) - distanceSquared(ent2.getBukkitEntity().getLocation())); } }); return new dList(found).getAttribute(attribute); } return new Element("null").getAttribute(attribute); } // <--[tag] // @attribute <[email protected]> // @returns dInventory // @description // Returns the dInventory of the block at the location. If the // block is not a container, returns null. // --> if (attribute.startsWith("inventory")) { if (getBlock().getState() instanceof InventoryHolder) return new dInventory(getBlock().getState()).getAttribute(attribute.fulfill(1)); return new Element("null").getAttribute(attribute); } // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns the Bukkit material name of the block at the location. // --> if (attribute.startsWith("block.material")) return dMaterial.getMaterialFrom(getBlock().getType(), getBlock().getData()).getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns dLocation // @description // Returns the location's direction as a one-length vector. // --> if (attribute.startsWith("direction.vector")) { double xzLen = Math.cos((getPitch() % 360) * (Math.PI/180)); double nx = xzLen * Math.cos(getYaw() * (Math.PI/180)); double ny = Math.sin(getPitch() * (Math.PI/180)); double nz = xzLen * Math.sin(-getYaw() * (Math.PI/180)); return new dLocation(getWorld(), -nx, -ny, nz).getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected][<location>]> // @returns Element // @description // Returns the compass direction between two locations. // If no second location is specified, returns the direction of the location. // --> if (attribute.startsWith("direction")) { // Get the cardinal direction from this location to another if (attribute.hasContext(1) && dLocation.matches(attribute.getContext(1))) { // Subtract this location's vector from the other location's vector, // not the other way around return new Element(Rotation.getCardinal(Rotation.getYaw (dLocation.valueOf(attribute.getContext(1)).toVector().subtract(this.toVector()) .normalize()))) .getAttribute(attribute.fulfill(1)); } // Get a cardinal direction from this location's yaw else { return new Element(Rotation.getCardinal(getYaw())) .getAttribute(attribute.fulfill(1)); } } // <--[tag] // @attribute <[email protected][<location>]> // @returns Element(Number) // @description // Returns the distance between 2 locations. // --> if (attribute.startsWith("distance")) { if (attribute.hasContext(1) && dLocation.matches(attribute.getContext(1))) { dLocation toLocation = dLocation.valueOf(attribute.getContext(1)); // <--[tag] // @attribute <[email protected][<location>].horizontal> // @returns Element(Number) // @description // Returns the horizontal distance between 2 locations. // --> if (attribute.getAttribute(2).startsWith("horizontal")) { // <--[tag] // @attribute <[email protected][<location>].horizontal.multiworld> // @returns Element(Number) // @description // Returns the horizontal distance between 2 multiworld locations. // --> if (attribute.getAttribute(3).startsWith("multiworld")) return new Element(Math.sqrt( Math.pow(this.getX() - toLocation.getX(), 2) + Math.pow(this.getZ() - toLocation.getZ(), 2))) .getAttribute(attribute.fulfill(3)); else if (this.getWorld() == toLocation.getWorld()) return new Element(Math.sqrt( Math.pow(this.getX() - toLocation.getX(), 2) + Math.pow(this.getZ() - toLocation.getZ(), 2))) .getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected][<location>].vertical> // @returns Element(Number) // @description // Returns the vertical distance between 2 locations. // --> else if (attribute.getAttribute(2).startsWith("vertical")) { // <--[tag] // @attribute <[email protected][<location>].vertical.multiworld> // @returns Element(Number) // @description // Returns the vertical distance between 2 multiworld locations. // --> if (attribute.getAttribute(3).startsWith("multiworld")) return new Element(Math.abs(this.getY() - toLocation.getY())) .getAttribute(attribute.fulfill(3)); else if (this.getWorld() == toLocation.getWorld()) return new Element(Math.abs(this.getY() - toLocation.getY())) .getAttribute(attribute.fulfill(2)); } else return new Element(this.distance(toLocation)) .getAttribute(attribute.fulfill(1)); } } // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns a simple formatted version of the dLocation. // EG: x,y,z,world // --> if (attribute.startsWith("simple")) return new Element(getBlockX() + "," + getBlockY() + "," + getBlockZ() + "," + getWorld().getName()).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns the formatted simple version of the dLocation. // EG: X 'x', Y 'y', Z 'z', in world 'world' // --> if (attribute.startsWith("formatted.simple")) return new Element("X '" + getBlockX() + "', Y '" + getBlockY() + "', Z '" + getBlockZ() + "', in world '" + getWorld().getName() + "'").getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns the formatted version of the dLocation. // EG: 'X 'x.x', Y 'y.y', Z 'z.z', in world 'world' // --> if (attribute.startsWith("formatted")) return new Element("X '" + getX() + "', Y '" + getY() + "', Z '" + getZ() + "', in world '" + getWorld().getName() + "'").getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_liquid> // @returns Element(Boolean) // @description // Returns whether block at the location is a liquid. // --> if (attribute.startsWith("is_liquid")) return new Element(getBlock().isLiquid()).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the amount of light from light blocks that is // on the location. // --> if (attribute.startsWith("light.from_blocks") || attribute.startsWith("light.blocks")) return new Element(getBlock().getLightFromBlocks()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the amount of light from the sky that is // on the location. // --> if (attribute.startsWith("light.from_sky") || attribute.startsWith("light.sky")) return new Element(getBlock().getLightFromSky()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the total amount of light on the location. // --> if (attribute.startsWith("light")) return new Element(getBlock().getLightLevel()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the pitch of the object at the location. // --> if (attribute.startsWith("pitch")) { return new Element(getPitch()).getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the raw yaw of the object at the location. // --> if (attribute.startsWith("yaw.raw")) { return new Element(getYaw()) .getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the normalized yaw of the object at the location. // --> if (attribute.startsWith("yaw")) { return new Element(Rotation.normalizeYaw(getYaw())) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected][<entity>/<location>]> // @returns Element(Boolean) // @description // Returns whether the location's yaw is facing another // entity or location. // --> if (attribute.startsWith("facing")) { if (attribute.hasContext(1)) { // The default number of degrees if there is no degrees attribute int degrees = 45; // The attribute to fulfill from int attributePos = 1; // <--[tag] // @attribute <location.facing[<entity>/<location>].degrees[X]> // @returns Element(Boolean) // @description // Returns whether the location's yaw is facing another // entity or location, within a specified degree range. // --> if (attribute.getAttribute(2).startsWith("degrees") && attribute.hasContext(2) && aH.matchesInteger(attribute.getContext(2))) { degrees = attribute.getIntContext(2); attributePos++; } if (dLocation.matches(attribute.getContext(1))) { return new Element(Rotation.isFacingLocation (this, dLocation.valueOf(attribute.getContext(1)), degrees)) .getAttribute(attribute.fulfill(attributePos)); } else if (dEntity.matches(attribute.getContext(1))) { return new Element(Rotation.isFacingLocation (this, dEntity.valueOf(attribute.getContext(1)) .getBukkitEntity().getLocation(), degrees)) .getAttribute(attribute.fulfill(attributePos)); } } } // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the current redstone power level of a block. // --> if (attribute.startsWith("power")) return new Element(getBlock().getBlockPower()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_region[<name>|...]> // @returns Element(Boolean) // @description // If a region name or list of names is specified, returns whether the // location is in one of the listed regions, otherwise returns whether // the location is in any region. // --> if (attribute.startsWith("in_region")) { if (Depends.worldGuard == null) { dB.echoError("Cannot check region! WorldGuard is not loaded!"); return null; } // Check if the player is in the specified region if (attribute.hasContext(1)) { dList region_list = dList.valueOf(attribute.getContext(1)); for(String region: region_list) if(WorldGuardUtilities.inRegion(this, region)) return Element.TRUE.getAttribute(attribute.fulfill(1)); return Element.FALSE.getAttribute(attribute.fulfill(1)); } // Check if the player is in any region else { return new Element(WorldGuardUtilities.inRegion(this)) .getAttribute(attribute.fulfill(1)); } } // <--[tag] // @attribute <[email protected]> // @returns dList // @description // Returns a list of regions that the location is in. // --> if (attribute.startsWith("regions")) { if (Depends.worldGuard == null) { dB.echoError("Cannot check region! WorldGuard is not loaded!"); return null; } return new dList(WorldGuardUtilities.getRegions(this)) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns dWorld // @description // Returns the world that the location is in. // --> if (attribute.startsWith("world")) { return dWorld.mirrorBukkitWorld(getWorld()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <location.block.x> // @returns Element(Number) // @description // Returns the X coordinate of the block. // --> if (attribute.startsWith("block.x")) { return new Element(getBlockX()).getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the Y coordinate of the block. // --> if (attribute.startsWith("block.y")) { return new Element(getBlockY()).getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the Z coordinate of the block. // --> if (attribute.startsWith("block.z")) { return new Element(getBlockZ()).getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the X coordinate of the location. // --> if (attribute.startsWith("x")) { return new Element(getX()).getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the Y coordinate of the location. // --> if (attribute.startsWith("y")) { return new Element(getY()).getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the Z coordinate of the location. // --> if (attribute.startsWith("z")) { return new Element(getZ()).getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_contents> // @returns dList // @description // Returns a list of lines on a sign. // --> if (attribute.startsWith("block.sign_contents")) { if (getBlock().getState() instanceof Sign) { return new dList(Arrays.asList(((Sign) getBlock().getState()).getLines())) .getAttribute(attribute.fulfill(2)); } else return "null"; } // <--[tag] // @attribute <[email protected]> // @returns dLocation // @description // Returns the location of the highest block at the location that isn't air. // --> if (attribute.startsWith("highest")) { return new dLocation(getWorld().getHighestBlockAt(this).getLocation()) .getAttribute(attribute.fulfill(1)); } return new Element(identify()).getAttribute(attribute); }
public String getAttribute(Attribute attribute) { if (attribute == null) return null; // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns the formatted biome name at the location. // --> if (attribute.startsWith("biome.formatted")) return new Element(getBlock().getBiome().name().toLowerCase().replace('_', ' ')) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the current humidity at the location. // --> if (attribute.startsWith("biome.humidity")) return new Element(getBlock().getHumidity()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the current temperature at the location. // --> if (attribute.startsWith("biome.temperature")) return new Element(getBlock().getTemperature()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns the biome name at the location. // --> if (attribute.startsWith("biome")) return new Element(getBlock().getBiome().name()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns dLocation // @description // Returns the location of the block below the location. // --> if (attribute.startsWith("block.below")) return new dLocation(this.add(0,-1,0)) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns dLocation // @description // Returns the location of the block above the location. // --> if (attribute.startsWith("block.above")) return new dLocation(this.add(0,1,0)) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected][x,y,z]> // @returns dLocation // @description // Returns the location with the specified coordinates added to it. // --> if (attribute.startsWith("add")) { if (attribute.hasContext(1) && attribute.getContext(1).split(",").length == 3) { String[] ints = attribute.getContext(1).split(",", 3); if ((aH.matchesDouble(ints[0]) || aH.matchesInteger(ints[0])) && (aH.matchesDouble(ints[1]) || aH.matchesInteger(ints[1])) && (aH.matchesDouble(ints[2]) || aH.matchesInteger(ints[2]))) { return new dLocation(this.clone().add(Double.valueOf(ints[0]), Double.valueOf(ints[1]), Double.valueOf(ints[2]))).getAttribute(attribute.fulfill(1)); } } } // <--[tag] // @attribute <[email protected]_pose[<entity>/<yaw>,<pitch>]> // @returns dLocation // @description // Returns the location with pitch and yaw. // --> if (attribute.startsWith("with_pose")) { String context = attribute.getContext(1); Float pitch = 0f; Float yaw = 0f; if (dEntity.matches(context)) { dEntity ent = dEntity.valueOf(context); if (ent.isSpawned()) { pitch = ent.getBukkitEntity().getLocation().getPitch(); yaw = ent.getBukkitEntity().getLocation().getYaw(); } } else if (context.split(",").length == 2) { String[] split = context.split(","); pitch = Float.valueOf(split[0]); yaw = Float.valueOf(split[1]); } dLocation loc = dLocation.valueOf(identify()); loc.setPitch(pitch); loc.setYaw(yaw); return loc.getAttribute(attribute.fulfill(1)); } if (attribute.startsWith("find") || attribute.startsWith("nearest")) { attribute.fulfill(1); // <--[tag] // @attribute <[email protected][<block>|...].within[X]> // @returns dList // @description // Returns a list of matching blocks within a radius. // --> if (attribute.startsWith("blocks") && attribute.getAttribute(2).startsWith("within") && attribute.hasContext(2)) { ArrayList<dLocation> found = new ArrayList<dLocation>(); int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10; List<dObject> materials = new ArrayList<dObject>(); if (attribute.hasContext(1)) materials = dList.valueOf(attribute.getContext(1)).filter(dMaterial.class); // dB.log(materials + " " + radius + " "); attribute.fulfill(2); for (int x = -(radius); x <= radius; x++) for (int y = -(radius); y <= radius; y++) for (int z = -(radius); z <= radius; z++) if (!materials.isEmpty()) { for (dObject material : materials) if (((dMaterial) material).matchesMaterialData(getBlock() .getRelative(x,y,z).getType().getNewData(getBlock() .getRelative(x,y,z).getData()))) found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation())); } else found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation())); Collections.sort(found, new Comparator<dLocation>() { @Override public int compare(dLocation loc1, dLocation loc2) { return (int) (distanceSquared(loc1) - distanceSquared(loc2)); } }); return new dList(found).getAttribute(attribute); } // <--[tag] // @attribute <[email protected]_blocks[<block>|...].within[X]> // @returns dList // @description // Returns a list of matching surface blocks within a radius. // --> else if (attribute.startsWith("surface_blocks") && attribute.getAttribute(2).startsWith("within") && attribute.hasContext(2)) { ArrayList<dLocation> found = new ArrayList<dLocation>(); int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10; List<dObject> materials = new ArrayList<dObject>(); if (attribute.hasContext(1)) materials = dList.valueOf(attribute.getContext(1)).filter(dMaterial.class); attribute.fulfill(2); for (int x = -(radius); x <= radius; x++) for (int y = -(radius); y <= radius; y++) for (int z = -(radius); z <= radius; z++) if (!materials.isEmpty()) { for (dObject material : materials) if (((dMaterial) material).matchesMaterialData(getBlock() .getRelative(x,y,z).getType().getNewData(getBlock() .getRelative(x,y,z).getData()))) { Location l = getBlock().getRelative(x,y,z).getLocation(); if (l.add(0,1,0).getBlock().getType() == Material.AIR && l.add(0,1,0).getBlock().getType() == Material.AIR) found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation())); } } else { Location l = getBlock().getRelative(x,y,z).getLocation(); if (l.add(0,1,0).getBlock().getType() == Material.AIR && l.add(0,1,0).getBlock().getType() == Material.AIR) found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation())); } Collections.sort(found, new Comparator<dLocation>() { @Override public int compare(dLocation loc1, dLocation loc2) { return (int) (distanceSquared(loc1) - distanceSquared(loc2)); } }); return new dList(found).getAttribute(attribute); } // <--[tag] // @attribute <[email protected][X]> // @returns dList // @description // Returns a list of players within a radius. // --> else if (attribute.startsWith("players") && attribute.getAttribute(2).startsWith("within") && attribute.hasContext(2)) { ArrayList<dPlayer> found = new ArrayList<dPlayer>(); int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10; attribute.fulfill(2); for (Player player : Bukkit.getOnlinePlayers()) if (!player.isDead() && Utilities.checkLocation(this, player.getLocation(), radius)) found.add(new dPlayer(player)); Collections.sort(found, new Comparator<dPlayer>() { @Override public int compare(dPlayer pl1, dPlayer pl2) { return (int) (distanceSquared(pl1.getLocation()) - distanceSquared(pl2.getLocation())); } }); return new dList(found).getAttribute(attribute); } // <--[tag] // @attribute <[email protected][X]> // @returns dList // @description // Returns a list of NPCs within a radius. // --> else if (attribute.startsWith("npcs") && attribute.getAttribute(2).startsWith("within") && attribute.hasContext(2)) { ArrayList<dNPC> found = new ArrayList<dNPC>(); int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10; attribute.fulfill(2); for (dNPC npc : DenizenAPI.getSpawnedNPCs()) if (Utilities.checkLocation(this, npc.getLocation(), radius)) found.add(npc); Collections.sort(found, new Comparator<dNPC>() { @Override public int compare(dNPC npc1, dNPC npc2) { return (int) (distanceSquared(npc1.getLocation()) - distanceSquared(npc2.getLocation())); } }); return new dList(found).getAttribute(attribute); } // <--[tag] // @attribute <[email protected][X]> // @returns dList // @description // Returns a list of entities within a radius. // --> else if (attribute.startsWith("entities") && attribute.getAttribute(2).startsWith("within") && attribute.hasContext(2)) { ArrayList<dEntity> found = new ArrayList<dEntity>(); int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10; attribute.fulfill(2); for (Entity entity : getWorld().getEntities()) if (Utilities.checkLocation(this, entity.getLocation(), radius)) found.add(new dEntity(entity)); Collections.sort(found, new Comparator<dEntity>() { @Override public int compare(dEntity ent1, dEntity ent2) { return (int) (distanceSquared(ent1.getBukkitEntity().getLocation()) - distanceSquared(ent2.getBukkitEntity().getLocation())); } }); return new dList(found).getAttribute(attribute); } // <--[tag] // @attribute <[email protected]_entities.within[X]> // @returns dList // @description // Returns a list of living entities within a radius. // --> else if (attribute.startsWith("living_entities") && attribute.getAttribute(2).startsWith("within") && attribute.hasContext(2)) { ArrayList<dEntity> found = new ArrayList<dEntity>(); int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10; attribute.fulfill(2); for (Entity entity : getWorld().getEntities()) if (entity instanceof LivingEntity && Utilities.checkLocation(this, entity.getLocation(), radius)) found.add(new dEntity(entity)); Collections.sort(found, new Comparator<dEntity>() { @Override public int compare(dEntity ent1, dEntity ent2) { return (int) (distanceSquared(ent1.getBukkitEntity().getLocation()) - distanceSquared(ent2.getBukkitEntity().getLocation())); } }); return new dList(found).getAttribute(attribute); } return new Element("null").getAttribute(attribute); } // <--[tag] // @attribute <[email protected]> // @returns dInventory // @description // Returns the dInventory of the block at the location. If the // block is not a container, returns null. // --> if (attribute.startsWith("inventory")) { if (getBlock().getState() instanceof InventoryHolder) return new dInventory(getBlock().getState()).getAttribute(attribute.fulfill(1)); return new Element("null").getAttribute(attribute); } // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns the Bukkit material name of the block at the location. // --> if (attribute.startsWith("block.material")) return dMaterial.getMaterialFrom(getBlock().getType(), getBlock().getData()).getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns dLocation // @description // Returns the location's direction as a one-length vector. // --> if (attribute.startsWith("direction.vector")) { double xzLen = Math.cos((getPitch() % 360) * (Math.PI/180)); double nx = xzLen * Math.cos(getYaw() * (Math.PI/180)); double ny = Math.sin(getPitch() * (Math.PI/180)); double nz = xzLen * Math.sin(-getYaw() * (Math.PI/180)); return new dLocation(getWorld(), -nx, -ny, nz).getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected][<location>]> // @returns Element // @description // Returns the compass direction between two locations. // If no second location is specified, returns the direction of the location. // --> if (attribute.startsWith("direction")) { // Get the cardinal direction from this location to another if (attribute.hasContext(1) && dLocation.matches(attribute.getContext(1))) { // Subtract this location's vector from the other location's vector, // not the other way around return new Element(Rotation.getCardinal(Rotation.getYaw (dLocation.valueOf(attribute.getContext(1)).toVector().subtract(this.toVector()) .normalize()))) .getAttribute(attribute.fulfill(1)); } // Get a cardinal direction from this location's yaw else { return new Element(Rotation.getCardinal(getYaw())) .getAttribute(attribute.fulfill(1)); } } // <--[tag] // @attribute <[email protected][<location>]> // @returns Element(Number) // @description // Returns the distance between 2 locations. // --> if (attribute.startsWith("distance")) { if (attribute.hasContext(1) && dLocation.matches(attribute.getContext(1))) { dLocation toLocation = dLocation.valueOf(attribute.getContext(1)); // <--[tag] // @attribute <[email protected][<location>].horizontal> // @returns Element(Number) // @description // Returns the horizontal distance between 2 locations. // --> if (attribute.getAttribute(2).startsWith("horizontal")) { // <--[tag] // @attribute <[email protected][<location>].horizontal.multiworld> // @returns Element(Number) // @description // Returns the horizontal distance between 2 multiworld locations. // --> if (attribute.getAttribute(3).startsWith("multiworld")) return new Element(Math.sqrt( Math.pow(this.getX() - toLocation.getX(), 2) + Math.pow(this.getZ() - toLocation.getZ(), 2))) .getAttribute(attribute.fulfill(3)); else if (this.getWorld() == toLocation.getWorld()) return new Element(Math.sqrt( Math.pow(this.getX() - toLocation.getX(), 2) + Math.pow(this.getZ() - toLocation.getZ(), 2))) .getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected][<location>].vertical> // @returns Element(Number) // @description // Returns the vertical distance between 2 locations. // --> else if (attribute.getAttribute(2).startsWith("vertical")) { // <--[tag] // @attribute <[email protected][<location>].vertical.multiworld> // @returns Element(Number) // @description // Returns the vertical distance between 2 multiworld locations. // --> if (attribute.getAttribute(3).startsWith("multiworld")) return new Element(Math.abs(this.getY() - toLocation.getY())) .getAttribute(attribute.fulfill(3)); else if (this.getWorld() == toLocation.getWorld()) return new Element(Math.abs(this.getY() - toLocation.getY())) .getAttribute(attribute.fulfill(2)); } else return new Element(this.distance(toLocation)) .getAttribute(attribute.fulfill(1)); } } // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns a simple formatted version of the dLocation. // EG: x,y,z,world // --> if (attribute.startsWith("simple")) return new Element(getBlockX() + "," + getBlockY() + "," + getBlockZ() + "," + getWorld().getName()).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns the formatted simple version of the dLocation. // EG: X 'x', Y 'y', Z 'z', in world 'world' // --> if (attribute.startsWith("formatted.simple")) return new Element("X '" + getBlockX() + "', Y '" + getBlockY() + "', Z '" + getBlockZ() + "', in world '" + getWorld().getName() + "'").getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns the formatted version of the dLocation. // EG: 'X 'x.x', Y 'y.y', Z 'z.z', in world 'world' // --> if (attribute.startsWith("formatted")) return new Element("X '" + getX() + "', Y '" + getY() + "', Z '" + getZ() + "', in world '" + getWorld().getName() + "'").getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_liquid> // @returns Element(Boolean) // @description // Returns whether block at the location is a liquid. // --> if (attribute.startsWith("is_liquid")) return new Element(getBlock().isLiquid()).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the amount of light from light blocks that is // on the location. // --> if (attribute.startsWith("light.from_blocks") || attribute.startsWith("light.blocks")) return new Element(getBlock().getLightFromBlocks()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the amount of light from the sky that is // on the location. // --> if (attribute.startsWith("light.from_sky") || attribute.startsWith("light.sky")) return new Element(getBlock().getLightFromSky()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the total amount of light on the location. // --> if (attribute.startsWith("light")) return new Element(getBlock().getLightLevel()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the pitch of the object at the location. // --> if (attribute.startsWith("pitch")) { return new Element(getPitch()).getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the raw yaw of the object at the location. // --> if (attribute.startsWith("yaw.raw")) { return new Element(getYaw()) .getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the normalized yaw of the object at the location. // --> if (attribute.startsWith("yaw")) { return new Element(Rotation.normalizeYaw(getYaw())) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected][<entity>/<location>]> // @returns Element(Boolean) // @description // Returns whether the location's yaw is facing another // entity or location. // --> if (attribute.startsWith("facing")) { if (attribute.hasContext(1)) { // The default number of degrees if there is no degrees attribute int degrees = 45; // The attribute to fulfill from int attributePos = 1; // <--[tag] // @attribute <location.facing[<entity>/<location>].degrees[X]> // @returns Element(Boolean) // @description // Returns whether the location's yaw is facing another // entity or location, within a specified degree range. // --> if (attribute.getAttribute(2).startsWith("degrees") && attribute.hasContext(2) && aH.matchesInteger(attribute.getContext(2))) { degrees = attribute.getIntContext(2); attributePos++; } if (dLocation.matches(attribute.getContext(1))) { return new Element(Rotation.isFacingLocation (this, dLocation.valueOf(attribute.getContext(1)), degrees)) .getAttribute(attribute.fulfill(attributePos)); } else if (dEntity.matches(attribute.getContext(1))) { return new Element(Rotation.isFacingLocation (this, dEntity.valueOf(attribute.getContext(1)) .getBukkitEntity().getLocation(), degrees)) .getAttribute(attribute.fulfill(attributePos)); } } } // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the current redstone power level of a block. // --> if (attribute.startsWith("power")) return new Element(getBlock().getBlockPower()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_region[<name>|...]> // @returns Element(Boolean) // @description // If a region name or list of names is specified, returns whether the // location is in one of the listed regions, otherwise returns whether // the location is in any region. // --> if (attribute.startsWith("in_region")) { if (Depends.worldGuard == null) { dB.echoError("Cannot check region! WorldGuard is not loaded!"); return null; } // Check if the player is in the specified region if (attribute.hasContext(1)) { dList region_list = dList.valueOf(attribute.getContext(1)); for(String region: region_list) if(WorldGuardUtilities.inRegion(this, region)) return Element.TRUE.getAttribute(attribute.fulfill(1)); return Element.FALSE.getAttribute(attribute.fulfill(1)); } // Check if the player is in any region else { return new Element(WorldGuardUtilities.inRegion(this)) .getAttribute(attribute.fulfill(1)); } } // <--[tag] // @attribute <[email protected]> // @returns dList // @description // Returns a list of regions that the location is in. // --> if (attribute.startsWith("regions")) { if (Depends.worldGuard == null) { dB.echoError("Cannot check region! WorldGuard is not loaded!"); return null; } return new dList(WorldGuardUtilities.getRegions(this)) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns dWorld // @description // Returns the world that the location is in. // --> if (attribute.startsWith("world")) { return dWorld.mirrorBukkitWorld(getWorld()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <location.block.x> // @returns Element(Number) // @description // Returns the X coordinate of the block. // --> if (attribute.startsWith("block.x")) { return new Element(getBlockX()).getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the Y coordinate of the block. // --> if (attribute.startsWith("block.y")) { return new Element(getBlockY()).getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the Z coordinate of the block. // --> if (attribute.startsWith("block.z")) { return new Element(getBlockZ()).getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the X coordinate of the location. // --> if (attribute.startsWith("x")) { return new Element(getX()).getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the Y coordinate of the location. // --> if (attribute.startsWith("y")) { return new Element(getY()).getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the Z coordinate of the location. // --> if (attribute.startsWith("z")) { return new Element(getZ()).getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_contents> // @returns dList // @description // Returns a list of lines on a sign. // --> if (attribute.startsWith("block.sign_contents")) { if (getBlock().getState() instanceof Sign) { return new dList(Arrays.asList(((Sign) getBlock().getState()).getLines())) .getAttribute(attribute.fulfill(2)); } else return "null"; } // <--[tag] // @attribute <[email protected]> // @returns dLocation // @description // Returns the location of the highest block at the location that isn't solid. // --> if (attribute.startsWith("highest")) { return new dLocation(getWorld().getHighestBlockAt(this).getLocation().add(0, -1, 0)) .getAttribute(attribute.fulfill(1)); } return new Element(identify()).getAttribute(attribute); }
diff --git a/src/main/java/songscribe/ui/musicsheetdrawer/BaseMsDrawer.java b/src/main/java/songscribe/ui/musicsheetdrawer/BaseMsDrawer.java index 36df8e2..fc475b6 100644 --- a/src/main/java/songscribe/ui/musicsheetdrawer/BaseMsDrawer.java +++ b/src/main/java/songscribe/ui/musicsheetdrawer/BaseMsDrawer.java @@ -1,827 +1,827 @@ /* SongScribe song notation program Copyright (C) 2006-2007 Csaba Kavai This file is part of SongScribe. SongScribe 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. SongScribe 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/>. Created on Jun 24, 2006 */ package songscribe.ui.musicsheetdrawer; import songscribe.data.Interval; import songscribe.data.SlurData; import songscribe.music.*; import songscribe.ui.Constants; import songscribe.ui.MusicSheet; import songscribe.ui.Utilities; import java.awt.*; import java.awt.geom.*; import java.io.File; import java.io.IOException; import java.util.ListIterator; import java.util.Vector; /** * @author Csaba Kávai */ public abstract class BaseMsDrawer { protected final int[][] FLATSHARPORDER = {{}, {0, -3, 1, -2, 2, -1, 3},{-4, -1, -5, -2, 1, -3, 0}}; protected static final float size = 32; protected static final BasicStroke beamStroke = new BasicStroke(4.167f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER); protected static final BasicStroke lineStroke = new BasicStroke(0.694f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER); protected static final BasicStroke stemStroke = new BasicStroke(0.836f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER); protected static final BasicStroke tenutoStroke = new BasicStroke(1.5f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER); private static final BasicStroke dashStroke = new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10f, new float[]{3.937f, 5.9055f}, 0f); private static final BasicStroke longDashStroke = new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER); private static final BasicStroke graceSemiQuaverStemStroke = new BasicStroke(0.6f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER); private static final BasicStroke graceSemiQuaverBeamStroke = new BasicStroke(2f, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER); private static final BasicStroke graceSemiQuaverStrikeStroke = new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL); private static final BasicStroke underScoreStroke = new BasicStroke(0.836f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER); private static final Ellipse2D.Float staccatoEllipse = new Ellipse2D.Float(0f, 0f, 3.5f, 3.5f); private static final Color selectionColor = new Color(254, 45, 125); private static final float beamTranslateY = 7; private static final Font tupletFont = new Font("Times New Roman", Font.BOLD, 14); private static final Font fsEndingFont = new Font("Times New Roman", Font.BOLD, 14); protected static Font fughetta; private static final String GLISSANDO = "\uf07e"; private static final String TRILL = "\uf0d9"; private static final double glissandoLength = size/2.6666667; private static final float longDashWidth = 7f; protected static final double tempoChangeZoomX = 0.8; protected static final double tempoChangeZoomY = 0.6; protected static final float spaceBtwNoteAndAccidental = 2.7f;//1.139f; protected static final float spaceBtwTwoAccidentals = 1.3f; protected static final float spaceBtwAccidentalAndParenthesis = 0f; private static final NoteType[] BEAMLEVELS = {NoteType.DEMISEMIQUAVER, NoteType.SEMIQUAVER, NoteType.QUAVER}; //fields for the key signature change private KeyType[] keyTypes = new KeyType[2]; private int[] keys = new int[2]; private int[] froms = new int[2]; private boolean[] isNaturals = new boolean[2]; protected double crotchetWidth; protected double beamX1Correction, beamX2Correction; protected MusicSheet ms; public BaseMsDrawer(MusicSheet ms) throws FontFormatException, IOException{ this.ms = ms; if(fughetta==null){ fughetta = Font.createFont(Font.TRUETYPE_FONT, new File("fonts/fughetta.ttf")).deriveFont(size); } } public void drawMusicSheet(Graphics2D g2, boolean drawEditingComponents, double scale){ FughettaDrawer.calculateAccidentalWidths(g2); Composition composition = ms.getComposition(); if(scale!=1d) g2.scale(scale, scale); if(!drawEditingComponents)g2.translate(0, -ms.getStartY()); //drawing the title g2.setPaint(Color.black); if(composition.getSongTitle().length()>0){ g2.setFont(composition.getSongTitleFont()); int i=0; for(String titleLine:composition.getSongTitle().split("\n")){ if(i==0 && composition.getNumber().length()>0){ titleLine = composition.getNumber()+". "+titleLine; } int titleWidth = g2.getFontMetrics().stringWidth(titleLine); drawAntialiasedString(g2, titleLine, (composition.getLineWidth()-titleWidth)/2, (i+1)*composition.getSongTitleFont().getSize()); i++; } } //drawing the rightInfo g2.setFont(composition.getGeneralFont()); if(composition.getRightInfo().length()>0){ drawTextBox(g2, composition.getRightInfo(), composition.getRightInfoStartY()+composition.getGeneralFont().getSize(), Component.RIGHT_ALIGNMENT, -20); } //drawing the under lyrics and the translated lyrics g2.setFont(composition.getLyricsFont()); if(composition.getUnderLyrics().length()>0){ drawTextBox(g2, composition.getUnderLyrics(), ms.getUnderLyricsYPos(), Component.CENTER_ALIGNMENT, 0); } if(composition.getTranslatedLyrics().length()>0){ drawTextBox(g2, composition.getTranslatedLyrics(), ms.getUnderLyricsYPos()+(Utilities.lineCount(composition.getUnderLyrics())+1)*g2.getFontMetrics().getAscent(), Component.CENTER_ALIGNMENT, 0); } //drawing the tempo if(composition.getLine(0).noteCount()>0){ drawTempoChange(g2, composition.getTempo(), 0, 0); } //drawing the composition for (int l = 0; l < composition.lineCount(); l++) { Line line = composition.getLine(l); g2.setPaint(l!=ms.getSelectedLine() ? Color.black : selectionColor); g2.setStroke(lineStroke); //drawing the lines for (int i = -2; i <= 2; i++) { g2.drawLine(0, ms.getNoteYPos(i*2, l), composition.getLineWidth(), ms.getNoteYPos(i*2, l)); } g2.drawLine(0, ms.getNoteYPos(-4, l), 0, ms.getNoteYPos(4, l)); g2.setPaint(Color.black); //drawing the trebleclef and the leading keys drawLineBeginning(g2, line, l); //drawing the notes int lyricsDrawn = 0; for (int n=0;n<line.noteCount();n++) { Note note = line.getNote(n); //drawing the tempochange if(note.getTempoChange()!=null){ drawTempoChange(g2, note.getTempoChange(), l, n); } //drawing th beat change if(note.getBeatChange()!=null){ drawBeatChange(g2, l, note); } //drawing the note boolean beamed = line.getBeamings().findInterval(n)!=null && note.getNoteType()!=NoteType.GRACEQUAVER; paintNote(g2, note, l, beamed, ms.isNoteSelected(n, l) && drawEditingComponents ? selectionColor : Color.black); //drawing the tie if any Interval tieVal = line.getTies().findInterval(n); if(tieVal!=null && n!=tieVal.getB()){ boolean tieUpper = note.isUpper(); int xPos = note.getXPos()+getHalfNoteWidthForTie(note)+2; int gap = line.getNote(n+1).getXPos()+getHalfNoteWidthForTie(line.getNote(n+1))-xPos-3; if(note.isUpper()!=line.getNote(n+1).isUpper() && note.isUpper()){ tieUpper = false; xPos+=7; gap-=5; } int yPos = ms.getNoteYPos(note.getYPos(), l)+(tieUpper ? MusicSheet.LINEDIST/2+2 : -MusicSheet.LINEDIST/2-2); g2.setStroke(lineStroke); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); GeneralPath tie = new GeneralPath(GeneralPath.WIND_NON_ZERO, 2); tie.moveTo(xPos, yPos); tie.quadTo(xPos+gap/2, yPos+(tieUpper?6:-6), xPos+gap, yPos); tie.quadTo(xPos+gap/2, yPos+(tieUpper?8:-8), xPos, yPos); tie.closePath(); g2.draw(tie); g2.fill(tie); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); /*g2.setPaint(Color.red); g2.drawRect(xPos, yPos, 1, 1); g2.setPaint(Color.green); g2.drawRect(note.getXPos(), yPos, 1, 1); g2.drawRect(note.getXPos()+note.getRealUpNoteRect().width, yPos, 1, 1); g2.setPaint(Color.black);*/ } //drawing the lyrics int lyricsY = ms.getNoteYPos(0, l)+line.getLyricsYPos(); int dashY = lyricsY - composition.getLyricsFont().getSize() / 4; g2.setFont(composition.getLyricsFont()); int syllableWidth = 0; if(note.a.syllable!=null && note.a.syllable!=Constants.UNDERSCORE){ syllableWidth = g2.getFontMetrics().stringWidth(note.a.syllable); int lyricsX = note.getXPos() + Note.HOTSPOT.x - syllableWidth / 2 + note.getSyllableMovement(); drawAntialiasedString(g2, note.a.syllable, lyricsX, lyricsY); if (n == 0 && line.beginRelation == Note.SyllableRelation.ONEDASH) { g2.setStroke(longDashStroke); g2.draw(new Line2D.Float(lyricsX - longDashWidth - 10, dashY, lyricsX - 10, dashY)); } } if(lyricsDrawn<=n && (note.a.syllableRelation!=Note.SyllableRelation.NO || n==0 && line.beginRelation==Note.SyllableRelation.EXTENDER)){ Note.SyllableRelation relation = note.a.syllableRelation!=Note.SyllableRelation.NO ? note.a.syllableRelation : line.beginRelation; int c; if(relation==Note.SyllableRelation.DASH || relation==Note.SyllableRelation.ONEDASH){ - for(c=n+1;c<line.noteCount() && line.getNote(c).a.syllable==Constants.UNDERSCORE;c++); + for(c=n+1;c<line.noteCount() && (line.getNote(c).a.syllable==Constants.UNDERSCORE || line.getNote(c).a.syllable.isEmpty());c++); }else{ - for(c=n;c<line.noteCount() && line.getNote(c).a.syllableRelation==relation;c++); + for(c=n;c<line.noteCount() && (line.getNote(c).a.syllableRelation==relation || line.getNote(c).a.syllable.isEmpty());c++); } lyricsDrawn = c; int startX = n==0 && line.beginRelation==Note.SyllableRelation.EXTENDER ? note.getXPos()-10 : note.getXPos()+Note.HOTSPOT.x+syllableWidth/2+note.getSyllableMovement()+2; int endX; if(c==line.noteCount() || c==line.noteCount()-1 && l+1<composition.lineCount() && composition.getLine(l+1).beginRelation!=Note.SyllableRelation.NO){ endX = relation==Note.SyllableRelation.ONEDASH ? startX+(int)(longDashWidth*2f) : composition.getLineWidth(); }else{ if (relation == Note.SyllableRelation.EXTENDER) { endX = line.getNote(c).getXPos() + 12; } else if (relation == Note.SyllableRelation.ONEDASH && line.getNote(c).a.syllable.isEmpty()) { endX = startX+(int)(longDashWidth*2f); } else { endX = line.getNote(c).getXPos() + Note.HOTSPOT.x - g2.getFontMetrics().stringWidth(line.getNote(c).a.syllable) / 2 + line.getNote(c).getSyllableMovement() - 2; } } if(relation==Note.SyllableRelation.DASH){ g2.setStroke(dashStroke); float dashPhase = dashStroke.getDashArray()[0]+dashStroke.getDashArray()[1]; int length = Math.round((float)Math.floor((endX-startX-dashStroke.getDashArray()[1])/dashPhase)*dashPhase+dashStroke.getDashArray()[0]); int gap = (endX-startX-length)/2; g2.drawLine(startX+gap, dashY, endX-gap, dashY); }else if(relation==Note.SyllableRelation.EXTENDER){ g2.setStroke(underScoreStroke); g2.drawLine(startX, lyricsY, endX, lyricsY); }else if(relation==Note.SyllableRelation.ONEDASH){ g2.setStroke(longDashStroke); float centerX = (endX-startX)/2f+startX; g2.draw(new Line2D.Float(centerX-longDashWidth/2f, dashY, centerX+longDashWidth/2f, dashY)); } } //drawing the annotation if(note.getAnnotation()!=null){ g2.setFont(getAnnotationFont()); drawAntialiasedString(g2, note.getAnnotation().getAnnotation(), getAnnotationXPos(g2, note), getAnnotationYPos(l, note)); } //drawing the trill if(note.isTrill() && (n==0 || !line.getNote(n-1).isTrill())){ int trillEnd=n+1; while(trillEnd<line.noteCount() && line.getNote(trillEnd).isTrill())trillEnd++; trillEnd--; int x = note.getXPos(); int y = ms.getNoteYPos(0, l)+line.getTrillYPos(); g2.setFont(fughetta); g2.drawString(TRILL, x, y); if(n<trillEnd){ drawGlissando(g2, x+18, y-3, (int)Math.round(line.getNote(trillEnd).getXPos()+crotchetWidth), y-3); } } } //drawing the slur if any for(ListIterator<Interval> li = line.getSlurs().listIterator();li.hasNext();){ Interval interval = li.next(); Note firstNote = line.getNote(interval.getA()); Note lastNote = line.getNote(interval.getB()); SlurData slurData; if (interval.getData() == null) { // applying the default values; boolean slurUpper = firstNote.isUpper(); int xPos1 = getHalfNoteWidthForTie(firstNote)+2; int xPos2 = getHalfNoteWidthForTie(lastNote)-3; if(firstNote.isUpper()!=lastNote.isUpper() && firstNote.isUpper()){ slurUpper = false; xPos1+=7; xPos2-=5; } int yPos1 = (slurUpper ? MusicSheet.LINEDIST/2+2 : -MusicSheet.LINEDIST/2-2); int yPos2 = (slurUpper ? MusicSheet.LINEDIST/2+2 : -MusicSheet.LINEDIST/2-2); int ctrly = slurUpper? 16 : -18; slurData = new SlurData(xPos1, xPos2, yPos1, yPos2, ctrly); interval.setData(slurData.toString()); } else { slurData = new SlurData(interval.getData()); } g2.setStroke(lineStroke); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); GeneralPath tie = new GeneralPath(GeneralPath.WIND_NON_ZERO, 2); int xPos1 = firstNote.getXPos()+slurData.getxPos1(); int xPos2 = lastNote.getXPos()+slurData.getxPos2(); int yPos1 = ms.getNoteYPos(firstNote.getYPos(), l)+slurData.getyPos1(); int yPos2 = ms.getNoteYPos(lastNote.getYPos(), l)+slurData.getyPos2(); int ctrly = (ms.getNoteYPos(firstNote.getYPos(), l) + ms.getNoteYPos(lastNote.getYPos(), l)) / 2 + slurData.getCtrly(); int gap = xPos2 - xPos1; tie.moveTo(xPos1, yPos1); tie.quadTo(xPos1 + gap / 2, ctrly, xPos1 + gap, yPos2); tie.quadTo(xPos1 + gap / 2, ctrly + 2, xPos1, yPos1); tie.closePath(); g2.draw(tie); g2.fill(tie); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); /*g2.setPaint(Color.red); g2.drawRect(xPos, yPos, 1, 1); g2.setPaint(Color.green); g2.drawRect(note.getXPos(), yPos, 1, 1); g2.drawRect(note.getXPos()+note.getRealUpNoteRect().width, yPos, 1, 1); g2.setPaint(Color.black);*/ } //drawing beamings for(ListIterator<Interval> li = line.getBeamings().listIterator();li.hasNext();){ Interval interval = li.next(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Line2D.Double beamLine; Note firstNote = line.getNote(interval.getA()); Note lastNote = line.getNote(interval.getB()); if(firstNote.isUpper()){ beamLine = new Line2D.Double( firstNote.getXPos()+crotchetWidth, ms.getNoteYPos(firstNote.getYPos(), l)-Note.HOTSPOT.y-firstNote.a.lengthening, lastNote.getXPos()+crotchetWidth, ms.getNoteYPos(lastNote.getYPos(), l)-Note.HOTSPOT.y-lastNote.a.lengthening); }else{ beamLine = new Line2D.Double( firstNote.getXPos(), ms.getNoteYPos(firstNote.getYPos(), l)+Note.HOTSPOT.y-firstNote.a.lengthening, lastNote.getXPos()+1, ms.getNoteYPos(lastNote.getYPos(), l)+Note.HOTSPOT.y-lastNote.a.lengthening); } Shape clip = g2.getClip(); g2.setStroke(beamStroke); beamLine.setLine(beamLine.x1-10, beamLine.y1+10*(beamLine.y1-beamLine.y2)/(beamLine.x2-beamLine.x1), beamLine.x2+10, beamLine.y2-10*(beamLine.y1-beamLine.y2)/(beamLine.x2-beamLine.x1)); drawBeaming(BEAMLEVELS.length-1, interval.getA(), interval.getB(), line, beamLine, g2, interval.getA(), interval.getB(), false); g2.setClip(clip); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } //drawing the tuplets for(ListIterator<Interval> li = line.getTuplets().listIterator();li.hasNext();){ Interval iv = li.next(); boolean odd = (iv.getB()-iv.getA()+1)%2==1; Note firstNote = line.getNote(iv.getA()); int upper = firstNote.isUpper() ? -1 : 0; int lx = firstNote.getXPos()+(int)crotchetWidth; int ly = ms.getNoteYPos(firstNote.getYPos(), l)-Note.HOTSPOT.y+upper*firstNote.a.lengthening; ly-=5; int cx; if(odd){ Note centerNote = line.getNote((iv.getB()-iv.getA())/2+iv.getA()); cx = centerNote.getXPos()+(int)crotchetWidth; }else{ Note cn1 = line.getNote((iv.getB()-iv.getA())/2+iv.getA()); Note cn2 = line.getNote((iv.getB()-iv.getA())/2+iv.getA()+1); cx = (cn2.getXPos()-cn1.getXPos())/2+cn1.getXPos()+(int)crotchetWidth; } Note lastNote = line.getNote(iv.getB()); int rx = lastNote.getXPos()+(int)crotchetWidth; int ry = ms.getNoteYPos(lastNote.getYPos(),l)-Note.HOTSPOT.y+upper*lastNote.a.lengthening; ry-=5; if(!firstNote.isUpper()){ lx-=(int)crotchetWidth/2; ly+=Note.HOTSPOT.y-3; cx-=(int)crotchetWidth/2; rx-=(int)crotchetWidth/2; ry+=Note.HOTSPOT.y-3; } g2.setStroke(lineStroke); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); TupletCalc tc = new TupletCalc(lx, ly, rx, ry); g2.draw(new QuadCurve2D.Float(lx, ly, (float)(cx-lx)/4+lx, tc.getRate((cx-lx)/4+lx)-10, cx-7, tc.getRate(cx-7)-8)); g2.draw(new QuadCurve2D.Float(cx+7, tc.getRate(cx+7)-8, (float)(rx-cx)*3/4+cx, tc.getRate((rx-cx)*3/4+cx)-10, rx, ry)); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); g2.setFont(tupletFont); drawAntialiasedString(g2, iv.getData(), cx-3, tc.getRate(cx-3)-5); /*g2.setColor(Color.red); g2.fill(new Rectangle2D.Double(triplet.getX1()-1, triplet.getY1()-1, 2, 2)); g2.fill(new Rectangle2D.Double(triplet.getX2()-1, triplet.getY2()-1, 2, 2)); g2.setColor(Color.orange); g2.fill(new Rectangle2D.Double(triplet.getCtrlX1()-1, triplet.getCtrlY1()-1, 2, 2)); g2.fill(new Rectangle2D.Double(triplet.getCtrlX2()-1, triplet.getCtrlY2()-1, 2, 2)); g2.setColor(Color.black);*/ } //drawing the key signature changes if(l+1<composition.lineCount() && (composition.getLine(l+1).getKeys()!=line.getKeys() || composition.getLine(l+1).getKeyType()!=line.getKeyType())){ Line nextLine = composition.getLine(l+1); if(nextLine.getKeyType()==line.getKeyType()){ keyTypes[0]=nextLine.getKeyType();keys[0]=nextLine.getKeys();froms[0]=0;isNaturals[0]=false; if(nextLine.getKeys()>line.getKeys()){ keyTypes[1]=null;keys[1]=0;froms[1]=0;isNaturals[1]=false; }else{ keyTypes[1]=line.getKeyType();keys[1]=line.getKeys()-nextLine.getKeys();froms[1]=nextLine.getKeys();isNaturals[1]=true; } }else{ keyTypes[0]=line.getKeyType();keys[0]=line.getKeys();froms[0]=0;isNaturals[0]=true; keyTypes[1]=nextLine.getKeyType();keys[1]=nextLine.getKeys();froms[1]=0;isNaturals[1]=false; } drawKeySignatureChange(g2, l, keyTypes, keys, froms, isNaturals); } //drawing the first-second endings for(ListIterator<Interval> li = line.getFsEndings().listIterator();li.hasNext();){ Interval iv = li.next(); int repeatRightPos = -1; for(int i=iv.getA();i<=iv.getB();i++){ if(line.getNote(i).getNoteType()==NoteType.REPEATRIGHT){ repeatRightPos = i; break; } } if(iv.getA()<repeatRightPos || repeatRightPos==-1){ drawEndings(g2, l, line.getNote(iv.getA()).getXPos(), (repeatRightPos!=-1 ? line.getNote(repeatRightPos-1).getXPos() : line.getNote(iv.getB()).getXPos())+2*(int)crotchetWidth, "1."); } if(iv.getB()>repeatRightPos && repeatRightPos!=-1){ drawEndings(g2, l, line.getNote(repeatRightPos+1).getXPos(), line.getNote(iv.getB()).getXPos()+2*(int)crotchetWidth, "2."); } } } } private class TupletCalc { int lx, ly, rx, ry; public TupletCalc(int lx, int ly, int rx, int ry) { this.lx = lx; this.ly = ly; this.rx = rx; this.ry = ry; } float getRate(int x) { return (float)(ry-ly)*(x-lx)/(rx-lx)+ly; } } public int getAnnotationYPos(int l, Note note) { return ms.getNoteYPos(0, l)+note.getAnnotation().getyPos(); } public double getAnnotationXPos(Graphics2D g2, Note note) { Annotation a = note.getAnnotation(); double xPos = note.getXPos()+crotchetWidth/2; if(a.getXalignment()==Component.CENTER_ALIGNMENT){ xPos-=g2.getFontMetrics(getAnnotationFont()).stringWidth(a.getAnnotation())/2; }else if(a.getXalignment()==Component.RIGHT_ALIGNMENT){ xPos-=g2.getFontMetrics(getAnnotationFont()).stringWidth(a.getAnnotation()); } return xPos; } private Font oldGeneralFont, annotationFont; private Font getAnnotationFont(){ if(oldGeneralFont!=ms.getComposition().getGeneralFont()){ oldGeneralFont = ms.getComposition().getGeneralFont(); annotationFont = oldGeneralFont.deriveFont(Font.ITALIC); } return annotationFont; } private int getHalfNoteWidthForTie(Note note){ if(note.getNoteType()==NoteType.SEMIBREVE || note.getNoteType()==NoteType.MINIM){ return note.getRealUpNoteRect().width/2; }else{ return (int)Math.round(crotchetWidth/2); } } private boolean isNoteTypeInLevel(Line line, int noteIndex, int level){ NoteType nt = line.getNote(noteIndex).getNoteType(); if(!nt.isGraceNote()){ for(int i=0;i<BEAMLEVELS.length;i++){ if(BEAMLEVELS[i]==nt){ return i<=level; } } return false; }else{ int begin=noteIndex-1, end=noteIndex+1; while(begin>0 && line.getNote(begin).getNoteType().isGraceNote())begin--; while(end<line.noteCount() && line.getNote(end).getNoteType().isGraceNote())end++; return begin>=0 && isNoteTypeInLevel(line, begin, level) && end<line.noteCount() && isNoteTypeInLevel(line, end, level); } } private void drawBeaming(int level, int begin, int end, Line line, Line2D.Double beamLine, Graphics2D g2, int prevBegin, int prevEnd, boolean isPrevLeft){ if(level==-1) return; boolean upper = line.getNote(begin).isUpper(); //clipping boolean leftOriented; if(begin==end){ if(line.getNote(begin).getNoteType().isGraceNote()) return; double startBeamLineX; double endBeamLineX; if(upper){ if(begin!=prevBegin || prevBegin==prevEnd && isPrevLeft){ startBeamLineX = line.getNote(begin).getXPos() - 1; endBeamLineX = line.getNote(begin).getXPos() + crotchetWidth; leftOriented = true; }else{ startBeamLineX = line.getNote(begin).getXPos() + crotchetWidth; endBeamLineX = line.getNote(begin).getXPos() + 2*crotchetWidth + 2; leftOriented = false; } }else{ if(begin!=prevBegin || prevBegin==prevEnd && isPrevLeft){ startBeamLineX = line.getNote(end).getXPos() - crotchetWidth - 2; endBeamLineX = line.getNote(end).getXPos(); leftOriented = true; }else{ startBeamLineX = line.getNote(end).getXPos(); endBeamLineX = line.getNote(end).getXPos() + crotchetWidth + 2; leftOriented = false; } } g2.setClip(new Rectangle2D.Double(startBeamLineX, Math.min(beamLine.y1,beamLine.y2)-3, endBeamLineX-startBeamLineX, Math.abs(beamLine.y1-beamLine.y2)+6)); }else{ leftOriented = false; double startBeamLineX = line.getNote(begin).getXPos() + (upper ? crotchetWidth : 0) + beamX1Correction - stemStroke.getLineWidth()/4f; double endBeamLineX = line.getNote(end).getXPos() + (upper ? crotchetWidth : 0) - beamX2Correction + stemStroke.getLineWidth()/4f; g2.setClip(new Rectangle2D.Double(startBeamLineX, Math.min(beamLine.y1,beamLine.y2)-3, endBeamLineX-startBeamLineX, Math.abs(beamLine.y1-beamLine.y2)+6)); } //drawing g2.draw(beamLine); //recursing float trans = upper ? beamTranslateY : -beamTranslateY; Line2D.Double subBeamLine = new Line2D.Double(beamLine.x1, beamLine.y1+trans, beamLine.x2, beamLine.y2+trans); int startSubBeam = -1; for(int i=begin;i<=end+1;i++){ if(i<=end && isNoteTypeInLevel(line, i, level-1)){ if(startSubBeam==-1){ startSubBeam = i; } }else if(startSubBeam!=-1){ drawBeaming(level-1, startSubBeam, i-1, line, subBeamLine, g2, begin, end, leftOriented); startSubBeam = -1; } } } public void drawGlissando(Graphics2D g2, int xIndex, Note.Glissando glissando, int l){ Line line = ms.getComposition().getLine(l); int x1 = getGlissandoX1Pos(xIndex, glissando, l); int x2 = getGlissandoX2Pos(xIndex, glissando, l); drawGlissando(g2, x1, ms.getNoteYPos(line.getNote(xIndex).getYPos(),l), x2, ms.getNoteYPos(glissando.pitch, l)); g2.setStroke(lineStroke); //drawing the stave-longitude // TODO: check with Tanima // if (Math.abs(glissando.pitch) > 5 && (xIndex+1==line.noteCount() || // Math.abs(line.getNote(xIndex+1).getYPos())<Math.abs(glissando.pitch))) { // for (int i = glissando.pitch + (glissando.pitch % 2 == 0 ? 0 : glissando.pitch > 0 ? -1 : 1); Math.abs(i) > 5; i += glissando.pitch > 0 ? -2 : 2) // g2.drawLine(x2-5, ms.getNoteYPos(i, l), // x2+5, ms.getNoteYPos(i, l)); // } } public int getGlissandoX1Pos(int xIndex, Note.Glissando glissando, int l){ Line line = ms.getComposition().getLine(l); Note note = line.getNote(xIndex); int x1 = note.getXPos()+15+glissando.x1Translate; NoteType noteType = note.getNoteType(); if(noteType ==NoteType.SEMIBREVE){ x1+=3; }else if(noteType.isGraceNote()){ x1-=3; if (noteType == NoteType.GRACESEMIQUAVER) { x1 += ((GraceSemiQuaver)note).getX2DiffPos(); } } x1+= note.getDotted()*6; return x1; } public int getGlissandoX2Pos(int xIndex, Note.Glissando glissando, int l){ Line line = ms.getComposition().getLine(l); float x2 = -glissando.x2Translate; if(xIndex+1<line.noteCount()){ x2+=line.getNote(xIndex+1).getXPos()-3; int accNum = line.getNote(xIndex+1).getAccidental().ordinal(); if(accNum>0){ x2-=FughettaDrawer.getAccidentalWidth(line.getNote(xIndex+1)); x2-=1.6; } }else{ x2+= line.getNote(xIndex).getXPos() + 45; } return Math.round(x2); } protected int getFermataYPos(Note note){ if(note.isUpper() && note.getYPos()<2){ return note.getYPos()-11; }else if(!note.isUpper() && note.getYPos()<-4){ return note.getYPos()-5; }else return -9; } private void drawGlissando(Graphics2D g2, int x1, int y1, int x2, int y2){ double l = Math.sqrt(Math.abs(x1-x2)*Math.abs(x1-x2)+Math.abs(y1-y2)*Math.abs(y1-y2)); int m = (int)Math.round(l/glissandoLength); m = Math.max(2, m); // minimum two glissando parts g2.setFont(fughetta); AffineTransform at = g2.getTransform(); g2.translate(x1, y1+2.25d); g2.rotate(Math.atan((double)(y2-y1)/(double)(x2-x1))); double scale = l/glissandoLength/m; g2.scale(scale, 1d); for(int i=0;i<m;i++){ drawAntialiasedString(g2, GLISSANDO, (int)Math.round(i*glissandoLength), 0); } g2.setTransform(at); } private void drawTempoChange(Graphics2D g2, Tempo tempo, int line, int note){ Line l = ms.getComposition().getLine(line); Note n = l.getNote(note); int yPos = ms.getMiddleLine()+l.getTempoChangeYPos()+line*ms.getRowHeight(); StringBuilder tempoBuilder = new StringBuilder(25); Note tempoTypeNote = tempo.getTempoType().getNote(); if(tempo.isShowTempo()){ drawTempoChangeNote(g2, tempoTypeNote, n.getXPos(), yPos); tempoBuilder.append("= "); tempoBuilder.append(tempo.getVisibleTempo()); tempoBuilder.append(' '); } tempoBuilder.append(tempo.getTempoDescription()); g2.setFont(ms.getComposition().getGeneralFont()); drawAntialiasedString(g2, tempoBuilder.toString(), n.getXPos()+(tempo.isShowTempo()?crotchetWidth+5+(tempoTypeNote.getDotted()==1 || tempoTypeNote.getNoteType()==NoteType.QUAVER ? 6 : 0) : 0), yPos); } private void drawBeatChange(Graphics2D g2, int line, Note note){ BeatChange beatChange = note.getBeatChange(); int yPos = ms.getNoteYPos(0, line)+ms.getComposition().getLine(line).getBeatChangeYPos(); drawBeatChange(g2, beatChange, note.getXPos(), yPos); } public void drawBeatChange(Graphics2D g2, BeatChange beatChange, int xPos, int yPos){ drawTempoChangeNote(g2, beatChange.getFirstNote(), xPos, yPos); g2.setFont(ms.getComposition().getGeneralFont()); double eqXPos = xPos + crotchetWidth + 7; drawAntialiasedString(g2, "=", eqXPos, yPos); drawTempoChangeNote(g2, beatChange.getSecondNote(), (int)Math.round(eqXPos+12), yPos); } private void drawEndings(Graphics2D g2, int line, int x1, int x2, String str){ int y = ms.getNoteYPos(0, line)+ms.getComposition().getLine(line).getFsEndingYPos(); int height = fsEndingFont.getSize()+2; g2.setStroke(stemStroke); g2.drawLine(x1, y, x1, y-height); g2.drawLine(x1, y-height, x2, y-height); g2.setFont(fsEndingFont); drawAntialiasedString(g2, str, x1+4, y); } protected void drawArticulation(Graphics2D g2, Note note, int line){ //todo exact y2 for all articulations //drawing the accent int xPos = note.getXPos(); if(note.getForceArticulation()==ForceArticulation.ACCENT){ int x1 = xPos; int x2 = xPos+(int)crotchetWidth+2; int y; if(note.isUpper()){ if(note.getYPos()<=3){ y = ms.getNoteYPos(6, line); }else{ y = ms.getNoteYPos(note.getYPos()+3, line); } }else{ if(note.getYPos()>=-3){ y = ms.getNoteYPos(-6, line); }else{ y = ms.getNoteYPos(note.getYPos()-3, line); } } g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.drawLine(x1, y-3, x2, y); g2.drawLine(x1, y+3, x2, y); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } int dir = note.isUpper() ? 1 : -1; int durY = ms.getNoteYPos(note.getYPos()+dir*2+dir*(1-note.getYPos()%2), line); if(note.getDurationArticulation()==DurationArticulation.STACCATO){ AffineTransform at = g2.getTransform(); g2.translate(xPos+getHalfNoteWidthForTie(note)-2, durY-2); g2.fill(staccatoEllipse); g2.setTransform(at); }else if(note.getDurationArticulation()==DurationArticulation.TENUTO){ g2.setStroke(tenutoStroke); double width = note.getNoteType()==NoteType.SEMIBREVE || note.getNoteType()==NoteType.MINIM ? note.getRealUpNoteRect().width : crotchetWidth; g2.draw(new Line2D.Double(xPos, durY, xPos+width, durY)); } } protected void drawAntialiasedString(Graphics2D g2, String str, int x, int y){ g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.drawString(str, x, y); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } protected void drawAntialiasedString(Graphics2D g2, String str, double x, double y){ g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.drawString(str, (float)x, (float)y); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } protected void drawAntialiasedStringZoomed(Graphics2D g2, String str, int x, int y, float zoom){ g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.drawString(str, x/zoom, y/zoom); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } protected void drawAntialiasedStringZoomed(Graphics2D g2, String str, float x, float y, float zoom){ g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.drawString(str, x/zoom, y/zoom); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } private void drawTextBox(Graphics2D g2, String str, int y, float xAlignment, int xTranslate){ Vector<String> rightVector = new Vector<String>(4); int prevIndex = 0; int maxWidth = 0; for(int i=0;i<=str.length();i++){ if(i==str.length() || str.charAt(i)=='\n' && i<str.length()-1){ String tmp = str.substring(prevIndex, i); rightVector.add(tmp); int thisWidth = g2.getFontMetrics().stringWidth(tmp); if(maxWidth<thisWidth){ maxWidth = thisWidth; } prevIndex = i+1; } } int x=0; if(xAlignment==Component.RIGHT_ALIGNMENT){ x = ms.getComposition().getLineWidth()-maxWidth; }else if(xAlignment==Component.CENTER_ALIGNMENT){ x = (ms.getComposition().getLineWidth()-maxWidth)/2; } x+=xTranslate; for(int i=0;i<rightVector.size();i++){ drawAntialiasedString(g2, rightVector.get(i), x, y+i*Math.round(g2.getFontMetrics().getHeight()*0.9f)); } } protected void drawGraceSemiQuaverBeam(Graphics2D g2, Note note, int line) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); int dir = note.isUpper() ? -1 : 1; int x1 = note.getXPos() + (note.isUpper() ? 8 : 2); int x2 = x1 + ((GraceSemiQuaver)note).getX2DiffPos(); int y1Pos = ((GraceSemiQuaver) note).getY0Pos(); int y2Pos = note.getYPos(); // drawing the stem g2.setStroke(graceSemiQuaverStemStroke); int yHead1 = ms.getNoteYPos(y1Pos, line); int lengthening1 = Math.max(dir * (y2Pos - y1Pos) - 2, 0); int yUpper1 = ms.getNoteYPos(y1Pos + dir * (4 + lengthening1), line); g2.drawLine(x1, yHead1, x1, yUpper1 + dir); int lengthening2 = Math.max(dir * (y1Pos - y2Pos) - 2, 0); int yUpper2 = ms.getNoteYPos(y2Pos + dir * (4 + lengthening2), line); int yHead2 = ms.getNoteYPos(y2Pos, line); g2.drawLine(x2, yHead2, x2, yUpper2 + dir); // drawing the beams g2.setStroke(graceSemiQuaverBeamStroke); g2.setClip(x1, 0, x2 - x1, Integer.MAX_VALUE); g2.drawLine(x1, yUpper1, x2, yUpper2); yUpper1 -= dir * 3; yUpper2 -= dir * 3; g2.drawLine(x1, yUpper1, x2, yUpper2); g2.setClip(null); // drawing the grace strike g2.setStroke(graceSemiQuaverStrikeStroke); yUpper1 += -3 * dir * MusicSheet.HALFLINEDIST + dir * 5; yUpper2 += dir * MusicSheet.HALFLINEDIST + dir * 4; g2.drawLine(x1-5, yUpper1, x2-3, yUpper2); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); //drawing steve-longitudes g2.setStroke(lineStroke); drawStaveLongitude(g2, y1Pos, line, x1-8, x1+3); drawStaveLongitude(g2, y2Pos, line, x2-8, x2+3); } protected void drawStaveLongitude(Graphics g2, int yPos, int line, int x1Pos, int x2Pos) { if (Math.abs(yPos) > 5) { for (int i = yPos + (yPos % 2 == 0 ? 0 : (yPos > 0 ? -1 : 1)); Math.abs(i) > 5; i += yPos > 0 ? -2 : 2){ int y1 = ms.getNoteYPos(i, line); g2.drawLine(x1Pos, y1, x2Pos, y1); } } } public abstract void paintNote(Graphics2D g2, Note note, int line, boolean beamed, Color color); protected abstract void drawLineBeginning(Graphics2D g2, Line line, int l); protected abstract void drawKeySignatureChange(Graphics2D g2, int l, KeyType[] keyTypes, int[] keys, int[] froms, boolean[] isNatural); protected abstract void drawTempoChangeNote(Graphics2D g2, Note tempoNote, int x, int y); }
false
true
public void drawMusicSheet(Graphics2D g2, boolean drawEditingComponents, double scale){ FughettaDrawer.calculateAccidentalWidths(g2); Composition composition = ms.getComposition(); if(scale!=1d) g2.scale(scale, scale); if(!drawEditingComponents)g2.translate(0, -ms.getStartY()); //drawing the title g2.setPaint(Color.black); if(composition.getSongTitle().length()>0){ g2.setFont(composition.getSongTitleFont()); int i=0; for(String titleLine:composition.getSongTitle().split("\n")){ if(i==0 && composition.getNumber().length()>0){ titleLine = composition.getNumber()+". "+titleLine; } int titleWidth = g2.getFontMetrics().stringWidth(titleLine); drawAntialiasedString(g2, titleLine, (composition.getLineWidth()-titleWidth)/2, (i+1)*composition.getSongTitleFont().getSize()); i++; } } //drawing the rightInfo g2.setFont(composition.getGeneralFont()); if(composition.getRightInfo().length()>0){ drawTextBox(g2, composition.getRightInfo(), composition.getRightInfoStartY()+composition.getGeneralFont().getSize(), Component.RIGHT_ALIGNMENT, -20); } //drawing the under lyrics and the translated lyrics g2.setFont(composition.getLyricsFont()); if(composition.getUnderLyrics().length()>0){ drawTextBox(g2, composition.getUnderLyrics(), ms.getUnderLyricsYPos(), Component.CENTER_ALIGNMENT, 0); } if(composition.getTranslatedLyrics().length()>0){ drawTextBox(g2, composition.getTranslatedLyrics(), ms.getUnderLyricsYPos()+(Utilities.lineCount(composition.getUnderLyrics())+1)*g2.getFontMetrics().getAscent(), Component.CENTER_ALIGNMENT, 0); } //drawing the tempo if(composition.getLine(0).noteCount()>0){ drawTempoChange(g2, composition.getTempo(), 0, 0); } //drawing the composition for (int l = 0; l < composition.lineCount(); l++) { Line line = composition.getLine(l); g2.setPaint(l!=ms.getSelectedLine() ? Color.black : selectionColor); g2.setStroke(lineStroke); //drawing the lines for (int i = -2; i <= 2; i++) { g2.drawLine(0, ms.getNoteYPos(i*2, l), composition.getLineWidth(), ms.getNoteYPos(i*2, l)); } g2.drawLine(0, ms.getNoteYPos(-4, l), 0, ms.getNoteYPos(4, l)); g2.setPaint(Color.black); //drawing the trebleclef and the leading keys drawLineBeginning(g2, line, l); //drawing the notes int lyricsDrawn = 0; for (int n=0;n<line.noteCount();n++) { Note note = line.getNote(n); //drawing the tempochange if(note.getTempoChange()!=null){ drawTempoChange(g2, note.getTempoChange(), l, n); } //drawing th beat change if(note.getBeatChange()!=null){ drawBeatChange(g2, l, note); } //drawing the note boolean beamed = line.getBeamings().findInterval(n)!=null && note.getNoteType()!=NoteType.GRACEQUAVER; paintNote(g2, note, l, beamed, ms.isNoteSelected(n, l) && drawEditingComponents ? selectionColor : Color.black); //drawing the tie if any Interval tieVal = line.getTies().findInterval(n); if(tieVal!=null && n!=tieVal.getB()){ boolean tieUpper = note.isUpper(); int xPos = note.getXPos()+getHalfNoteWidthForTie(note)+2; int gap = line.getNote(n+1).getXPos()+getHalfNoteWidthForTie(line.getNote(n+1))-xPos-3; if(note.isUpper()!=line.getNote(n+1).isUpper() && note.isUpper()){ tieUpper = false; xPos+=7; gap-=5; } int yPos = ms.getNoteYPos(note.getYPos(), l)+(tieUpper ? MusicSheet.LINEDIST/2+2 : -MusicSheet.LINEDIST/2-2); g2.setStroke(lineStroke); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); GeneralPath tie = new GeneralPath(GeneralPath.WIND_NON_ZERO, 2); tie.moveTo(xPos, yPos); tie.quadTo(xPos+gap/2, yPos+(tieUpper?6:-6), xPos+gap, yPos); tie.quadTo(xPos+gap/2, yPos+(tieUpper?8:-8), xPos, yPos); tie.closePath(); g2.draw(tie); g2.fill(tie); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); /*g2.setPaint(Color.red); g2.drawRect(xPos, yPos, 1, 1); g2.setPaint(Color.green); g2.drawRect(note.getXPos(), yPos, 1, 1); g2.drawRect(note.getXPos()+note.getRealUpNoteRect().width, yPos, 1, 1); g2.setPaint(Color.black);*/ } //drawing the lyrics int lyricsY = ms.getNoteYPos(0, l)+line.getLyricsYPos(); int dashY = lyricsY - composition.getLyricsFont().getSize() / 4; g2.setFont(composition.getLyricsFont()); int syllableWidth = 0; if(note.a.syllable!=null && note.a.syllable!=Constants.UNDERSCORE){ syllableWidth = g2.getFontMetrics().stringWidth(note.a.syllable); int lyricsX = note.getXPos() + Note.HOTSPOT.x - syllableWidth / 2 + note.getSyllableMovement(); drawAntialiasedString(g2, note.a.syllable, lyricsX, lyricsY); if (n == 0 && line.beginRelation == Note.SyllableRelation.ONEDASH) { g2.setStroke(longDashStroke); g2.draw(new Line2D.Float(lyricsX - longDashWidth - 10, dashY, lyricsX - 10, dashY)); } } if(lyricsDrawn<=n && (note.a.syllableRelation!=Note.SyllableRelation.NO || n==0 && line.beginRelation==Note.SyllableRelation.EXTENDER)){ Note.SyllableRelation relation = note.a.syllableRelation!=Note.SyllableRelation.NO ? note.a.syllableRelation : line.beginRelation; int c; if(relation==Note.SyllableRelation.DASH || relation==Note.SyllableRelation.ONEDASH){ for(c=n+1;c<line.noteCount() && line.getNote(c).a.syllable==Constants.UNDERSCORE;c++); }else{ for(c=n;c<line.noteCount() && line.getNote(c).a.syllableRelation==relation;c++); } lyricsDrawn = c; int startX = n==0 && line.beginRelation==Note.SyllableRelation.EXTENDER ? note.getXPos()-10 : note.getXPos()+Note.HOTSPOT.x+syllableWidth/2+note.getSyllableMovement()+2; int endX; if(c==line.noteCount() || c==line.noteCount()-1 && l+1<composition.lineCount() && composition.getLine(l+1).beginRelation!=Note.SyllableRelation.NO){ endX = relation==Note.SyllableRelation.ONEDASH ? startX+(int)(longDashWidth*2f) : composition.getLineWidth(); }else{ if (relation == Note.SyllableRelation.EXTENDER) { endX = line.getNote(c).getXPos() + 12; } else if (relation == Note.SyllableRelation.ONEDASH && line.getNote(c).a.syllable.isEmpty()) { endX = startX+(int)(longDashWidth*2f); } else { endX = line.getNote(c).getXPos() + Note.HOTSPOT.x - g2.getFontMetrics().stringWidth(line.getNote(c).a.syllable) / 2 + line.getNote(c).getSyllableMovement() - 2; } } if(relation==Note.SyllableRelation.DASH){ g2.setStroke(dashStroke); float dashPhase = dashStroke.getDashArray()[0]+dashStroke.getDashArray()[1]; int length = Math.round((float)Math.floor((endX-startX-dashStroke.getDashArray()[1])/dashPhase)*dashPhase+dashStroke.getDashArray()[0]); int gap = (endX-startX-length)/2; g2.drawLine(startX+gap, dashY, endX-gap, dashY); }else if(relation==Note.SyllableRelation.EXTENDER){ g2.setStroke(underScoreStroke); g2.drawLine(startX, lyricsY, endX, lyricsY); }else if(relation==Note.SyllableRelation.ONEDASH){ g2.setStroke(longDashStroke); float centerX = (endX-startX)/2f+startX; g2.draw(new Line2D.Float(centerX-longDashWidth/2f, dashY, centerX+longDashWidth/2f, dashY)); } } //drawing the annotation if(note.getAnnotation()!=null){ g2.setFont(getAnnotationFont()); drawAntialiasedString(g2, note.getAnnotation().getAnnotation(), getAnnotationXPos(g2, note), getAnnotationYPos(l, note)); } //drawing the trill if(note.isTrill() && (n==0 || !line.getNote(n-1).isTrill())){ int trillEnd=n+1; while(trillEnd<line.noteCount() && line.getNote(trillEnd).isTrill())trillEnd++; trillEnd--; int x = note.getXPos(); int y = ms.getNoteYPos(0, l)+line.getTrillYPos(); g2.setFont(fughetta); g2.drawString(TRILL, x, y); if(n<trillEnd){ drawGlissando(g2, x+18, y-3, (int)Math.round(line.getNote(trillEnd).getXPos()+crotchetWidth), y-3); } } } //drawing the slur if any for(ListIterator<Interval> li = line.getSlurs().listIterator();li.hasNext();){ Interval interval = li.next(); Note firstNote = line.getNote(interval.getA()); Note lastNote = line.getNote(interval.getB()); SlurData slurData; if (interval.getData() == null) { // applying the default values; boolean slurUpper = firstNote.isUpper(); int xPos1 = getHalfNoteWidthForTie(firstNote)+2; int xPos2 = getHalfNoteWidthForTie(lastNote)-3; if(firstNote.isUpper()!=lastNote.isUpper() && firstNote.isUpper()){ slurUpper = false; xPos1+=7; xPos2-=5; } int yPos1 = (slurUpper ? MusicSheet.LINEDIST/2+2 : -MusicSheet.LINEDIST/2-2); int yPos2 = (slurUpper ? MusicSheet.LINEDIST/2+2 : -MusicSheet.LINEDIST/2-2); int ctrly = slurUpper? 16 : -18; slurData = new SlurData(xPos1, xPos2, yPos1, yPos2, ctrly); interval.setData(slurData.toString()); } else { slurData = new SlurData(interval.getData()); } g2.setStroke(lineStroke); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); GeneralPath tie = new GeneralPath(GeneralPath.WIND_NON_ZERO, 2); int xPos1 = firstNote.getXPos()+slurData.getxPos1(); int xPos2 = lastNote.getXPos()+slurData.getxPos2(); int yPos1 = ms.getNoteYPos(firstNote.getYPos(), l)+slurData.getyPos1(); int yPos2 = ms.getNoteYPos(lastNote.getYPos(), l)+slurData.getyPos2(); int ctrly = (ms.getNoteYPos(firstNote.getYPos(), l) + ms.getNoteYPos(lastNote.getYPos(), l)) / 2 + slurData.getCtrly(); int gap = xPos2 - xPos1; tie.moveTo(xPos1, yPos1); tie.quadTo(xPos1 + gap / 2, ctrly, xPos1 + gap, yPos2); tie.quadTo(xPos1 + gap / 2, ctrly + 2, xPos1, yPos1); tie.closePath(); g2.draw(tie); g2.fill(tie); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); /*g2.setPaint(Color.red); g2.drawRect(xPos, yPos, 1, 1); g2.setPaint(Color.green); g2.drawRect(note.getXPos(), yPos, 1, 1); g2.drawRect(note.getXPos()+note.getRealUpNoteRect().width, yPos, 1, 1); g2.setPaint(Color.black);*/ } //drawing beamings for(ListIterator<Interval> li = line.getBeamings().listIterator();li.hasNext();){ Interval interval = li.next(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Line2D.Double beamLine; Note firstNote = line.getNote(interval.getA()); Note lastNote = line.getNote(interval.getB()); if(firstNote.isUpper()){ beamLine = new Line2D.Double( firstNote.getXPos()+crotchetWidth, ms.getNoteYPos(firstNote.getYPos(), l)-Note.HOTSPOT.y-firstNote.a.lengthening, lastNote.getXPos()+crotchetWidth, ms.getNoteYPos(lastNote.getYPos(), l)-Note.HOTSPOT.y-lastNote.a.lengthening); }else{ beamLine = new Line2D.Double( firstNote.getXPos(), ms.getNoteYPos(firstNote.getYPos(), l)+Note.HOTSPOT.y-firstNote.a.lengthening, lastNote.getXPos()+1, ms.getNoteYPos(lastNote.getYPos(), l)+Note.HOTSPOT.y-lastNote.a.lengthening); } Shape clip = g2.getClip(); g2.setStroke(beamStroke); beamLine.setLine(beamLine.x1-10, beamLine.y1+10*(beamLine.y1-beamLine.y2)/(beamLine.x2-beamLine.x1), beamLine.x2+10, beamLine.y2-10*(beamLine.y1-beamLine.y2)/(beamLine.x2-beamLine.x1)); drawBeaming(BEAMLEVELS.length-1, interval.getA(), interval.getB(), line, beamLine, g2, interval.getA(), interval.getB(), false); g2.setClip(clip); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } //drawing the tuplets for(ListIterator<Interval> li = line.getTuplets().listIterator();li.hasNext();){ Interval iv = li.next(); boolean odd = (iv.getB()-iv.getA()+1)%2==1; Note firstNote = line.getNote(iv.getA()); int upper = firstNote.isUpper() ? -1 : 0; int lx = firstNote.getXPos()+(int)crotchetWidth; int ly = ms.getNoteYPos(firstNote.getYPos(), l)-Note.HOTSPOT.y+upper*firstNote.a.lengthening; ly-=5; int cx; if(odd){ Note centerNote = line.getNote((iv.getB()-iv.getA())/2+iv.getA()); cx = centerNote.getXPos()+(int)crotchetWidth; }else{ Note cn1 = line.getNote((iv.getB()-iv.getA())/2+iv.getA()); Note cn2 = line.getNote((iv.getB()-iv.getA())/2+iv.getA()+1); cx = (cn2.getXPos()-cn1.getXPos())/2+cn1.getXPos()+(int)crotchetWidth; } Note lastNote = line.getNote(iv.getB()); int rx = lastNote.getXPos()+(int)crotchetWidth; int ry = ms.getNoteYPos(lastNote.getYPos(),l)-Note.HOTSPOT.y+upper*lastNote.a.lengthening; ry-=5; if(!firstNote.isUpper()){ lx-=(int)crotchetWidth/2; ly+=Note.HOTSPOT.y-3; cx-=(int)crotchetWidth/2; rx-=(int)crotchetWidth/2; ry+=Note.HOTSPOT.y-3; } g2.setStroke(lineStroke); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); TupletCalc tc = new TupletCalc(lx, ly, rx, ry); g2.draw(new QuadCurve2D.Float(lx, ly, (float)(cx-lx)/4+lx, tc.getRate((cx-lx)/4+lx)-10, cx-7, tc.getRate(cx-7)-8)); g2.draw(new QuadCurve2D.Float(cx+7, tc.getRate(cx+7)-8, (float)(rx-cx)*3/4+cx, tc.getRate((rx-cx)*3/4+cx)-10, rx, ry)); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); g2.setFont(tupletFont); drawAntialiasedString(g2, iv.getData(), cx-3, tc.getRate(cx-3)-5); /*g2.setColor(Color.red); g2.fill(new Rectangle2D.Double(triplet.getX1()-1, triplet.getY1()-1, 2, 2)); g2.fill(new Rectangle2D.Double(triplet.getX2()-1, triplet.getY2()-1, 2, 2)); g2.setColor(Color.orange); g2.fill(new Rectangle2D.Double(triplet.getCtrlX1()-1, triplet.getCtrlY1()-1, 2, 2)); g2.fill(new Rectangle2D.Double(triplet.getCtrlX2()-1, triplet.getCtrlY2()-1, 2, 2)); g2.setColor(Color.black);*/ } //drawing the key signature changes if(l+1<composition.lineCount() && (composition.getLine(l+1).getKeys()!=line.getKeys() || composition.getLine(l+1).getKeyType()!=line.getKeyType())){ Line nextLine = composition.getLine(l+1); if(nextLine.getKeyType()==line.getKeyType()){ keyTypes[0]=nextLine.getKeyType();keys[0]=nextLine.getKeys();froms[0]=0;isNaturals[0]=false; if(nextLine.getKeys()>line.getKeys()){ keyTypes[1]=null;keys[1]=0;froms[1]=0;isNaturals[1]=false; }else{ keyTypes[1]=line.getKeyType();keys[1]=line.getKeys()-nextLine.getKeys();froms[1]=nextLine.getKeys();isNaturals[1]=true; } }else{ keyTypes[0]=line.getKeyType();keys[0]=line.getKeys();froms[0]=0;isNaturals[0]=true; keyTypes[1]=nextLine.getKeyType();keys[1]=nextLine.getKeys();froms[1]=0;isNaturals[1]=false; } drawKeySignatureChange(g2, l, keyTypes, keys, froms, isNaturals); } //drawing the first-second endings for(ListIterator<Interval> li = line.getFsEndings().listIterator();li.hasNext();){ Interval iv = li.next(); int repeatRightPos = -1; for(int i=iv.getA();i<=iv.getB();i++){ if(line.getNote(i).getNoteType()==NoteType.REPEATRIGHT){ repeatRightPos = i; break; } } if(iv.getA()<repeatRightPos || repeatRightPos==-1){ drawEndings(g2, l, line.getNote(iv.getA()).getXPos(), (repeatRightPos!=-1 ? line.getNote(repeatRightPos-1).getXPos() : line.getNote(iv.getB()).getXPos())+2*(int)crotchetWidth, "1."); } if(iv.getB()>repeatRightPos && repeatRightPos!=-1){ drawEndings(g2, l, line.getNote(repeatRightPos+1).getXPos(), line.getNote(iv.getB()).getXPos()+2*(int)crotchetWidth, "2."); } } } }
public void drawMusicSheet(Graphics2D g2, boolean drawEditingComponents, double scale){ FughettaDrawer.calculateAccidentalWidths(g2); Composition composition = ms.getComposition(); if(scale!=1d) g2.scale(scale, scale); if(!drawEditingComponents)g2.translate(0, -ms.getStartY()); //drawing the title g2.setPaint(Color.black); if(composition.getSongTitle().length()>0){ g2.setFont(composition.getSongTitleFont()); int i=0; for(String titleLine:composition.getSongTitle().split("\n")){ if(i==0 && composition.getNumber().length()>0){ titleLine = composition.getNumber()+". "+titleLine; } int titleWidth = g2.getFontMetrics().stringWidth(titleLine); drawAntialiasedString(g2, titleLine, (composition.getLineWidth()-titleWidth)/2, (i+1)*composition.getSongTitleFont().getSize()); i++; } } //drawing the rightInfo g2.setFont(composition.getGeneralFont()); if(composition.getRightInfo().length()>0){ drawTextBox(g2, composition.getRightInfo(), composition.getRightInfoStartY()+composition.getGeneralFont().getSize(), Component.RIGHT_ALIGNMENT, -20); } //drawing the under lyrics and the translated lyrics g2.setFont(composition.getLyricsFont()); if(composition.getUnderLyrics().length()>0){ drawTextBox(g2, composition.getUnderLyrics(), ms.getUnderLyricsYPos(), Component.CENTER_ALIGNMENT, 0); } if(composition.getTranslatedLyrics().length()>0){ drawTextBox(g2, composition.getTranslatedLyrics(), ms.getUnderLyricsYPos()+(Utilities.lineCount(composition.getUnderLyrics())+1)*g2.getFontMetrics().getAscent(), Component.CENTER_ALIGNMENT, 0); } //drawing the tempo if(composition.getLine(0).noteCount()>0){ drawTempoChange(g2, composition.getTempo(), 0, 0); } //drawing the composition for (int l = 0; l < composition.lineCount(); l++) { Line line = composition.getLine(l); g2.setPaint(l!=ms.getSelectedLine() ? Color.black : selectionColor); g2.setStroke(lineStroke); //drawing the lines for (int i = -2; i <= 2; i++) { g2.drawLine(0, ms.getNoteYPos(i*2, l), composition.getLineWidth(), ms.getNoteYPos(i*2, l)); } g2.drawLine(0, ms.getNoteYPos(-4, l), 0, ms.getNoteYPos(4, l)); g2.setPaint(Color.black); //drawing the trebleclef and the leading keys drawLineBeginning(g2, line, l); //drawing the notes int lyricsDrawn = 0; for (int n=0;n<line.noteCount();n++) { Note note = line.getNote(n); //drawing the tempochange if(note.getTempoChange()!=null){ drawTempoChange(g2, note.getTempoChange(), l, n); } //drawing th beat change if(note.getBeatChange()!=null){ drawBeatChange(g2, l, note); } //drawing the note boolean beamed = line.getBeamings().findInterval(n)!=null && note.getNoteType()!=NoteType.GRACEQUAVER; paintNote(g2, note, l, beamed, ms.isNoteSelected(n, l) && drawEditingComponents ? selectionColor : Color.black); //drawing the tie if any Interval tieVal = line.getTies().findInterval(n); if(tieVal!=null && n!=tieVal.getB()){ boolean tieUpper = note.isUpper(); int xPos = note.getXPos()+getHalfNoteWidthForTie(note)+2; int gap = line.getNote(n+1).getXPos()+getHalfNoteWidthForTie(line.getNote(n+1))-xPos-3; if(note.isUpper()!=line.getNote(n+1).isUpper() && note.isUpper()){ tieUpper = false; xPos+=7; gap-=5; } int yPos = ms.getNoteYPos(note.getYPos(), l)+(tieUpper ? MusicSheet.LINEDIST/2+2 : -MusicSheet.LINEDIST/2-2); g2.setStroke(lineStroke); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); GeneralPath tie = new GeneralPath(GeneralPath.WIND_NON_ZERO, 2); tie.moveTo(xPos, yPos); tie.quadTo(xPos+gap/2, yPos+(tieUpper?6:-6), xPos+gap, yPos); tie.quadTo(xPos+gap/2, yPos+(tieUpper?8:-8), xPos, yPos); tie.closePath(); g2.draw(tie); g2.fill(tie); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); /*g2.setPaint(Color.red); g2.drawRect(xPos, yPos, 1, 1); g2.setPaint(Color.green); g2.drawRect(note.getXPos(), yPos, 1, 1); g2.drawRect(note.getXPos()+note.getRealUpNoteRect().width, yPos, 1, 1); g2.setPaint(Color.black);*/ } //drawing the lyrics int lyricsY = ms.getNoteYPos(0, l)+line.getLyricsYPos(); int dashY = lyricsY - composition.getLyricsFont().getSize() / 4; g2.setFont(composition.getLyricsFont()); int syllableWidth = 0; if(note.a.syllable!=null && note.a.syllable!=Constants.UNDERSCORE){ syllableWidth = g2.getFontMetrics().stringWidth(note.a.syllable); int lyricsX = note.getXPos() + Note.HOTSPOT.x - syllableWidth / 2 + note.getSyllableMovement(); drawAntialiasedString(g2, note.a.syllable, lyricsX, lyricsY); if (n == 0 && line.beginRelation == Note.SyllableRelation.ONEDASH) { g2.setStroke(longDashStroke); g2.draw(new Line2D.Float(lyricsX - longDashWidth - 10, dashY, lyricsX - 10, dashY)); } } if(lyricsDrawn<=n && (note.a.syllableRelation!=Note.SyllableRelation.NO || n==0 && line.beginRelation==Note.SyllableRelation.EXTENDER)){ Note.SyllableRelation relation = note.a.syllableRelation!=Note.SyllableRelation.NO ? note.a.syllableRelation : line.beginRelation; int c; if(relation==Note.SyllableRelation.DASH || relation==Note.SyllableRelation.ONEDASH){ for(c=n+1;c<line.noteCount() && (line.getNote(c).a.syllable==Constants.UNDERSCORE || line.getNote(c).a.syllable.isEmpty());c++); }else{ for(c=n;c<line.noteCount() && (line.getNote(c).a.syllableRelation==relation || line.getNote(c).a.syllable.isEmpty());c++); } lyricsDrawn = c; int startX = n==0 && line.beginRelation==Note.SyllableRelation.EXTENDER ? note.getXPos()-10 : note.getXPos()+Note.HOTSPOT.x+syllableWidth/2+note.getSyllableMovement()+2; int endX; if(c==line.noteCount() || c==line.noteCount()-1 && l+1<composition.lineCount() && composition.getLine(l+1).beginRelation!=Note.SyllableRelation.NO){ endX = relation==Note.SyllableRelation.ONEDASH ? startX+(int)(longDashWidth*2f) : composition.getLineWidth(); }else{ if (relation == Note.SyllableRelation.EXTENDER) { endX = line.getNote(c).getXPos() + 12; } else if (relation == Note.SyllableRelation.ONEDASH && line.getNote(c).a.syllable.isEmpty()) { endX = startX+(int)(longDashWidth*2f); } else { endX = line.getNote(c).getXPos() + Note.HOTSPOT.x - g2.getFontMetrics().stringWidth(line.getNote(c).a.syllable) / 2 + line.getNote(c).getSyllableMovement() - 2; } } if(relation==Note.SyllableRelation.DASH){ g2.setStroke(dashStroke); float dashPhase = dashStroke.getDashArray()[0]+dashStroke.getDashArray()[1]; int length = Math.round((float)Math.floor((endX-startX-dashStroke.getDashArray()[1])/dashPhase)*dashPhase+dashStroke.getDashArray()[0]); int gap = (endX-startX-length)/2; g2.drawLine(startX+gap, dashY, endX-gap, dashY); }else if(relation==Note.SyllableRelation.EXTENDER){ g2.setStroke(underScoreStroke); g2.drawLine(startX, lyricsY, endX, lyricsY); }else if(relation==Note.SyllableRelation.ONEDASH){ g2.setStroke(longDashStroke); float centerX = (endX-startX)/2f+startX; g2.draw(new Line2D.Float(centerX-longDashWidth/2f, dashY, centerX+longDashWidth/2f, dashY)); } } //drawing the annotation if(note.getAnnotation()!=null){ g2.setFont(getAnnotationFont()); drawAntialiasedString(g2, note.getAnnotation().getAnnotation(), getAnnotationXPos(g2, note), getAnnotationYPos(l, note)); } //drawing the trill if(note.isTrill() && (n==0 || !line.getNote(n-1).isTrill())){ int trillEnd=n+1; while(trillEnd<line.noteCount() && line.getNote(trillEnd).isTrill())trillEnd++; trillEnd--; int x = note.getXPos(); int y = ms.getNoteYPos(0, l)+line.getTrillYPos(); g2.setFont(fughetta); g2.drawString(TRILL, x, y); if(n<trillEnd){ drawGlissando(g2, x+18, y-3, (int)Math.round(line.getNote(trillEnd).getXPos()+crotchetWidth), y-3); } } } //drawing the slur if any for(ListIterator<Interval> li = line.getSlurs().listIterator();li.hasNext();){ Interval interval = li.next(); Note firstNote = line.getNote(interval.getA()); Note lastNote = line.getNote(interval.getB()); SlurData slurData; if (interval.getData() == null) { // applying the default values; boolean slurUpper = firstNote.isUpper(); int xPos1 = getHalfNoteWidthForTie(firstNote)+2; int xPos2 = getHalfNoteWidthForTie(lastNote)-3; if(firstNote.isUpper()!=lastNote.isUpper() && firstNote.isUpper()){ slurUpper = false; xPos1+=7; xPos2-=5; } int yPos1 = (slurUpper ? MusicSheet.LINEDIST/2+2 : -MusicSheet.LINEDIST/2-2); int yPos2 = (slurUpper ? MusicSheet.LINEDIST/2+2 : -MusicSheet.LINEDIST/2-2); int ctrly = slurUpper? 16 : -18; slurData = new SlurData(xPos1, xPos2, yPos1, yPos2, ctrly); interval.setData(slurData.toString()); } else { slurData = new SlurData(interval.getData()); } g2.setStroke(lineStroke); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); GeneralPath tie = new GeneralPath(GeneralPath.WIND_NON_ZERO, 2); int xPos1 = firstNote.getXPos()+slurData.getxPos1(); int xPos2 = lastNote.getXPos()+slurData.getxPos2(); int yPos1 = ms.getNoteYPos(firstNote.getYPos(), l)+slurData.getyPos1(); int yPos2 = ms.getNoteYPos(lastNote.getYPos(), l)+slurData.getyPos2(); int ctrly = (ms.getNoteYPos(firstNote.getYPos(), l) + ms.getNoteYPos(lastNote.getYPos(), l)) / 2 + slurData.getCtrly(); int gap = xPos2 - xPos1; tie.moveTo(xPos1, yPos1); tie.quadTo(xPos1 + gap / 2, ctrly, xPos1 + gap, yPos2); tie.quadTo(xPos1 + gap / 2, ctrly + 2, xPos1, yPos1); tie.closePath(); g2.draw(tie); g2.fill(tie); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); /*g2.setPaint(Color.red); g2.drawRect(xPos, yPos, 1, 1); g2.setPaint(Color.green); g2.drawRect(note.getXPos(), yPos, 1, 1); g2.drawRect(note.getXPos()+note.getRealUpNoteRect().width, yPos, 1, 1); g2.setPaint(Color.black);*/ } //drawing beamings for(ListIterator<Interval> li = line.getBeamings().listIterator();li.hasNext();){ Interval interval = li.next(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Line2D.Double beamLine; Note firstNote = line.getNote(interval.getA()); Note lastNote = line.getNote(interval.getB()); if(firstNote.isUpper()){ beamLine = new Line2D.Double( firstNote.getXPos()+crotchetWidth, ms.getNoteYPos(firstNote.getYPos(), l)-Note.HOTSPOT.y-firstNote.a.lengthening, lastNote.getXPos()+crotchetWidth, ms.getNoteYPos(lastNote.getYPos(), l)-Note.HOTSPOT.y-lastNote.a.lengthening); }else{ beamLine = new Line2D.Double( firstNote.getXPos(), ms.getNoteYPos(firstNote.getYPos(), l)+Note.HOTSPOT.y-firstNote.a.lengthening, lastNote.getXPos()+1, ms.getNoteYPos(lastNote.getYPos(), l)+Note.HOTSPOT.y-lastNote.a.lengthening); } Shape clip = g2.getClip(); g2.setStroke(beamStroke); beamLine.setLine(beamLine.x1-10, beamLine.y1+10*(beamLine.y1-beamLine.y2)/(beamLine.x2-beamLine.x1), beamLine.x2+10, beamLine.y2-10*(beamLine.y1-beamLine.y2)/(beamLine.x2-beamLine.x1)); drawBeaming(BEAMLEVELS.length-1, interval.getA(), interval.getB(), line, beamLine, g2, interval.getA(), interval.getB(), false); g2.setClip(clip); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } //drawing the tuplets for(ListIterator<Interval> li = line.getTuplets().listIterator();li.hasNext();){ Interval iv = li.next(); boolean odd = (iv.getB()-iv.getA()+1)%2==1; Note firstNote = line.getNote(iv.getA()); int upper = firstNote.isUpper() ? -1 : 0; int lx = firstNote.getXPos()+(int)crotchetWidth; int ly = ms.getNoteYPos(firstNote.getYPos(), l)-Note.HOTSPOT.y+upper*firstNote.a.lengthening; ly-=5; int cx; if(odd){ Note centerNote = line.getNote((iv.getB()-iv.getA())/2+iv.getA()); cx = centerNote.getXPos()+(int)crotchetWidth; }else{ Note cn1 = line.getNote((iv.getB()-iv.getA())/2+iv.getA()); Note cn2 = line.getNote((iv.getB()-iv.getA())/2+iv.getA()+1); cx = (cn2.getXPos()-cn1.getXPos())/2+cn1.getXPos()+(int)crotchetWidth; } Note lastNote = line.getNote(iv.getB()); int rx = lastNote.getXPos()+(int)crotchetWidth; int ry = ms.getNoteYPos(lastNote.getYPos(),l)-Note.HOTSPOT.y+upper*lastNote.a.lengthening; ry-=5; if(!firstNote.isUpper()){ lx-=(int)crotchetWidth/2; ly+=Note.HOTSPOT.y-3; cx-=(int)crotchetWidth/2; rx-=(int)crotchetWidth/2; ry+=Note.HOTSPOT.y-3; } g2.setStroke(lineStroke); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); TupletCalc tc = new TupletCalc(lx, ly, rx, ry); g2.draw(new QuadCurve2D.Float(lx, ly, (float)(cx-lx)/4+lx, tc.getRate((cx-lx)/4+lx)-10, cx-7, tc.getRate(cx-7)-8)); g2.draw(new QuadCurve2D.Float(cx+7, tc.getRate(cx+7)-8, (float)(rx-cx)*3/4+cx, tc.getRate((rx-cx)*3/4+cx)-10, rx, ry)); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); g2.setFont(tupletFont); drawAntialiasedString(g2, iv.getData(), cx-3, tc.getRate(cx-3)-5); /*g2.setColor(Color.red); g2.fill(new Rectangle2D.Double(triplet.getX1()-1, triplet.getY1()-1, 2, 2)); g2.fill(new Rectangle2D.Double(triplet.getX2()-1, triplet.getY2()-1, 2, 2)); g2.setColor(Color.orange); g2.fill(new Rectangle2D.Double(triplet.getCtrlX1()-1, triplet.getCtrlY1()-1, 2, 2)); g2.fill(new Rectangle2D.Double(triplet.getCtrlX2()-1, triplet.getCtrlY2()-1, 2, 2)); g2.setColor(Color.black);*/ } //drawing the key signature changes if(l+1<composition.lineCount() && (composition.getLine(l+1).getKeys()!=line.getKeys() || composition.getLine(l+1).getKeyType()!=line.getKeyType())){ Line nextLine = composition.getLine(l+1); if(nextLine.getKeyType()==line.getKeyType()){ keyTypes[0]=nextLine.getKeyType();keys[0]=nextLine.getKeys();froms[0]=0;isNaturals[0]=false; if(nextLine.getKeys()>line.getKeys()){ keyTypes[1]=null;keys[1]=0;froms[1]=0;isNaturals[1]=false; }else{ keyTypes[1]=line.getKeyType();keys[1]=line.getKeys()-nextLine.getKeys();froms[1]=nextLine.getKeys();isNaturals[1]=true; } }else{ keyTypes[0]=line.getKeyType();keys[0]=line.getKeys();froms[0]=0;isNaturals[0]=true; keyTypes[1]=nextLine.getKeyType();keys[1]=nextLine.getKeys();froms[1]=0;isNaturals[1]=false; } drawKeySignatureChange(g2, l, keyTypes, keys, froms, isNaturals); } //drawing the first-second endings for(ListIterator<Interval> li = line.getFsEndings().listIterator();li.hasNext();){ Interval iv = li.next(); int repeatRightPos = -1; for(int i=iv.getA();i<=iv.getB();i++){ if(line.getNote(i).getNoteType()==NoteType.REPEATRIGHT){ repeatRightPos = i; break; } } if(iv.getA()<repeatRightPos || repeatRightPos==-1){ drawEndings(g2, l, line.getNote(iv.getA()).getXPos(), (repeatRightPos!=-1 ? line.getNote(repeatRightPos-1).getXPos() : line.getNote(iv.getB()).getXPos())+2*(int)crotchetWidth, "1."); } if(iv.getB()>repeatRightPos && repeatRightPos!=-1){ drawEndings(g2, l, line.getNote(repeatRightPos+1).getXPos(), line.getNote(iv.getB()).getXPos()+2*(int)crotchetWidth, "2."); } } } }
diff --git a/trunk/uim/api/src/test/java/eu/europeana/uim/store/AbstractResourceEngineTest.java b/trunk/uim/api/src/test/java/eu/europeana/uim/store/AbstractResourceEngineTest.java index afb855fc..0e11e724 100644 --- a/trunk/uim/api/src/test/java/eu/europeana/uim/store/AbstractResourceEngineTest.java +++ b/trunk/uim/api/src/test/java/eu/europeana/uim/store/AbstractResourceEngineTest.java @@ -1,224 +1,224 @@ /* AbstractResourceEngineTest.java - created on May 9, 2011, Copyright (c) 2011 The European Library, all rights reserved */ package eu.europeana.uim.store; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Set; import org.junit.Before; import org.junit.Test; import eu.europeana.uim.api.ResourceEngine; import eu.europeana.uim.store.bean.CollectionBean; import eu.europeana.uim.store.bean.ProviderBean; /** * Abstract base class to test the contract of the resource engine * * @author Rene Wiermer ([email protected]) * @param <I> * @date May 9, 2011 */ public abstract class AbstractResourceEngineTest<I> { ResourceEngine<I> engine = null; final String EXAMPLE_KEY_1="example1.property.file"; final String EXAMPLE_KEY_2="example2.property"; final String EXAMPLE_KEY_3="3"; final String EXAMPLE_KEY_4="4"; final String EXAMPLE_VALUE_1="exampleValue1"; final String EXAMPLE_VALUE_2="exampleValue2"; /** * Setups storage engine. */ @Before public void setUp() { engine = getResourceEngine(); performSetUp(); } /** * Override this for additional setup */ protected void performSetUp() { // nothing todo } /** * @return configured storage engine */ protected abstract ResourceEngine<I> getResourceEngine(); /** * */ protected abstract I getExampleID(); abstract class AbstractCreateAndGetResourceTestCase<J> { public abstract LinkedHashMap<String,List<String>> getEntityResources(J entity,List<String> keys); public abstract void setEntityResources(J entity,LinkedHashMap<String, List<String>> resources); public abstract J getExampleEntity(); public void run() { //simple put and get List<String> testList1=new LinkedList<String>(); testList1.add(EXAMPLE_VALUE_1); testList1.add(EXAMPLE_VALUE_2); LinkedHashMap<String, List<String>> testSet1=new LinkedHashMap<String, List<String>>(); testSet1.put(EXAMPLE_KEY_1,testList1); J testEntity=getExampleEntity(); setEntityResources(testEntity,testSet1); @SuppressWarnings({ "unchecked", "rawtypes" }) LinkedHashMap<String,List<String>> result=getEntityResources(testEntity, new LinkedList(testSet1.keySet())); assertNotNull(result); assertNotNull(result.get(EXAMPLE_KEY_1)); assertEquals(2,result.get(EXAMPLE_KEY_1).size()); assertEquals(EXAMPLE_VALUE_1,result.get(EXAMPLE_KEY_1).get(0)); assertEquals(EXAMPLE_VALUE_2,result.get(EXAMPLE_KEY_1).get(1)); //overwrite with fewer list entrys List<String> testList2=new LinkedList<String>(); testList2.add(EXAMPLE_VALUE_1); LinkedHashMap<String, List<String>> testSet2=new LinkedHashMap<String, List<String>>(); testSet2.put(EXAMPLE_KEY_1,testList2); setEntityResources(testEntity,testSet2); @SuppressWarnings({ "rawtypes", "unchecked" }) LinkedHashMap<String,List<String>> result2=getEntityResources(testEntity,new LinkedList(testSet2.keySet())); assertNotNull(result2); assertEquals(1,result2.get(EXAMPLE_KEY_1).size()); assertEquals(EXAMPLE_VALUE_1,result2.get(EXAMPLE_KEY_1).get(0)); //check if you ask for more keys than there are actually stored //return only those which are in there List<String> testList=new LinkedList<String>(); testList.add(EXAMPLE_VALUE_1); testList.add(EXAMPLE_VALUE_2); LinkedHashMap<String, List<String>> testSet3=new LinkedHashMap<String, List<String>>(); - testSet1.put(EXAMPLE_KEY_3,testList); - engine.setGlobalResources(testSet3); + testSet3.put(EXAMPLE_KEY_3,testList); + setEntityResources(testEntity,testSet3); LinkedList<String> keys=new LinkedList<String>(); keys.add(EXAMPLE_KEY_3); keys.add(EXAMPLE_KEY_4); - LinkedHashMap<String,List<String>> result3=engine.getGlobalResources(keys); + LinkedHashMap<String,List<String>> result3=getEntityResources(testEntity,keys); assertNotNull(result3); assertEquals(1,result3.size()); assertNotNull(result3.get(EXAMPLE_KEY_3)); assertEquals(2,result3.get(EXAMPLE_KEY_3).size()); assertNull(result3.get(EXAMPLE_KEY_4)); } } @Test public void testCreateAndGetGlobalResources() { new AbstractCreateAndGetResourceTestCase<String>(){ @Override public LinkedHashMap<String, List<String>> getEntityResources(String entity, List<String> keys) { return engine.getGlobalResources(keys); } @Override public void setEntityResources(String entity, LinkedHashMap<String, List<String>> resources) { engine.setGlobalResources(resources); } @Override public String getExampleEntity() { return null; } }.run(); } @Test public void testMoreGlobalPropertiesRequestedThenExists() { //ask for more keys than there are actually stored. //The keys should be included in the result but have empty entry at the global level } @Test(expected=IllegalArgumentException.class) public void testNullGlobalResource() { engine.setGlobalResources(null); } @Test public void testCreateAndGetProviderResources() { new AbstractCreateAndGetResourceTestCase<Provider<I>>(){ @Override public LinkedHashMap<String, List<String>> getEntityResources(Provider<I> entity, List<String> keys) { return engine.getProviderResources(entity, keys); } @Override public void setEntityResources(Provider<I> entity, LinkedHashMap<String, List<String>> resources) { engine.setProviderResources(entity, resources); } @Override public Provider<I> getExampleEntity() { return new ProviderBean<I>(getExampleID()); } }.run(); } @Test public void testCreateAndGetCollectionResources() { new AbstractCreateAndGetResourceTestCase<Collection<I>>(){ @Override public LinkedHashMap<String, List<String>> getEntityResources(Collection<I> entity, List<String> keys) { return engine.getCollectionResources(entity, keys); } @Override public void setEntityResources(Collection<I> entity, LinkedHashMap<String, List<String>> resources) { engine.setCollectionResources(entity, resources); } @Override public Collection<I> getExampleEntity() { return new CollectionBean<I>(getExampleID(),new ProviderBean<I>(getExampleID())); } }.run(); } }
false
true
public void run() { //simple put and get List<String> testList1=new LinkedList<String>(); testList1.add(EXAMPLE_VALUE_1); testList1.add(EXAMPLE_VALUE_2); LinkedHashMap<String, List<String>> testSet1=new LinkedHashMap<String, List<String>>(); testSet1.put(EXAMPLE_KEY_1,testList1); J testEntity=getExampleEntity(); setEntityResources(testEntity,testSet1); @SuppressWarnings({ "unchecked", "rawtypes" }) LinkedHashMap<String,List<String>> result=getEntityResources(testEntity, new LinkedList(testSet1.keySet())); assertNotNull(result); assertNotNull(result.get(EXAMPLE_KEY_1)); assertEquals(2,result.get(EXAMPLE_KEY_1).size()); assertEquals(EXAMPLE_VALUE_1,result.get(EXAMPLE_KEY_1).get(0)); assertEquals(EXAMPLE_VALUE_2,result.get(EXAMPLE_KEY_1).get(1)); //overwrite with fewer list entrys List<String> testList2=new LinkedList<String>(); testList2.add(EXAMPLE_VALUE_1); LinkedHashMap<String, List<String>> testSet2=new LinkedHashMap<String, List<String>>(); testSet2.put(EXAMPLE_KEY_1,testList2); setEntityResources(testEntity,testSet2); @SuppressWarnings({ "rawtypes", "unchecked" }) LinkedHashMap<String,List<String>> result2=getEntityResources(testEntity,new LinkedList(testSet2.keySet())); assertNotNull(result2); assertEquals(1,result2.get(EXAMPLE_KEY_1).size()); assertEquals(EXAMPLE_VALUE_1,result2.get(EXAMPLE_KEY_1).get(0)); //check if you ask for more keys than there are actually stored //return only those which are in there List<String> testList=new LinkedList<String>(); testList.add(EXAMPLE_VALUE_1); testList.add(EXAMPLE_VALUE_2); LinkedHashMap<String, List<String>> testSet3=new LinkedHashMap<String, List<String>>(); testSet1.put(EXAMPLE_KEY_3,testList); engine.setGlobalResources(testSet3); LinkedList<String> keys=new LinkedList<String>(); keys.add(EXAMPLE_KEY_3); keys.add(EXAMPLE_KEY_4); LinkedHashMap<String,List<String>> result3=engine.getGlobalResources(keys); assertNotNull(result3); assertEquals(1,result3.size()); assertNotNull(result3.get(EXAMPLE_KEY_3)); assertEquals(2,result3.get(EXAMPLE_KEY_3).size()); assertNull(result3.get(EXAMPLE_KEY_4)); }
public void run() { //simple put and get List<String> testList1=new LinkedList<String>(); testList1.add(EXAMPLE_VALUE_1); testList1.add(EXAMPLE_VALUE_2); LinkedHashMap<String, List<String>> testSet1=new LinkedHashMap<String, List<String>>(); testSet1.put(EXAMPLE_KEY_1,testList1); J testEntity=getExampleEntity(); setEntityResources(testEntity,testSet1); @SuppressWarnings({ "unchecked", "rawtypes" }) LinkedHashMap<String,List<String>> result=getEntityResources(testEntity, new LinkedList(testSet1.keySet())); assertNotNull(result); assertNotNull(result.get(EXAMPLE_KEY_1)); assertEquals(2,result.get(EXAMPLE_KEY_1).size()); assertEquals(EXAMPLE_VALUE_1,result.get(EXAMPLE_KEY_1).get(0)); assertEquals(EXAMPLE_VALUE_2,result.get(EXAMPLE_KEY_1).get(1)); //overwrite with fewer list entrys List<String> testList2=new LinkedList<String>(); testList2.add(EXAMPLE_VALUE_1); LinkedHashMap<String, List<String>> testSet2=new LinkedHashMap<String, List<String>>(); testSet2.put(EXAMPLE_KEY_1,testList2); setEntityResources(testEntity,testSet2); @SuppressWarnings({ "rawtypes", "unchecked" }) LinkedHashMap<String,List<String>> result2=getEntityResources(testEntity,new LinkedList(testSet2.keySet())); assertNotNull(result2); assertEquals(1,result2.get(EXAMPLE_KEY_1).size()); assertEquals(EXAMPLE_VALUE_1,result2.get(EXAMPLE_KEY_1).get(0)); //check if you ask for more keys than there are actually stored //return only those which are in there List<String> testList=new LinkedList<String>(); testList.add(EXAMPLE_VALUE_1); testList.add(EXAMPLE_VALUE_2); LinkedHashMap<String, List<String>> testSet3=new LinkedHashMap<String, List<String>>(); testSet3.put(EXAMPLE_KEY_3,testList); setEntityResources(testEntity,testSet3); LinkedList<String> keys=new LinkedList<String>(); keys.add(EXAMPLE_KEY_3); keys.add(EXAMPLE_KEY_4); LinkedHashMap<String,List<String>> result3=getEntityResources(testEntity,keys); assertNotNull(result3); assertEquals(1,result3.size()); assertNotNull(result3.get(EXAMPLE_KEY_3)); assertEquals(2,result3.get(EXAMPLE_KEY_3).size()); assertNull(result3.get(EXAMPLE_KEY_4)); }
diff --git a/projects/impl/src/main/java/org/jboss/forge/addon/projects/impl/NewProjectWizard.java b/projects/impl/src/main/java/org/jboss/forge/addon/projects/impl/NewProjectWizard.java index 65ad00d58..9433bfa3a 100644 --- a/projects/impl/src/main/java/org/jboss/forge/addon/projects/impl/NewProjectWizard.java +++ b/projects/impl/src/main/java/org/jboss/forge/addon/projects/impl/NewProjectWizard.java @@ -1,231 +1,235 @@ package org.jboss.forge.addon.projects.impl; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.concurrent.Callable; import javax.inject.Inject; import org.jboss.forge.addon.convert.Converter; import org.jboss.forge.addon.projects.Project; import org.jboss.forge.addon.projects.ProjectFactory; import org.jboss.forge.addon.projects.ProjectType; import org.jboss.forge.addon.projects.facets.MetadataFacet; import org.jboss.forge.addon.resource.DirectoryResource; import org.jboss.forge.addon.resource.Resource; import org.jboss.forge.addon.resource.ResourceFactory; import org.jboss.forge.addon.ui.context.UIBuilder; import org.jboss.forge.addon.ui.context.UIContext; import org.jboss.forge.addon.ui.context.UISelection; import org.jboss.forge.addon.ui.context.UIValidationContext; import org.jboss.forge.addon.ui.input.SingleValued; import org.jboss.forge.addon.ui.input.UIInput; import org.jboss.forge.addon.ui.input.UISelectOne; import org.jboss.forge.addon.ui.metadata.UICommandMetadata; import org.jboss.forge.addon.ui.metadata.WithAttributes; import org.jboss.forge.addon.ui.result.NavigationResult; import org.jboss.forge.addon.ui.result.Result; import org.jboss.forge.addon.ui.result.Results; import org.jboss.forge.addon.ui.util.Categories; import org.jboss.forge.addon.ui.util.Metadata; import org.jboss.forge.addon.ui.wizard.UIWizard; public class NewProjectWizard implements UIWizard { @Inject private ProjectFactory projectFactory; @Inject private ResourceFactory resourceFactory; @Inject @WithAttributes(label = "Project name:", required = true) private UIInput<String> named; @Inject @WithAttributes(label = "Top level package:", required = true) private UIInput<String> topLevelPackage; @Inject @WithAttributes(label = "Version:", required = false) private UIInput<String> version; @Inject @WithAttributes(label = "Project location:") private UIInput<DirectoryResource> targetLocation; @Inject @WithAttributes(label = "Overwrite existing project location") private UIInput<Boolean> overwrite; @Inject @WithAttributes(label = "Project Type:", required = true) private UISelectOne<ProjectType> type; @Override public UICommandMetadata getMetadata() { return Metadata.forCommand(getClass()).name("New Project").description("Create a new project") .category(Categories.create("Project", "Generation")); } @Override public boolean isEnabled(UIContext context) { return true; } @Override public void initializeUI(final UIBuilder builder) throws Exception { version.setDefaultValue("1.0.0-SNAPSHOT"); UISelection<Resource<?>> currentSelection = builder.getUIContext().getInitialSelection(); if (currentSelection != null) { Resource<?> resource = currentSelection.get(); if (resource instanceof DirectoryResource) { targetLocation.setDefaultValue((DirectoryResource) resource); } } else { targetLocation.setDefaultValue(resourceFactory.create(DirectoryResource.class, new File(""))); } overwrite.setDefaultValue(false).setEnabled(new Callable<Boolean>() { @Override public Boolean call() throws Exception { String projectName = named.getValue(); return targetLocation.getValue() != null && projectName != null && targetLocation.getValue().getChild(projectName).exists() && !targetLocation.getValue().getChild(projectName).listResources().isEmpty(); } }); type.setItemLabelConverter(new Converter<ProjectType, String>() { @Override public String convert(ProjectType source) { return source == null ? null : source.getType(); } }); // Add Project types List<ProjectType> projectTypes = new ArrayList<ProjectType>(); + for (ProjectType projectType : type.getValueChoices()) + { + projectTypes.add(projectType); + } Collections.sort(projectTypes, new Comparator<ProjectType>() { @Override public int compare(ProjectType left, ProjectType right) { if (left == null || left.getType() == null || right == null || right.getType() == null) return 0; return left.getType().compareTo(right.getType()); } }); - if(!projectTypes.isEmpty()) + if (!projectTypes.isEmpty()) { type.setDefaultValue(projectTypes.get(0)); } type.setValueChoices(projectTypes); builder.add(named).add(topLevelPackage).add(version).add(targetLocation).add(overwrite).add(type); } @Override public void validate(UIValidationContext context) { if (!topLevelPackage.getValue().matches("(?i)(~\\.)?([a-z0-9_]+\\.?)+[a-z0-9_]")) { context.addValidationError(topLevelPackage, "Top level package must be a valid package name."); } if (overwrite.isEnabled() && overwrite.getValue() == false) { context.addValidationError(targetLocation, "Target location is not empty."); } } @Override public Result execute(UIContext context) throws Exception { Result result = Results.success("New project has been created."); DirectoryResource directory = targetLocation.getValue(); DirectoryResource targetDir = directory.getChildDirectory(named.getValue()); if (targetDir.mkdirs() || overwrite.getValue()) { ProjectType value = type.getValue(); Project project = null; if (value != null) { project = projectFactory.createProject(targetDir, value.getRequiredFacets()); } else { project = projectFactory.createProject(targetDir); } if (project != null) { MetadataFacet metadataFacet = project.getFacet(MetadataFacet.class); metadataFacet.setProjectName(named.getValue()); metadataFacet.setProjectVersion(version.getValue()); metadataFacet.setTopLevelPackage(topLevelPackage.getValue()); context.setAttribute(Project.class, project); } else result = Results.fail("Could not create project of type: [" + value + "]"); } else result = Results.fail("Could not create target location: " + targetDir); return result; } public UIInput<String> getNamed() { return named; } public UIInput<DirectoryResource> getTargetLocation() { return targetLocation; } public UIInput<Boolean> getOverwrite() { return overwrite; } public UISelectOne<ProjectType> getType() { return type; } public SingleValued<UIInput<String>, String> getTopLevelPackage() { return topLevelPackage; } @Override public NavigationResult next(UIContext context) throws Exception { if (type.getValue() != null) { return Results.navigateTo(type.getValue().getSetupFlow()); } else { return null; } } }
false
true
public void initializeUI(final UIBuilder builder) throws Exception { version.setDefaultValue("1.0.0-SNAPSHOT"); UISelection<Resource<?>> currentSelection = builder.getUIContext().getInitialSelection(); if (currentSelection != null) { Resource<?> resource = currentSelection.get(); if (resource instanceof DirectoryResource) { targetLocation.setDefaultValue((DirectoryResource) resource); } } else { targetLocation.setDefaultValue(resourceFactory.create(DirectoryResource.class, new File(""))); } overwrite.setDefaultValue(false).setEnabled(new Callable<Boolean>() { @Override public Boolean call() throws Exception { String projectName = named.getValue(); return targetLocation.getValue() != null && projectName != null && targetLocation.getValue().getChild(projectName).exists() && !targetLocation.getValue().getChild(projectName).listResources().isEmpty(); } }); type.setItemLabelConverter(new Converter<ProjectType, String>() { @Override public String convert(ProjectType source) { return source == null ? null : source.getType(); } }); // Add Project types List<ProjectType> projectTypes = new ArrayList<ProjectType>(); Collections.sort(projectTypes, new Comparator<ProjectType>() { @Override public int compare(ProjectType left, ProjectType right) { if (left == null || left.getType() == null || right == null || right.getType() == null) return 0; return left.getType().compareTo(right.getType()); } }); if(!projectTypes.isEmpty()) { type.setDefaultValue(projectTypes.get(0)); } type.setValueChoices(projectTypes); builder.add(named).add(topLevelPackage).add(version).add(targetLocation).add(overwrite).add(type); }
public void initializeUI(final UIBuilder builder) throws Exception { version.setDefaultValue("1.0.0-SNAPSHOT"); UISelection<Resource<?>> currentSelection = builder.getUIContext().getInitialSelection(); if (currentSelection != null) { Resource<?> resource = currentSelection.get(); if (resource instanceof DirectoryResource) { targetLocation.setDefaultValue((DirectoryResource) resource); } } else { targetLocation.setDefaultValue(resourceFactory.create(DirectoryResource.class, new File(""))); } overwrite.setDefaultValue(false).setEnabled(new Callable<Boolean>() { @Override public Boolean call() throws Exception { String projectName = named.getValue(); return targetLocation.getValue() != null && projectName != null && targetLocation.getValue().getChild(projectName).exists() && !targetLocation.getValue().getChild(projectName).listResources().isEmpty(); } }); type.setItemLabelConverter(new Converter<ProjectType, String>() { @Override public String convert(ProjectType source) { return source == null ? null : source.getType(); } }); // Add Project types List<ProjectType> projectTypes = new ArrayList<ProjectType>(); for (ProjectType projectType : type.getValueChoices()) { projectTypes.add(projectType); } Collections.sort(projectTypes, new Comparator<ProjectType>() { @Override public int compare(ProjectType left, ProjectType right) { if (left == null || left.getType() == null || right == null || right.getType() == null) return 0; return left.getType().compareTo(right.getType()); } }); if (!projectTypes.isEmpty()) { type.setDefaultValue(projectTypes.get(0)); } type.setValueChoices(projectTypes); builder.add(named).add(topLevelPackage).add(version).add(targetLocation).add(overwrite).add(type); }
diff --git a/src/com/harcourtprogramming/utils/FileUtils.java b/src/com/harcourtprogramming/utils/FileUtils.java index abbac43..7cc2b29 100644 --- a/src/com/harcourtprogramming/utils/FileUtils.java +++ b/src/com/harcourtprogramming/utils/FileUtils.java @@ -1,73 +1,78 @@ package com.harcourtprogramming.utils; import java.io.File; /** * File Untilites funtions * @author Benedict Harcourt */ public final class FileUtils { - public static String realtivePath(File base, File target) + public static String realtivePath(final File base, final File target) { + final File baseDir; if (!base.isDirectory()) { - base = base.getParentFile(); + baseDir = base.getParentFile(); } + else + { + baseDir = base; + } - String[] fromPath = explodedPath(base); - String[] toPath = explodedPath(target); + final String[] fromPath = explodedPath(baseDir); + final String[] toPath = explodedPath(target); - int common; + final int common; int i; for (i = 0; i < Math.min(fromPath.length, toPath.length); i++) { if (!fromPath[i].equals(toPath[i])) { break; } } common = i; if (i == 0) { return target.getPath(); } StringBuilder ret = new StringBuilder(); for (i = common; i < fromPath.length; i++) { ret.append(".."); ret.append(File.separatorChar); } for (i = common; i < toPath.length; i++) { ret.append(toPath[i]); ret.append(File.separatorChar); } ret.deleteCharAt(ret.length() - 1); return ret.toString(); } public static String[] explodedPath(File f) { if (File.separatorChar == '\\') { return f.getPath().split("\\\\"); // Because I hate you java and you lake of split on char or string. } return f.getPath().split(File.separator); } private FileUtils() { // Nothing to see here. Move along, citizen. } }
false
true
public static String realtivePath(File base, File target) { if (!base.isDirectory()) { base = base.getParentFile(); } String[] fromPath = explodedPath(base); String[] toPath = explodedPath(target); int common; int i; for (i = 0; i < Math.min(fromPath.length, toPath.length); i++) { if (!fromPath[i].equals(toPath[i])) { break; } } common = i; if (i == 0) { return target.getPath(); } StringBuilder ret = new StringBuilder(); for (i = common; i < fromPath.length; i++) { ret.append(".."); ret.append(File.separatorChar); } for (i = common; i < toPath.length; i++) { ret.append(toPath[i]); ret.append(File.separatorChar); } ret.deleteCharAt(ret.length() - 1); return ret.toString(); }
public static String realtivePath(final File base, final File target) { final File baseDir; if (!base.isDirectory()) { baseDir = base.getParentFile(); } else { baseDir = base; } final String[] fromPath = explodedPath(baseDir); final String[] toPath = explodedPath(target); final int common; int i; for (i = 0; i < Math.min(fromPath.length, toPath.length); i++) { if (!fromPath[i].equals(toPath[i])) { break; } } common = i; if (i == 0) { return target.getPath(); } StringBuilder ret = new StringBuilder(); for (i = common; i < fromPath.length; i++) { ret.append(".."); ret.append(File.separatorChar); } for (i = common; i < toPath.length; i++) { ret.append(toPath[i]); ret.append(File.separatorChar); } ret.deleteCharAt(ret.length() - 1); return ret.toString(); }
diff --git a/src/main/java/net/aufdemrand/denizen/objects/Element.java b/src/main/java/net/aufdemrand/denizen/objects/Element.java index 6decc53dc..7cb8b3a2d 100644 --- a/src/main/java/net/aufdemrand/denizen/objects/Element.java +++ b/src/main/java/net/aufdemrand/denizen/objects/Element.java @@ -1,497 +1,497 @@ package net.aufdemrand.denizen.objects; import net.aufdemrand.denizen.tags.Attribute; import net.aufdemrand.denizen.utilities.debugging.dB; import org.apache.commons.lang.StringUtils; import org.bukkit.ChatColor; import java.text.DecimalFormat; import java.util.Arrays; import java.util.regex.Pattern; public class Element implements dObject { public final static Element TRUE = new Element(Boolean.TRUE); public final static Element FALSE = new Element(Boolean.FALSE); /** * * @param string the string or dScript argument String * @return a dScript dList * */ @ObjectFetcher("el") public static Element valueOf(String string) { if (string == null) return null; return new Element(string); } public static boolean matches(String string) { return string != null; } private String element; public Element(String string) { this.prefix = "element"; this.element = string; } public Element(Integer integer) { this.prefix = "integer"; this.element = String.valueOf(integer); } public Element(Double dbl) { this.prefix = "double"; this.element = String.valueOf(dbl); } public Element(Boolean bool) { this.prefix = "boolean"; this.element = String.valueOf(bool); } public Element(String prefix, String string) { if (prefix == null) this.prefix = "element"; else this.prefix = prefix; this.element = string; } public double asDouble() { return Double.valueOf(element.replace("%", "")); } public float asFloat() { return Float.valueOf(element.replace("%", "")); } public int asInt() { return Integer.valueOf(element.replace("%", "")); } public boolean asBoolean() { return Boolean.valueOf(element); } public String asString() { return element; } private String prefix; @Override public String getType() { return "Element"; } @Override public String getPrefix() { return prefix; } @Override public dObject setPrefix(String prefix) { this.prefix = prefix; return this; } @Override public String debug() { return (prefix + "='<A>" + identify() + "<G>' "); } @Override public String identify() { return element; } @Override public String toString() { return identify(); } @Override public boolean isUnique() { return false; } @Override public String getAttribute(Attribute attribute) { if (attribute == null) return null; // <-- // <element.asint> -> Element(Number) // Returns the element as a number without a decimal. // --> if (attribute.startsWith("asint") || attribute.startsWith("as_int")) try { // Round the Double instead of just getting its // value as an Integer (which would incorrectly // turn 2.9 into 2) return new Element(String.valueOf (Math.round(Double.valueOf(element)))) .getAttribute(attribute.fulfill(1)); } catch (NumberFormatException e) { dB.echoError("'" + element + "' is not a valid Integer."); - return null; + return new Element("null").getAttribute(attribute.fulfill(1)); } // <-- // <element.asdouble> -> Element(Number) // Returns the element as a number with a decimal. // --> if (attribute.startsWith("asdouble") || attribute.startsWith("as_double")) try { return new Element(String.valueOf(Double.valueOf(element))) .getAttribute(attribute.fulfill(1)); } catch (NumberFormatException e) { dB.echoError("'" + element + "' is not a valid Double."); - return null; + return new Element("null").getAttribute(attribute.fulfill(1)); } // <-- // <element.asmoney> -> Element(Number) // Returns the element as a number with two decimal places. // --> if (attribute.startsWith("asmoney") || attribute.startsWith("as_money")) { try { DecimalFormat d = new DecimalFormat("0.00"); return new Element(String.valueOf(d.format(Double.valueOf(element)))) .getAttribute(attribute.fulfill(1)); } catch (NumberFormatException e) { dB.echoError("'" + element + "' is not a valid Money format."); - return null; + return new Element("null").getAttribute(attribute.fulfill(1)); } } // <-- // <element.asboolean> -> Element(Boolean) // Returns the element as true/false. // --> if (attribute.startsWith("asboolean") || attribute.startsWith("as_boolean")) return new Element(Boolean.valueOf(element).toString()) .getAttribute(attribute.fulfill(1)); // <-- // <element.aslist> -> dList // Returns the element as a list. // --> if (attribute.startsWith("aslist") || attribute.startsWith("as_list")) return dList.valueOf(element).getAttribute(attribute.fulfill(1)); // <-- // <element.asentity> -> dEntity // Returns the element as an entity. // --> if (attribute.startsWith("asentity") || attribute.startsWith("as_entity")) return dEntity.valueOf(element).getAttribute(attribute.fulfill(1)); // <-- // <element.aslocation> -> dLocation // Returns the element as a location. // --> if (attribute.startsWith("aslocation") || attribute.startsWith("as_location")) return dLocation.valueOf(element).getAttribute(attribute.fulfill(1)); // <-- // <element.asplayer> -> dPlayer // Returns the element as a player. // --> if (attribute.startsWith("asplayer") || attribute.startsWith("as_player")) return dPlayer.valueOf(element).getAttribute(attribute.fulfill(1)); // <-- // <element.asnpc> -> dNPC // Returns the element as an NPC. // --> if (attribute.startsWith("asnpc") || attribute.startsWith("as_npc")) return dNPC.valueOf(element).getAttribute(attribute.fulfill(1)); // <-- // <element.asitem> -> dItem // Returns the element as an item. // --> if (attribute.startsWith("asitem") || attribute.startsWith("as_item")) return dItem.valueOf(element).getAttribute(attribute.fulfill(1)); // <-- // <element.asscript> -> dScript // Returns the element as a script. // --> if (attribute.startsWith("asscript") || attribute.startsWith("as_script")) return dScript.valueOf(element).getAttribute(attribute.fulfill(1)); // <-- // <element.asentity> -> Duration // Returns the element as a duration. // --> if (attribute.startsWith("asduration") || attribute.startsWith("as_duration")) return Duration.valueOf(element).getAttribute(attribute.fulfill(1)); // <-- // <element.contains[<string>]> -> Element(Boolean) // Returns whether the element contains a specified string. // --> if (attribute.startsWith("contains")) { String contains = attribute.getContext(1); if (contains.toLowerCase().startsWith("regex:")) { if (Pattern.compile(contains.substring(("regex:").length()), Pattern.CASE_INSENSITIVE).matcher(element).matches()) return new Element("true").getAttribute(attribute.fulfill(1)); else return new Element("false").getAttribute(attribute.fulfill(1)); } else if (element.toLowerCase().contains(contains.toLowerCase())) return new Element("true").getAttribute(attribute.fulfill(1)); else return new Element("false").getAttribute(attribute.fulfill(1)); } // <-- // <element.after[<string>]> -> Element // Returns the portion of an element after a specified string. // --> // Get the substring after a certain text if (attribute.startsWith("after")) { String delimiter = attribute.getContext(1); return new Element(String.valueOf(element.substring (element.indexOf(delimiter) + delimiter.length()))) .getAttribute(attribute.fulfill(1)); } // <-- // <element.before[<string>]> -> Element // Returns the portion of an element before a specified string. // --> // Get the substring before a certain text if (attribute.startsWith("before")) { String delimiter = attribute.getContext(1); return new Element(String.valueOf(element.substring (0, element.indexOf(delimiter)))) .getAttribute(attribute.fulfill(1)); } // <-- // <element.substring[<#>(,<#>)]> -> Element // Returns the portion of an element between two string indices. // If no second index is specified, it will return the portion of an // element after the specified index. // --> if (attribute.startsWith("substring")||attribute.startsWith("substr")) { // substring[2,8] int beginning_index = Integer.valueOf(attribute.getContext(1).split(",")[0]) - 1; int ending_index; if (attribute.getContext(1).split(",").length > 1) ending_index = Integer.valueOf(attribute.getContext(1).split(",")[1]) - 1; else ending_index = element.length(); return new Element(String.valueOf(element.substring(beginning_index, ending_index))) .getAttribute(attribute.fulfill(1)); } if (attribute.startsWith("last_color")) return new Element(String.valueOf(ChatColor.getLastColors(element))).getAttribute(attribute.fulfill(1)); // <-- // <element.strip_color> -> Element // Returns the element with all color encoding stripped. // --> if (attribute.startsWith("strip_color")) return new Element(String.valueOf(ChatColor.stripColor(element))).getAttribute(attribute.fulfill(1)); // <-- // <element.startswith[<string>]> -> Element(Boolean) // Returns whether the element starts with a specified string. // --> if (attribute.startsWith("starts_with") || attribute.startsWith("startswith")) return new Element(String.valueOf(element.startsWith(attribute.getContext(1)))).getAttribute(attribute.fulfill(1)); // <-- // <element.endswith[<string>]> -> Element(Boolean) // Returns whether the element ends with a specified string. // --> if (attribute.startsWith("ends_with") || attribute.startsWith("endswith")) return new Element(String.valueOf(element.endsWith(attribute.getContext(1)))).getAttribute(attribute.fulfill(1)); // <-- // <element.split[<string>].limit[<#>]> -> dList // Returns a list of portions of this element, split by the specified string, // and capped at the specified number of max list items. // --> if (attribute.startsWith("split") && attribute.startsWith("limit", 2)) { String split_string = (attribute.hasContext(1) ? attribute.getContext(1) : " "); Integer limit = (attribute.hasContext(2) ? attribute.getIntContext(2) : 1); if (split_string.toLowerCase().startsWith("regex:")) return new dList(Arrays.asList(element.split(split_string.split(":", 2)[1], limit))) .getAttribute(attribute.fulfill(1)); else return new dList(Arrays.asList(StringUtils.split(element, split_string, limit))) .getAttribute(attribute.fulfill(1)); } // <-- // <element.split[<string>]> -> dList // Returns a list of portions of this element, split by the specified string. // --> if (attribute.startsWith("split")) { String split_string = (attribute.hasContext(1) ? attribute.getContext(1) : " "); if (split_string.toLowerCase().startsWith("regex:")) return new dList(Arrays.asList(element.split(split_string.split(":", 2)[1]))) .getAttribute(attribute.fulfill(1)); else return new dList(Arrays.asList(StringUtils.split(element, split_string))) .getAttribute(attribute.fulfill(1)); } // <-- // <element.sqrt> -> Element(Number) // Returns the square root of the element. // --> if (attribute.startsWith("sqrt")) { return new Element(Math.sqrt(asDouble())) .getAttribute(attribute.fulfill(1)); } // <-- // <element.abs> -> Element(Number) // Returns the absolute value of the element. // --> if (attribute.startsWith("abs")) { return new Element(Math.abs(asDouble())) .getAttribute(attribute.fulfill(1)); } // <-- // <element.mul[<#>]> -> Element(Number) // Returns the element multiplied by a number. // --> if (attribute.startsWith("mul") && attribute.hasContext(1)) { return new Element(asDouble() * aH.getDoubleFrom(attribute.getContext(1))) .getAttribute(attribute.fulfill(1)); } // <-- // <element.sub[<#>]> -> Element(Number) // Returns the element minus a number. // --> if (attribute.startsWith("sub") && attribute.hasContext(1)) { return new Element(asDouble() - aH.getDoubleFrom(attribute.getContext(1))) .getAttribute(attribute.fulfill(1)); } // <-- // <element.add[<#>]> -> Element(Number) // Returns the element plus a number. // --> if (attribute.startsWith("add") && attribute.hasContext(1)) { return new Element(asDouble() + aH.getDoubleFrom(attribute.getContext(1))) .getAttribute(attribute.fulfill(1)); } // <-- // <element.div[<#>]> -> Element(Number) // Returns the element divided by a number. // --> if (attribute.startsWith("div") && attribute.hasContext(1)) { return new Element(asDouble() / aH.getDoubleFrom(attribute.getContext(1))) .getAttribute(attribute.fulfill(1)); } // <-- // <element.mod[<#>]> -> Element(Number) // Returns the remainder of the element divided by a number. // --> if (attribute.startsWith("mod") && attribute.hasContext(1)) { return new Element(asDouble() % aH.getDoubleFrom(attribute.getContext(1))) .getAttribute(attribute.fulfill(1)); } // <-- // <element.replace[<string>]> -> Element // Returns the element with all instances of a string removed. // --> // <-- // <element.replace[<string>].with[<string>]> -> Element // Returns the element with all instances of a string replaced with another. // --> if (attribute.startsWith("replace") && attribute.hasContext(1)) { String replace = attribute.getContext(1); String replacement = ""; if (attribute.startsWith("with", 2)) { if (attribute.hasContext(2)) replacement = attribute.getContext(2); attribute.fulfill(1); } return new Element(element.replace(replace, replacement)) .getAttribute(attribute.fulfill(1)); } // <-- // <element.length> -> Element(Number) // Returns the length of the element. // --> if (attribute.startsWith("length")) { return new Element(element.length()) .getAttribute(attribute.fulfill(1)); } // <-- // <element.prefix> -> Element // Returns the prefix of the element. // --> if (attribute.startsWith("prefix")) return new Element(prefix) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("debug.log")) { dB.log(debug()); return new Element(Boolean.TRUE.toString()) .getAttribute(attribute.fulfill(2)); } if (attribute.startsWith("debug.no_color")) { return new Element(ChatColor.stripColor(debug())) .getAttribute(attribute.fulfill(2)); } if (attribute.startsWith("debug")) { return new Element(debug()) .getAttribute(attribute.fulfill(1)); } // Unfilled attributes past this point probably means the tag is spelled // incorrectly. So instead of just passing through what's been resolved // so far, 'null' shall be returned with an error message. if (attribute.attributes.size() > 0) { dB.echoError("Unfilled attributes '" + attribute.attributes.toString() + "'" + "for tag <" + attribute.getOrigin() + ">!"); return "null"; } else { dB.log("Filled tag <" + attribute.getOrigin() + "> with '" + element + "'."); return element; } } }
false
true
public String getAttribute(Attribute attribute) { if (attribute == null) return null; // <-- // <element.asint> -> Element(Number) // Returns the element as a number without a decimal. // --> if (attribute.startsWith("asint") || attribute.startsWith("as_int")) try { // Round the Double instead of just getting its // value as an Integer (which would incorrectly // turn 2.9 into 2) return new Element(String.valueOf (Math.round(Double.valueOf(element)))) .getAttribute(attribute.fulfill(1)); } catch (NumberFormatException e) { dB.echoError("'" + element + "' is not a valid Integer."); return null; } // <-- // <element.asdouble> -> Element(Number) // Returns the element as a number with a decimal. // --> if (attribute.startsWith("asdouble") || attribute.startsWith("as_double")) try { return new Element(String.valueOf(Double.valueOf(element))) .getAttribute(attribute.fulfill(1)); } catch (NumberFormatException e) { dB.echoError("'" + element + "' is not a valid Double."); return null; } // <-- // <element.asmoney> -> Element(Number) // Returns the element as a number with two decimal places. // --> if (attribute.startsWith("asmoney") || attribute.startsWith("as_money")) { try { DecimalFormat d = new DecimalFormat("0.00"); return new Element(String.valueOf(d.format(Double.valueOf(element)))) .getAttribute(attribute.fulfill(1)); } catch (NumberFormatException e) { dB.echoError("'" + element + "' is not a valid Money format."); return null; } } // <-- // <element.asboolean> -> Element(Boolean) // Returns the element as true/false. // --> if (attribute.startsWith("asboolean") || attribute.startsWith("as_boolean")) return new Element(Boolean.valueOf(element).toString()) .getAttribute(attribute.fulfill(1)); // <-- // <element.aslist> -> dList // Returns the element as a list. // --> if (attribute.startsWith("aslist") || attribute.startsWith("as_list")) return dList.valueOf(element).getAttribute(attribute.fulfill(1)); // <-- // <element.asentity> -> dEntity // Returns the element as an entity. // --> if (attribute.startsWith("asentity") || attribute.startsWith("as_entity")) return dEntity.valueOf(element).getAttribute(attribute.fulfill(1)); // <-- // <element.aslocation> -> dLocation // Returns the element as a location. // --> if (attribute.startsWith("aslocation") || attribute.startsWith("as_location")) return dLocation.valueOf(element).getAttribute(attribute.fulfill(1)); // <-- // <element.asplayer> -> dPlayer // Returns the element as a player. // --> if (attribute.startsWith("asplayer") || attribute.startsWith("as_player")) return dPlayer.valueOf(element).getAttribute(attribute.fulfill(1)); // <-- // <element.asnpc> -> dNPC // Returns the element as an NPC. // --> if (attribute.startsWith("asnpc") || attribute.startsWith("as_npc")) return dNPC.valueOf(element).getAttribute(attribute.fulfill(1)); // <-- // <element.asitem> -> dItem // Returns the element as an item. // --> if (attribute.startsWith("asitem") || attribute.startsWith("as_item")) return dItem.valueOf(element).getAttribute(attribute.fulfill(1)); // <-- // <element.asscript> -> dScript // Returns the element as a script. // --> if (attribute.startsWith("asscript") || attribute.startsWith("as_script")) return dScript.valueOf(element).getAttribute(attribute.fulfill(1)); // <-- // <element.asentity> -> Duration // Returns the element as a duration. // --> if (attribute.startsWith("asduration") || attribute.startsWith("as_duration")) return Duration.valueOf(element).getAttribute(attribute.fulfill(1)); // <-- // <element.contains[<string>]> -> Element(Boolean) // Returns whether the element contains a specified string. // --> if (attribute.startsWith("contains")) { String contains = attribute.getContext(1); if (contains.toLowerCase().startsWith("regex:")) { if (Pattern.compile(contains.substring(("regex:").length()), Pattern.CASE_INSENSITIVE).matcher(element).matches()) return new Element("true").getAttribute(attribute.fulfill(1)); else return new Element("false").getAttribute(attribute.fulfill(1)); } else if (element.toLowerCase().contains(contains.toLowerCase())) return new Element("true").getAttribute(attribute.fulfill(1)); else return new Element("false").getAttribute(attribute.fulfill(1)); } // <-- // <element.after[<string>]> -> Element // Returns the portion of an element after a specified string. // --> // Get the substring after a certain text if (attribute.startsWith("after")) { String delimiter = attribute.getContext(1); return new Element(String.valueOf(element.substring (element.indexOf(delimiter) + delimiter.length()))) .getAttribute(attribute.fulfill(1)); } // <-- // <element.before[<string>]> -> Element // Returns the portion of an element before a specified string. // --> // Get the substring before a certain text if (attribute.startsWith("before")) { String delimiter = attribute.getContext(1); return new Element(String.valueOf(element.substring (0, element.indexOf(delimiter)))) .getAttribute(attribute.fulfill(1)); } // <-- // <element.substring[<#>(,<#>)]> -> Element // Returns the portion of an element between two string indices. // If no second index is specified, it will return the portion of an // element after the specified index. // --> if (attribute.startsWith("substring")||attribute.startsWith("substr")) { // substring[2,8] int beginning_index = Integer.valueOf(attribute.getContext(1).split(",")[0]) - 1; int ending_index; if (attribute.getContext(1).split(",").length > 1) ending_index = Integer.valueOf(attribute.getContext(1).split(",")[1]) - 1; else ending_index = element.length(); return new Element(String.valueOf(element.substring(beginning_index, ending_index))) .getAttribute(attribute.fulfill(1)); } if (attribute.startsWith("last_color")) return new Element(String.valueOf(ChatColor.getLastColors(element))).getAttribute(attribute.fulfill(1)); // <-- // <element.strip_color> -> Element // Returns the element with all color encoding stripped. // --> if (attribute.startsWith("strip_color")) return new Element(String.valueOf(ChatColor.stripColor(element))).getAttribute(attribute.fulfill(1)); // <-- // <element.startswith[<string>]> -> Element(Boolean) // Returns whether the element starts with a specified string. // --> if (attribute.startsWith("starts_with") || attribute.startsWith("startswith")) return new Element(String.valueOf(element.startsWith(attribute.getContext(1)))).getAttribute(attribute.fulfill(1)); // <-- // <element.endswith[<string>]> -> Element(Boolean) // Returns whether the element ends with a specified string. // --> if (attribute.startsWith("ends_with") || attribute.startsWith("endswith")) return new Element(String.valueOf(element.endsWith(attribute.getContext(1)))).getAttribute(attribute.fulfill(1)); // <-- // <element.split[<string>].limit[<#>]> -> dList // Returns a list of portions of this element, split by the specified string, // and capped at the specified number of max list items. // --> if (attribute.startsWith("split") && attribute.startsWith("limit", 2)) { String split_string = (attribute.hasContext(1) ? attribute.getContext(1) : " "); Integer limit = (attribute.hasContext(2) ? attribute.getIntContext(2) : 1); if (split_string.toLowerCase().startsWith("regex:")) return new dList(Arrays.asList(element.split(split_string.split(":", 2)[1], limit))) .getAttribute(attribute.fulfill(1)); else return new dList(Arrays.asList(StringUtils.split(element, split_string, limit))) .getAttribute(attribute.fulfill(1)); } // <-- // <element.split[<string>]> -> dList // Returns a list of portions of this element, split by the specified string. // --> if (attribute.startsWith("split")) { String split_string = (attribute.hasContext(1) ? attribute.getContext(1) : " "); if (split_string.toLowerCase().startsWith("regex:")) return new dList(Arrays.asList(element.split(split_string.split(":", 2)[1]))) .getAttribute(attribute.fulfill(1)); else return new dList(Arrays.asList(StringUtils.split(element, split_string))) .getAttribute(attribute.fulfill(1)); } // <-- // <element.sqrt> -> Element(Number) // Returns the square root of the element. // --> if (attribute.startsWith("sqrt")) { return new Element(Math.sqrt(asDouble())) .getAttribute(attribute.fulfill(1)); } // <-- // <element.abs> -> Element(Number) // Returns the absolute value of the element. // --> if (attribute.startsWith("abs")) { return new Element(Math.abs(asDouble())) .getAttribute(attribute.fulfill(1)); } // <-- // <element.mul[<#>]> -> Element(Number) // Returns the element multiplied by a number. // --> if (attribute.startsWith("mul") && attribute.hasContext(1)) { return new Element(asDouble() * aH.getDoubleFrom(attribute.getContext(1))) .getAttribute(attribute.fulfill(1)); } // <-- // <element.sub[<#>]> -> Element(Number) // Returns the element minus a number. // --> if (attribute.startsWith("sub") && attribute.hasContext(1)) { return new Element(asDouble() - aH.getDoubleFrom(attribute.getContext(1))) .getAttribute(attribute.fulfill(1)); } // <-- // <element.add[<#>]> -> Element(Number) // Returns the element plus a number. // --> if (attribute.startsWith("add") && attribute.hasContext(1)) { return new Element(asDouble() + aH.getDoubleFrom(attribute.getContext(1))) .getAttribute(attribute.fulfill(1)); } // <-- // <element.div[<#>]> -> Element(Number) // Returns the element divided by a number. // --> if (attribute.startsWith("div") && attribute.hasContext(1)) { return new Element(asDouble() / aH.getDoubleFrom(attribute.getContext(1))) .getAttribute(attribute.fulfill(1)); } // <-- // <element.mod[<#>]> -> Element(Number) // Returns the remainder of the element divided by a number. // --> if (attribute.startsWith("mod") && attribute.hasContext(1)) { return new Element(asDouble() % aH.getDoubleFrom(attribute.getContext(1))) .getAttribute(attribute.fulfill(1)); } // <-- // <element.replace[<string>]> -> Element // Returns the element with all instances of a string removed. // --> // <-- // <element.replace[<string>].with[<string>]> -> Element // Returns the element with all instances of a string replaced with another. // --> if (attribute.startsWith("replace") && attribute.hasContext(1)) { String replace = attribute.getContext(1); String replacement = ""; if (attribute.startsWith("with", 2)) { if (attribute.hasContext(2)) replacement = attribute.getContext(2); attribute.fulfill(1); } return new Element(element.replace(replace, replacement)) .getAttribute(attribute.fulfill(1)); } // <-- // <element.length> -> Element(Number) // Returns the length of the element. // --> if (attribute.startsWith("length")) { return new Element(element.length()) .getAttribute(attribute.fulfill(1)); } // <-- // <element.prefix> -> Element // Returns the prefix of the element. // --> if (attribute.startsWith("prefix")) return new Element(prefix) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("debug.log")) { dB.log(debug()); return new Element(Boolean.TRUE.toString()) .getAttribute(attribute.fulfill(2)); } if (attribute.startsWith("debug.no_color")) { return new Element(ChatColor.stripColor(debug())) .getAttribute(attribute.fulfill(2)); } if (attribute.startsWith("debug")) { return new Element(debug()) .getAttribute(attribute.fulfill(1)); } // Unfilled attributes past this point probably means the tag is spelled // incorrectly. So instead of just passing through what's been resolved // so far, 'null' shall be returned with an error message. if (attribute.attributes.size() > 0) { dB.echoError("Unfilled attributes '" + attribute.attributes.toString() + "'" + "for tag <" + attribute.getOrigin() + ">!"); return "null"; } else { dB.log("Filled tag <" + attribute.getOrigin() + "> with '" + element + "'."); return element; } }
public String getAttribute(Attribute attribute) { if (attribute == null) return null; // <-- // <element.asint> -> Element(Number) // Returns the element as a number without a decimal. // --> if (attribute.startsWith("asint") || attribute.startsWith("as_int")) try { // Round the Double instead of just getting its // value as an Integer (which would incorrectly // turn 2.9 into 2) return new Element(String.valueOf (Math.round(Double.valueOf(element)))) .getAttribute(attribute.fulfill(1)); } catch (NumberFormatException e) { dB.echoError("'" + element + "' is not a valid Integer."); return new Element("null").getAttribute(attribute.fulfill(1)); } // <-- // <element.asdouble> -> Element(Number) // Returns the element as a number with a decimal. // --> if (attribute.startsWith("asdouble") || attribute.startsWith("as_double")) try { return new Element(String.valueOf(Double.valueOf(element))) .getAttribute(attribute.fulfill(1)); } catch (NumberFormatException e) { dB.echoError("'" + element + "' is not a valid Double."); return new Element("null").getAttribute(attribute.fulfill(1)); } // <-- // <element.asmoney> -> Element(Number) // Returns the element as a number with two decimal places. // --> if (attribute.startsWith("asmoney") || attribute.startsWith("as_money")) { try { DecimalFormat d = new DecimalFormat("0.00"); return new Element(String.valueOf(d.format(Double.valueOf(element)))) .getAttribute(attribute.fulfill(1)); } catch (NumberFormatException e) { dB.echoError("'" + element + "' is not a valid Money format."); return new Element("null").getAttribute(attribute.fulfill(1)); } } // <-- // <element.asboolean> -> Element(Boolean) // Returns the element as true/false. // --> if (attribute.startsWith("asboolean") || attribute.startsWith("as_boolean")) return new Element(Boolean.valueOf(element).toString()) .getAttribute(attribute.fulfill(1)); // <-- // <element.aslist> -> dList // Returns the element as a list. // --> if (attribute.startsWith("aslist") || attribute.startsWith("as_list")) return dList.valueOf(element).getAttribute(attribute.fulfill(1)); // <-- // <element.asentity> -> dEntity // Returns the element as an entity. // --> if (attribute.startsWith("asentity") || attribute.startsWith("as_entity")) return dEntity.valueOf(element).getAttribute(attribute.fulfill(1)); // <-- // <element.aslocation> -> dLocation // Returns the element as a location. // --> if (attribute.startsWith("aslocation") || attribute.startsWith("as_location")) return dLocation.valueOf(element).getAttribute(attribute.fulfill(1)); // <-- // <element.asplayer> -> dPlayer // Returns the element as a player. // --> if (attribute.startsWith("asplayer") || attribute.startsWith("as_player")) return dPlayer.valueOf(element).getAttribute(attribute.fulfill(1)); // <-- // <element.asnpc> -> dNPC // Returns the element as an NPC. // --> if (attribute.startsWith("asnpc") || attribute.startsWith("as_npc")) return dNPC.valueOf(element).getAttribute(attribute.fulfill(1)); // <-- // <element.asitem> -> dItem // Returns the element as an item. // --> if (attribute.startsWith("asitem") || attribute.startsWith("as_item")) return dItem.valueOf(element).getAttribute(attribute.fulfill(1)); // <-- // <element.asscript> -> dScript // Returns the element as a script. // --> if (attribute.startsWith("asscript") || attribute.startsWith("as_script")) return dScript.valueOf(element).getAttribute(attribute.fulfill(1)); // <-- // <element.asentity> -> Duration // Returns the element as a duration. // --> if (attribute.startsWith("asduration") || attribute.startsWith("as_duration")) return Duration.valueOf(element).getAttribute(attribute.fulfill(1)); // <-- // <element.contains[<string>]> -> Element(Boolean) // Returns whether the element contains a specified string. // --> if (attribute.startsWith("contains")) { String contains = attribute.getContext(1); if (contains.toLowerCase().startsWith("regex:")) { if (Pattern.compile(contains.substring(("regex:").length()), Pattern.CASE_INSENSITIVE).matcher(element).matches()) return new Element("true").getAttribute(attribute.fulfill(1)); else return new Element("false").getAttribute(attribute.fulfill(1)); } else if (element.toLowerCase().contains(contains.toLowerCase())) return new Element("true").getAttribute(attribute.fulfill(1)); else return new Element("false").getAttribute(attribute.fulfill(1)); } // <-- // <element.after[<string>]> -> Element // Returns the portion of an element after a specified string. // --> // Get the substring after a certain text if (attribute.startsWith("after")) { String delimiter = attribute.getContext(1); return new Element(String.valueOf(element.substring (element.indexOf(delimiter) + delimiter.length()))) .getAttribute(attribute.fulfill(1)); } // <-- // <element.before[<string>]> -> Element // Returns the portion of an element before a specified string. // --> // Get the substring before a certain text if (attribute.startsWith("before")) { String delimiter = attribute.getContext(1); return new Element(String.valueOf(element.substring (0, element.indexOf(delimiter)))) .getAttribute(attribute.fulfill(1)); } // <-- // <element.substring[<#>(,<#>)]> -> Element // Returns the portion of an element between two string indices. // If no second index is specified, it will return the portion of an // element after the specified index. // --> if (attribute.startsWith("substring")||attribute.startsWith("substr")) { // substring[2,8] int beginning_index = Integer.valueOf(attribute.getContext(1).split(",")[0]) - 1; int ending_index; if (attribute.getContext(1).split(",").length > 1) ending_index = Integer.valueOf(attribute.getContext(1).split(",")[1]) - 1; else ending_index = element.length(); return new Element(String.valueOf(element.substring(beginning_index, ending_index))) .getAttribute(attribute.fulfill(1)); } if (attribute.startsWith("last_color")) return new Element(String.valueOf(ChatColor.getLastColors(element))).getAttribute(attribute.fulfill(1)); // <-- // <element.strip_color> -> Element // Returns the element with all color encoding stripped. // --> if (attribute.startsWith("strip_color")) return new Element(String.valueOf(ChatColor.stripColor(element))).getAttribute(attribute.fulfill(1)); // <-- // <element.startswith[<string>]> -> Element(Boolean) // Returns whether the element starts with a specified string. // --> if (attribute.startsWith("starts_with") || attribute.startsWith("startswith")) return new Element(String.valueOf(element.startsWith(attribute.getContext(1)))).getAttribute(attribute.fulfill(1)); // <-- // <element.endswith[<string>]> -> Element(Boolean) // Returns whether the element ends with a specified string. // --> if (attribute.startsWith("ends_with") || attribute.startsWith("endswith")) return new Element(String.valueOf(element.endsWith(attribute.getContext(1)))).getAttribute(attribute.fulfill(1)); // <-- // <element.split[<string>].limit[<#>]> -> dList // Returns a list of portions of this element, split by the specified string, // and capped at the specified number of max list items. // --> if (attribute.startsWith("split") && attribute.startsWith("limit", 2)) { String split_string = (attribute.hasContext(1) ? attribute.getContext(1) : " "); Integer limit = (attribute.hasContext(2) ? attribute.getIntContext(2) : 1); if (split_string.toLowerCase().startsWith("regex:")) return new dList(Arrays.asList(element.split(split_string.split(":", 2)[1], limit))) .getAttribute(attribute.fulfill(1)); else return new dList(Arrays.asList(StringUtils.split(element, split_string, limit))) .getAttribute(attribute.fulfill(1)); } // <-- // <element.split[<string>]> -> dList // Returns a list of portions of this element, split by the specified string. // --> if (attribute.startsWith("split")) { String split_string = (attribute.hasContext(1) ? attribute.getContext(1) : " "); if (split_string.toLowerCase().startsWith("regex:")) return new dList(Arrays.asList(element.split(split_string.split(":", 2)[1]))) .getAttribute(attribute.fulfill(1)); else return new dList(Arrays.asList(StringUtils.split(element, split_string))) .getAttribute(attribute.fulfill(1)); } // <-- // <element.sqrt> -> Element(Number) // Returns the square root of the element. // --> if (attribute.startsWith("sqrt")) { return new Element(Math.sqrt(asDouble())) .getAttribute(attribute.fulfill(1)); } // <-- // <element.abs> -> Element(Number) // Returns the absolute value of the element. // --> if (attribute.startsWith("abs")) { return new Element(Math.abs(asDouble())) .getAttribute(attribute.fulfill(1)); } // <-- // <element.mul[<#>]> -> Element(Number) // Returns the element multiplied by a number. // --> if (attribute.startsWith("mul") && attribute.hasContext(1)) { return new Element(asDouble() * aH.getDoubleFrom(attribute.getContext(1))) .getAttribute(attribute.fulfill(1)); } // <-- // <element.sub[<#>]> -> Element(Number) // Returns the element minus a number. // --> if (attribute.startsWith("sub") && attribute.hasContext(1)) { return new Element(asDouble() - aH.getDoubleFrom(attribute.getContext(1))) .getAttribute(attribute.fulfill(1)); } // <-- // <element.add[<#>]> -> Element(Number) // Returns the element plus a number. // --> if (attribute.startsWith("add") && attribute.hasContext(1)) { return new Element(asDouble() + aH.getDoubleFrom(attribute.getContext(1))) .getAttribute(attribute.fulfill(1)); } // <-- // <element.div[<#>]> -> Element(Number) // Returns the element divided by a number. // --> if (attribute.startsWith("div") && attribute.hasContext(1)) { return new Element(asDouble() / aH.getDoubleFrom(attribute.getContext(1))) .getAttribute(attribute.fulfill(1)); } // <-- // <element.mod[<#>]> -> Element(Number) // Returns the remainder of the element divided by a number. // --> if (attribute.startsWith("mod") && attribute.hasContext(1)) { return new Element(asDouble() % aH.getDoubleFrom(attribute.getContext(1))) .getAttribute(attribute.fulfill(1)); } // <-- // <element.replace[<string>]> -> Element // Returns the element with all instances of a string removed. // --> // <-- // <element.replace[<string>].with[<string>]> -> Element // Returns the element with all instances of a string replaced with another. // --> if (attribute.startsWith("replace") && attribute.hasContext(1)) { String replace = attribute.getContext(1); String replacement = ""; if (attribute.startsWith("with", 2)) { if (attribute.hasContext(2)) replacement = attribute.getContext(2); attribute.fulfill(1); } return new Element(element.replace(replace, replacement)) .getAttribute(attribute.fulfill(1)); } // <-- // <element.length> -> Element(Number) // Returns the length of the element. // --> if (attribute.startsWith("length")) { return new Element(element.length()) .getAttribute(attribute.fulfill(1)); } // <-- // <element.prefix> -> Element // Returns the prefix of the element. // --> if (attribute.startsWith("prefix")) return new Element(prefix) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("debug.log")) { dB.log(debug()); return new Element(Boolean.TRUE.toString()) .getAttribute(attribute.fulfill(2)); } if (attribute.startsWith("debug.no_color")) { return new Element(ChatColor.stripColor(debug())) .getAttribute(attribute.fulfill(2)); } if (attribute.startsWith("debug")) { return new Element(debug()) .getAttribute(attribute.fulfill(1)); } // Unfilled attributes past this point probably means the tag is spelled // incorrectly. So instead of just passing through what's been resolved // so far, 'null' shall be returned with an error message. if (attribute.attributes.size() > 0) { dB.echoError("Unfilled attributes '" + attribute.attributes.toString() + "'" + "for tag <" + attribute.getOrigin() + ">!"); return "null"; } else { dB.log("Filled tag <" + attribute.getOrigin() + "> with '" + element + "'."); return element; } }
diff --git a/SIMSOnline/src/test/Sims_1.java b/SIMSOnline/src/test/Sims_1.java index 67147ba..bd0f9b1 100644 --- a/SIMSOnline/src/test/Sims_1.java +++ b/SIMSOnline/src/test/Sims_1.java @@ -1,1699 +1,1699 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package test; import java.awt.CardLayout; import java.awt.event.MouseEvent; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JDialog; /** * * @author Stazzer */ public class Sims_1 extends javax.swing.JFrame { /** * Creates new form Sims */ public CardLayout cl; public Game game; Item item = new Item(); CoinExchange exchange = new CoinExchange(); public Sims_1() { initComponents(); setSize(1000, 700); buyCoins.setSize(400, 320); buyCoins.setDefaultCloseOperation(DISPOSE_ON_CLOSE); dialog_error.setSize(400, 320); dialog_error.setDefaultCloseOperation(DISPOSE_ON_CLOSE); jPanel2.setVisible(false); cl = (CardLayout)(jPanel2.getLayout()); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buyCoins = new javax.swing.JDialog(); label_swapper = new javax.swing.JLabel(); label_swapperUcoins = new javax.swing.JLabel(); label_swapperUcoinsAmount = new javax.swing.JLabel(); label_swapperCredits = new javax.swing.JLabel(); label_swapperCreditsAmount = new javax.swing.JLabel(); label_currentExchange = new javax.swing.JLabel(); textfield_swapperUcoins = new javax.swing.JTextField(); button_swapperExchange = new javax.swing.JButton(); button_swapperAbord = new javax.swing.JButton(); textfield_swapperCredits = new javax.swing.JTextField(); label_swapperArrow1 = new javax.swing.JLabel(); label_swapperArrow3 = new javax.swing.JLabel(); dialog_error = new javax.swing.JDialog(); label_shopMessage = new javax.swing.JLabel(); label_shopMessage1 = new javax.swing.JLabel(); label_shopMessage2 = new javax.swing.JLabel(); button_shopMessageOk = new javax.swing.JButton(); jPanel1 = new javax.swing.JPanel(); startPlanningGame = new javax.swing.JPanel(); Menu_overlay = new javax.swing.JLabel(); startNewGame = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); exit = new javax.swing.JButton(); loadGame = new javax.swing.JButton(); jButton6 = new javax.swing.JButton(); jButton7 = new javax.swing.JButton(); jButton8 = new javax.swing.JButton(); jButton13 = new javax.swing.JButton(); jPanel2 = new javax.swing.JPanel(); gamePlanning = new javax.swing.JPanel(); Logo = new javax.swing.JPanel(); jLab_Logo = new javax.swing.JLabel(); Header = new javax.swing.JPanel(); jLabel41 = new javax.swing.JLabel(); jLabel42 = new javax.swing.JLabel(); jLabel43 = new javax.swing.JLabel(); jProgB_Müdigkeit = new javax.swing.JProgressBar(); jProgB_Motivation = new javax.swing.JProgressBar(); jProgB_Wissen = new javax.swing.JProgressBar(); jLabel3 = new javax.swing.JLabel(); Shop = new javax.swing.JPanel(); jBut_startShop = new javax.swing.JButton(); Navi = new javax.swing.JPanel(); jPan_StudSwitch = new javax.swing.JPanel(); jLab_StudSwitch = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel90 = new javax.swing.JLabel(); jLab_StudCounter = new javax.swing.JLabel(); jBut_BackG = new javax.swing.JButton(); jPan_DozSwitch = new javax.swing.JPanel(); jLab_DozSwitch = new javax.swing.JLabel(); jLabel91 = new javax.swing.JLabel(); jLabel27 = new javax.swing.JLabel(); jLab_DozCounter = new javax.swing.JLabel(); jBut_BackG2 = new javax.swing.JButton(); jPan_ItemSelect = new javax.swing.JPanel(); jComboB_Items = new javax.swing.JComboBox(); jBut_ComboB_useItem = new javax.swing.JButton(); jPan_ItemStorage = new javax.swing.JPanel(); jLabel8 = new javax.swing.JLabel(); jLab_Redbull = new javax.swing.JLabel(); jLab_Duplo = new javax.swing.JLabel(); jLab_OMNI = new javax.swing.JLabel(); jPanel32 = new javax.swing.JPanel(); jBut_Play = new javax.swing.JButton(); StudField = new javax.swing.JPanel(); jBut_Dozent = new javax.swing.JButton(); jBut_1 = new javax.swing.JButton(); jBut_2 = new javax.swing.JButton(); jBut_3 = new javax.swing.JButton(); jBut_4 = new javax.swing.JButton(); jBut_5 = new javax.swing.JButton(); jBut_6 = new javax.swing.JButton(); jBut_7 = new javax.swing.JButton(); jBut_8 = new javax.swing.JButton(); jBut_9 = new javax.swing.JButton(); jBut_10 = new javax.swing.JButton(); jBut_11 = new javax.swing.JButton(); jBut_12 = new javax.swing.JButton(); jBut_13 = new javax.swing.JButton(); jBut_14 = new javax.swing.JButton(); jBut_15 = new javax.swing.JButton(); jBut_16 = new javax.swing.JButton(); jBut_17 = new javax.swing.JButton(); jBut_18 = new javax.swing.JButton(); jBut_19 = new javax.swing.JButton(); jBut_20 = new javax.swing.JButton(); jBut_21 = new javax.swing.JButton(); jBut_22 = new javax.swing.JButton(); jBut_23 = new javax.swing.JButton(); jBut_24 = new javax.swing.JButton(); jBut_25 = new javax.swing.JButton(); jBut_26 = new javax.swing.JButton(); jBut_27 = new javax.swing.JButton(); jBut_28 = new javax.swing.JButton(); jBut_29 = new javax.swing.JButton(); jBut_30 = new javax.swing.JButton(); shop = new javax.swing.JPanel(); jPanel18 = new javax.swing.JPanel(); jLabel55 = new javax.swing.JLabel(); jPanel19 = new javax.swing.JPanel(); label_inventar = new javax.swing.JLabel(); jLabel58 = new javax.swing.JLabel(); jLabel59 = new javax.swing.JLabel(); jLabel60 = new javax.swing.JLabel(); jLabel61 = new javax.swing.JLabel(); label_item4 = new javax.swing.JLabel(); label_item1 = new javax.swing.JLabel(); label_item2 = new javax.swing.JLabel(); label_item1Name = new javax.swing.JLabel(); label_item1Amount = new javax.swing.JLabel(); label_item2Name = new javax.swing.JLabel(); label_item2Amount = new javax.swing.JLabel(); label_item3Name = new javax.swing.JLabel(); label_item3Amount = new javax.swing.JLabel(); label_item3 = new javax.swing.JLabel(); label_item4Name = new javax.swing.JLabel(); label_item4Amount = new javax.swing.JLabel(); jPanel20 = new javax.swing.JPanel(); ucoinsShop = new javax.swing.JLabel(); creditsShop = new javax.swing.JLabel(); punkteShop = new javax.swing.JLabel(); jButton12 = new javax.swing.JButton(); jLabel70 = new javax.swing.JLabel(); jLabel71 = new javax.swing.JLabel(); jLabel72 = new javax.swing.JLabel(); jLabel85 = new javax.swing.JLabel(); jPanel21 = new javax.swing.JPanel(); jLabel54 = new javax.swing.JLabel(); jPanel22 = new javax.swing.JPanel(); label_redBullOverlay = new javax.swing.JLabel(); label_cheatSheetOverlay = new javax.swing.JLabel(); label_omniOverlay = new javax.swing.JLabel(); label_duploOverlay = new javax.swing.JLabel(); panel_redBull = new javax.swing.JPanel(); label_redBullName = new javax.swing.JLabel(); label_redBullAmount = new javax.swing.JLabel(); label_redBullLocked = new javax.swing.JLabel(); jPanel23 = new javax.swing.JPanel(); label_omniName = new javax.swing.JLabel(); label_omniLocked = new javax.swing.JLabel(); label_omniAmount = new javax.swing.JLabel(); panel_duplo = new javax.swing.JPanel(); label_duploName = new javax.swing.JLabel(); label_duploAmount = new javax.swing.JLabel(); label_duploLocked = new javax.swing.JLabel(); panel_cheatSheet = new javax.swing.JPanel(); label_cheatSheetName = new javax.swing.JLabel(); label_cheatSheetLocked = new javax.swing.JLabel(); label_cheatSheetAmount = new javax.swing.JLabel(); gamePlaying = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jPanel4 = new javax.swing.JPanel(); jLabel11 = new javax.swing.JLabel(); label_item3Inv = new javax.swing.JLabel(); jLabel18 = new javax.swing.JLabel(); jLabel19 = new javax.swing.JLabel(); jLabel20 = new javax.swing.JLabel(); jLabel21 = new javax.swing.JLabel(); label_ucoinsInv = new javax.swing.JLabel(); label_item2Inv = new javax.swing.JLabel(); label_creditsInv = new javax.swing.JLabel(); label_item3InvName = new javax.swing.JLabel(); label_item3InvAmount = new javax.swing.JLabel(); label_item1Inv = new javax.swing.JLabel(); jLabel13 = new javax.swing.JLabel(); jLabel14 = new javax.swing.JLabel(); label_item1InvName = new javax.swing.JLabel(); label_item2InvName = new javax.swing.JLabel(); label_item2InvAmount = new javax.swing.JLabel(); label_item1InvAmount = new javax.swing.JLabel(); jPanel5 = new javax.swing.JPanel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jProgressBar1 = new javax.swing.JProgressBar(); jProgressBar2 = new javax.swing.JProgressBar(); jProgressBar4 = new javax.swing.JProgressBar(); jButton1 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); jButton5 = new javax.swing.JButton(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); jProgressBar5 = new javax.swing.JProgressBar(); jProgressBar6 = new javax.swing.JProgressBar(); jPanel6 = new javax.swing.JPanel(); label_timer = new javax.swing.JLabel(); jPanel7 = new javax.swing.JPanel(); buyCoins.getContentPane().setLayout(null); label_swapper.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N label_swapper.setText("UCoins => Credits Tausch"); buyCoins.getContentPane().add(label_swapper); label_swapper.setBounds(30, 20, 370, 60); label_swapperUcoins.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N label_swapperUcoins.setText("UCoins:"); buyCoins.getContentPane().add(label_swapperUcoins); label_swapperUcoins.setBounds(50, 90, 80, 30); label_swapperUcoinsAmount.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N label_swapperUcoinsAmount.setText("5"); buyCoins.getContentPane().add(label_swapperUcoinsAmount); label_swapperUcoinsAmount.setBounds(120, 80, 80, 50); label_swapperCredits.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N label_swapperCredits.setText("Credits:"); buyCoins.getContentPane().add(label_swapperCredits); label_swapperCredits.setBounds(50, 160, 70, 30); label_swapperCreditsAmount.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N label_swapperCreditsAmount.setText("600"); buyCoins.getContentPane().add(label_swapperCreditsAmount); label_swapperCreditsAmount.setBounds(120, 150, 80, 50); label_currentExchange.setText("1 UCoin = 100 Credits"); buyCoins.getContentPane().add(label_currentExchange); label_currentExchange.setBounds(230, 120, 140, 40); textfield_swapperUcoins.setMinimumSize(new java.awt.Dimension(30, 20)); textfield_swapperUcoins.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { textfield_swapperUcoinsKeyReleased(evt); } }); buyCoins.getContentPane().add(textfield_swapperUcoins); textfield_swapperUcoins.setBounds(170, 90, 50, 30); button_swapperExchange.setText("Tauschen"); button_swapperExchange.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { button_swapperExchangeActionPerformed(evt); } }); buyCoins.getContentPane().add(button_swapperExchange); button_swapperExchange.setBounds(50, 220, 130, 23); button_swapperAbord.setText("Abbrechen"); button_swapperAbord.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { button_swapperAbordActionPerformed(evt); } }); buyCoins.getContentPane().add(button_swapperAbord); button_swapperAbord.setBounds(210, 220, 130, 23); textfield_swapperCredits.setEditable(false); textfield_swapperCredits.setMinimumSize(new java.awt.Dimension(30, 20)); buyCoins.getContentPane().add(textfield_swapperCredits); textfield_swapperCredits.setBounds(170, 160, 50, 30); label_swapperArrow1.setText("||"); buyCoins.getContentPane().add(label_swapperArrow1); label_swapperArrow1.setBounds(190, 130, 8, 14); label_swapperArrow3.setText("\\/"); buyCoins.getContentPane().add(label_swapperArrow3); label_swapperArrow3.setBounds(190, 140, 40, 14); dialog_error.getContentPane().setLayout(null); label_shopMessage.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); label_shopMessage.setText("Shop - Mitteilung"); dialog_error.getContentPane().add(label_shopMessage); label_shopMessage.setBounds(50, 10, 290, 70); label_shopMessage1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); label_shopMessage1.setText("Erwerbe neue Credits im Spiel oder tausche UCoins!"); dialog_error.getContentPane().add(label_shopMessage1); label_shopMessage1.setBounds(10, 110, 380, 70); label_shopMessage2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); label_shopMessage2.setText("Du hast leider nicht mehr genug Credits/UCoins um das Item zu kaufen"); dialog_error.getContentPane().add(label_shopMessage2); label_shopMessage2.setBounds(10, 80, 380, 70); button_shopMessageOk.setText("OK"); button_shopMessageOk.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { button_shopMessageOkActionPerformed(evt); } }); dialog_error.getContentPane().add(button_shopMessageOk); button_shopMessageOk.setBounds(170, 210, 47, 23); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setMaximumSize(new java.awt.Dimension(1000, 700)); setMinimumSize(new java.awt.Dimension(1000, 700)); setResizable(false); getContentPane().setLayout(new java.awt.GridLayout(1, 0)); jPanel1.setMaximumSize(new java.awt.Dimension(1000, 700)); jPanel1.setMinimumSize(new java.awt.Dimension(1000, 700)); jPanel1.setPreferredSize(new java.awt.Dimension(1000, 700)); jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); startPlanningGame.setMaximumSize(new java.awt.Dimension(1000, 700)); startPlanningGame.setMinimumSize(new java.awt.Dimension(1000, 700)); startPlanningGame.setName(""); // NOI18N startPlanningGame.setPreferredSize(new java.awt.Dimension(1000, 700)); startPlanningGame.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); - Menu_overlay.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pictures/hauptmenü1000x700_00000.png"))); // NOI18N + Menu_overlay.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pictures/hauptmenue1000x700.png"))); // NOI18N Menu_overlay.setText("Overlay_hauptmenü"); startPlanningGame.add(Menu_overlay, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1)); startNewGame.setText("Neues Spiel"); startNewGame.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { startNewGameActionPerformed(evt); } }); startPlanningGame.add(startNewGame, new org.netbeans.lib.awtextra.AbsoluteConstraints(640, 200, 160, 40)); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N jLabel1.setText("SIMS Test Menü"); jLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); startPlanningGame.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(340, 100, 330, 80)); exit.setText("Beenden"); exit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exitActionPerformed(evt); } }); startPlanningGame.add(exit, new org.netbeans.lib.awtextra.AbsoluteConstraints(640, 440, 160, 40)); loadGame.setText("Spiel Laden"); loadGame.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { loadGameActionPerformed(evt); } }); startPlanningGame.add(loadGame, new org.netbeans.lib.awtextra.AbsoluteConstraints(620, 240, 210, 40)); jButton6.setText("Credits"); jButton6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton6ActionPerformed(evt); } }); startPlanningGame.add(jButton6, new org.netbeans.lib.awtextra.AbsoluteConstraints(640, 360, 160, 40)); jButton7.setText("Profil"); jButton7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton7ActionPerformed(evt); } }); startPlanningGame.add(jButton7, new org.netbeans.lib.awtextra.AbsoluteConstraints(650, 280, 160, 40)); jButton8.setText("Abmelden"); jButton8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton8ActionPerformed(evt); } }); startPlanningGame.add(jButton8, new org.netbeans.lib.awtextra.AbsoluteConstraints(640, 400, 160, 40)); jButton13.setText("Statistik"); jButton13.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton13ActionPerformed(evt); } }); startPlanningGame.add(jButton13, new org.netbeans.lib.awtextra.AbsoluteConstraints(650, 320, 160, 40)); jPanel1.add(startPlanningGame, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1000, 700)); jPanel2.setLayout(new java.awt.CardLayout()); gamePlanning.setName("card3"); // NOI18N gamePlanning.setLayout(null); Logo.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); Logo.setLayout(null); jLab_Logo.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLab_Logo.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLab_Logo.setText("SIMS Logo"); jLab_Logo.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLab_LogoMouseClicked(evt); } }); Logo.add(jLab_Logo); jLab_Logo.setBounds(0, 0, 150, 110); gamePlanning.add(Logo); Logo.setBounds(0, 0, 150, 110); Header.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); Header.setLayout(null); jLabel41.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel41.setText("Wissen:"); Header.add(jLabel41); jLabel41.setBounds(10, 20, 70, 20); jLabel42.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel42.setText("Motivation:"); Header.add(jLabel42); jLabel42.setBounds(10, 40, 80, 30); jLabel43.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel43.setText("Müdigkeit:"); Header.add(jLabel43); jLabel43.setBounds(10, 80, 90, 20); Header.add(jProgB_Müdigkeit); jProgB_Müdigkeit.setBounds(90, 80, 260, 20); Header.add(jProgB_Motivation); jProgB_Motivation.setBounds(90, 50, 260, 20); Header.add(jProgB_Wissen); jProgB_Wissen.setBounds(90, 20, 260, 20); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N jLabel3.setText("PLANUNGSPHASE"); Header.add(jLabel3); jLabel3.setBounds(360, 10, 340, 90); gamePlanning.add(Header); Header.setBounds(150, 0, 700, 110); Shop.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); Shop.setLayout(null); jBut_startShop.setFont(new java.awt.Font("Lucida Grande", 1, 24)); // NOI18N jBut_startShop.setText("SHOP"); jBut_startShop.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jBut_startShopMouseClicked(evt); } }); jBut_startShop.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBut_startShopActionPerformed(evt); } }); Shop.add(jBut_startShop); jBut_startShop.setBounds(5, 5, 120, 100); gamePlanning.add(Shop); Shop.setBounds(850, 0, 130, 110); Navi.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); Navi.setLayout(null); jPan_StudSwitch.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPan_StudSwitch.setLayout(null); jPan_StudSwitch.add(jLab_StudSwitch); jLab_StudSwitch.setBounds(0, 0, 150, 110); jLabel4.setText("umsetzen"); jPan_StudSwitch.add(jLabel4); jLabel4.setBounds(40, 40, 70, 14); jLabel90.setText("Studenten"); jPan_StudSwitch.add(jLabel90); jLabel90.setBounds(40, 20, 70, 20); jLab_StudCounter.setFont(new java.awt.Font("Lucida Grande", 1, 18)); // NOI18N jLab_StudCounter.setText("5x"); jPan_StudSwitch.add(jLab_StudCounter); jLab_StudCounter.setBounds(60, 60, 30, 24); jBut_BackG.setFont(new java.awt.Font("Lucida Grande", 1, 18)); // NOI18N jBut_BackG.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBut_BackGActionPerformed(evt); } }); jPan_StudSwitch.add(jBut_BackG); jBut_BackG.setBounds(10, 10, 130, 90); Navi.add(jPan_StudSwitch); jPan_StudSwitch.setBounds(0, 0, 150, 110); jPan_StudSwitch.getAccessibleContext().setAccessibleDescription(""); jPan_DozSwitch.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPan_DozSwitch.setLayout(null); jPan_DozSwitch.add(jLab_DozSwitch); jLab_DozSwitch.setBounds(0, 0, 150, 110); jLabel91.setText("Dozenten"); jPan_DozSwitch.add(jLabel91); jLabel91.setBounds(40, 20, 70, 20); jLabel27.setText("tauschen"); jPan_DozSwitch.add(jLabel27); jLabel27.setBounds(40, 40, 60, 20); jLab_DozCounter.setFont(new java.awt.Font("Lucida Grande", 1, 18)); // NOI18N jLab_DozCounter.setText("1x"); jPan_DozSwitch.add(jLab_DozCounter); jLab_DozCounter.setBounds(60, 60, 30, 30); jBut_BackG2.setFont(new java.awt.Font("Lucida Grande", 1, 18)); // NOI18N jBut_BackG2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBut_BackG2ActionPerformed(evt); } }); jPan_DozSwitch.add(jBut_BackG2); jBut_BackG2.setBounds(10, 10, 130, 90); Navi.add(jPan_DozSwitch); jPan_DozSwitch.setBounds(0, 110, 150, 110); jPan_ItemSelect.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPan_ItemSelect.setLayout(null); jComboB_Items.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "wähle Item", "Spicker" })); jPan_ItemSelect.add(jComboB_Items); jComboB_Items.setBounds(10, 20, 130, 30); jBut_ComboB_useItem.setText("Benutzen"); jPan_ItemSelect.add(jBut_ComboB_useItem); jBut_ComboB_useItem.setBounds(10, 60, 120, 23); Navi.add(jPan_ItemSelect); jPan_ItemSelect.setBounds(0, 220, 150, 110); jPan_ItemStorage.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPan_ItemStorage.setLayout(null); jLabel8.setFont(new java.awt.Font("Lucida Grande", 1, 14)); // NOI18N jLabel8.setText("Item-Vorräte"); jPan_ItemStorage.add(jLabel8); jLabel8.setBounds(10, 10, 120, 20); jLab_Redbull.setText("Redbull: 5"); jPan_ItemStorage.add(jLab_Redbull); jLab_Redbull.setBounds(10, 40, 90, 14); jLab_Duplo.setText("Duplo: 3"); jPan_ItemStorage.add(jLab_Duplo); jLab_Duplo.setBounds(10, 60, 90, 14); jLab_OMNI.setText("OMNI Sense Buch: 1"); jPan_ItemStorage.add(jLab_OMNI); jLab_OMNI.setBounds(10, 80, 140, 14); Navi.add(jPan_ItemStorage); jPan_ItemStorage.setBounds(0, 330, 150, 110); jPanel32.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel32.setLayout(null); jBut_Play.setFont(new java.awt.Font("Lucida Grande", 1, 18)); // NOI18N jBut_Play.setText("SPIELEN"); jBut_Play.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBut_PlayActionPerformed(evt); } }); jPanel32.add(jBut_Play); jBut_Play.setBounds(10, 10, 130, 90); Navi.add(jPanel32); jPanel32.setBounds(0, 440, 150, 110); gamePlanning.add(Navi); Navi.setBounds(0, 110, 150, 550); StudField.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); StudField.setLayout(null); jBut_Dozent.setText("Dozent"); StudField.add(jBut_Dozent); jBut_Dozent.setBounds(340, 470, 110, 50); jBut_1.setText("Platz_1"); jBut_1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBut_1ActionPerformed(evt); } }); StudField.add(jBut_1); jBut_1.setBounds(60, 10, 110, 50); jBut_2.setText("Platz_2"); StudField.add(jBut_2); jBut_2.setBounds(210, 10, 110, 50); jBut_3.setText("Platz_3"); StudField.add(jBut_3); jBut_3.setBounds(360, 10, 110, 50); jBut_4.setText("Platz_4"); StudField.add(jBut_4); jBut_4.setBounds(510, 10, 110, 50); jBut_5.setText("Platz_5"); StudField.add(jBut_5); jBut_5.setBounds(660, 10, 110, 50); jBut_6.setText("Platz_6"); StudField.add(jBut_6); jBut_6.setBounds(60, 80, 110, 50); jBut_7.setText("Platz_7"); StudField.add(jBut_7); jBut_7.setBounds(210, 80, 110, 50); jBut_8.setText("Platz_8"); StudField.add(jBut_8); jBut_8.setBounds(360, 80, 110, 50); jBut_9.setText("Platz_9"); StudField.add(jBut_9); jBut_9.setBounds(510, 80, 110, 50); jBut_10.setText("Platz_10"); StudField.add(jBut_10); jBut_10.setBounds(660, 80, 110, 50); jBut_11.setText("Platz_11"); StudField.add(jBut_11); jBut_11.setBounds(60, 150, 110, 50); jBut_12.setText("Platz_12"); StudField.add(jBut_12); jBut_12.setBounds(210, 150, 110, 50); jBut_13.setText("Platz_13"); StudField.add(jBut_13); jBut_13.setBounds(360, 150, 110, 50); jBut_14.setText("Platz_14"); StudField.add(jBut_14); jBut_14.setBounds(510, 150, 110, 50); jBut_15.setText("Platz_15"); StudField.add(jBut_15); jBut_15.setBounds(660, 150, 110, 50); jBut_16.setText("Platz_16"); StudField.add(jBut_16); jBut_16.setBounds(60, 220, 110, 50); jBut_17.setText("Platz_17"); jBut_17.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBut_17ActionPerformed(evt); } }); StudField.add(jBut_17); jBut_17.setBounds(210, 220, 110, 50); jBut_18.setText("Platz_18"); StudField.add(jBut_18); jBut_18.setBounds(360, 220, 110, 50); jBut_19.setText("Platz_19"); StudField.add(jBut_19); jBut_19.setBounds(510, 220, 110, 50); jBut_20.setText("Platz_20"); StudField.add(jBut_20); jBut_20.setBounds(660, 220, 110, 50); jBut_21.setText("Platz_21"); StudField.add(jBut_21); jBut_21.setBounds(60, 290, 110, 50); jBut_22.setText("Platz_22"); StudField.add(jBut_22); jBut_22.setBounds(210, 290, 110, 50); jBut_23.setText("Platz_23"); StudField.add(jBut_23); jBut_23.setBounds(360, 290, 110, 50); jBut_24.setText("Platz_24"); StudField.add(jBut_24); jBut_24.setBounds(510, 290, 110, 50); jBut_25.setText("Platz_25"); StudField.add(jBut_25); jBut_25.setBounds(660, 290, 110, 50); jBut_26.setText("Platz_26"); StudField.add(jBut_26); jBut_26.setBounds(60, 360, 110, 50); jBut_27.setText("Platz_27"); jBut_27.setToolTipText(""); StudField.add(jBut_27); jBut_27.setBounds(210, 360, 110, 50); jBut_28.setText("Platz_28"); StudField.add(jBut_28); jBut_28.setBounds(360, 360, 110, 50); jBut_29.setText("Platz_29"); StudField.add(jBut_29); jBut_29.setBounds(510, 360, 110, 50); jBut_30.setText("Platz_30"); StudField.add(jBut_30); jBut_30.setBounds(660, 360, 110, 50); gamePlanning.add(StudField); StudField.setBounds(150, 110, 830, 550); jPanel2.add(gamePlanning, "card3"); shop.setLayout(null); jPanel18.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel18.setLayout(null); jLabel55.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel55.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel55.setText("SIMS Logo"); jLabel55.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel55MouseClicked(evt); } }); jPanel18.add(jLabel55); jLabel55.setBounds(0, 0, 150, 110); shop.add(jPanel18); jPanel18.setBounds(0, 0, 150, 110); jPanel19.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel19.setLayout(null); label_inventar.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N label_inventar.setText("Inventar"); jPanel19.add(label_inventar); label_inventar.setBounds(30, 0, 120, 40); jLabel58.setText("Studenten:"); jPanel19.add(jLabel58); jLabel58.setBounds(10, 450, 80, 14); jLabel59.setText("4 / 40"); jPanel19.add(jLabel59); jLabel59.setBounds(80, 450, 50, 14); jLabel60.setText("Semester: "); jPanel19.add(jLabel60); jLabel60.setBounds(10, 470, 80, 14); jLabel61.setText("3 / 6"); jPanel19.add(jLabel61); jLabel61.setBounds(80, 470, 60, 14); label_item4.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel19.add(label_item4); label_item4.setBounds(30, 350, 90, 80); label_item1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel19.add(label_item1); label_item1.setBounds(30, 50, 90, 80); label_item2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); label_item2.setPreferredSize(new java.awt.Dimension(20, 20)); jPanel19.add(label_item2); label_item2.setBounds(30, 150, 90, 80); label_item1Name.setText("jLabel4"); jPanel19.add(label_item1Name); label_item1Name.setBounds(60, 80, 34, 14); label_item1Amount.setText("jLabel4"); jPanel19.add(label_item1Amount); label_item1Amount.setBounds(60, 100, 34, 14); label_item2Name.setText("jLabel4"); jPanel19.add(label_item2Name); label_item2Name.setBounds(60, 190, 34, 14); label_item2Amount.setText("jLabel4"); jPanel19.add(label_item2Amount); label_item2Amount.setBounds(60, 210, 34, 14); label_item3Name.setText("jLabel4"); jPanel19.add(label_item3Name); label_item3Name.setBounds(60, 380, 34, 14); label_item3Amount.setText("jLabel26"); jPanel19.add(label_item3Amount); label_item3Amount.setBounds(60, 400, 40, 14); label_item3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel19.add(label_item3); label_item3.setBounds(30, 250, 90, 80); label_item4Name.setText("jLabel4"); jPanel19.add(label_item4Name); label_item4Name.setBounds(60, 280, 34, 14); label_item4Amount.setText("jLabel26"); jPanel19.add(label_item4Amount); label_item4Amount.setBounds(60, 300, 40, 14); shop.add(jPanel19); jPanel19.setBounds(0, 110, 150, 550); jPanel20.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel20.setLayout(null); ucoinsShop.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N ucoinsShop.setText("0"); jPanel20.add(ucoinsShop); ucoinsShop.setBounds(80, 10, 80, 20); creditsShop.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N creditsShop.setText("0"); jPanel20.add(creditsShop); creditsShop.setBounds(80, 40, 70, 17); punkteShop.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N punkteShop.setText("0"); jPanel20.add(punkteShop); punkteShop.setBounds(80, 70, 70, 17); jButton12.setText("UCoins Tauschen"); jButton12.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton12ActionPerformed(evt); } }); jPanel20.add(jButton12); jButton12.setBounds(230, 10, 160, 90); jLabel70.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel70.setText("UCoins:"); jPanel20.add(jLabel70); jLabel70.setBounds(10, 10, 80, 20); jLabel71.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel71.setText("Credits:"); jPanel20.add(jLabel71); jLabel71.setBounds(10, 40, 70, 17); jLabel72.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel72.setText("Punkte:"); jPanel20.add(jLabel72); jLabel72.setBounds(10, 70, 70, 17); jLabel85.setFont(new java.awt.Font("Tahoma", 1, 48)); // NOI18N jLabel85.setText("SHOP"); jPanel20.add(jLabel85); jLabel85.setBounds(470, 0, 210, 110); shop.add(jPanel20); jPanel20.setBounds(150, 0, 700, 110); jPanel21.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel21.setLayout(null); jLabel54.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel54.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel54.setText("SPIEL"); jLabel54.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel54MouseClicked(evt); } }); jPanel21.add(jLabel54); jLabel54.setBounds(0, 0, 130, 110); shop.add(jPanel21); jPanel21.setBounds(850, 0, 130, 110); jPanel22.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel22.setLayout(null); label_redBullOverlay.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); label_redBullOverlay.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { label_redBullOverlayMouseClicked(evt); } }); jPanel22.add(label_redBullOverlay); label_redBullOverlay.setBounds(100, 40, 230, 220); label_cheatSheetOverlay.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); label_cheatSheetOverlay.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { label_cheatSheetOverlayMouseClicked(evt); } }); jPanel22.add(label_cheatSheetOverlay); label_cheatSheetOverlay.setBounds(100, 300, 230, 220); label_omniOverlay.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); label_omniOverlay.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { label_omniOverlayMouseClicked(evt); } }); jPanel22.add(label_omniOverlay); label_omniOverlay.setBounds(510, 300, 230, 220); label_duploOverlay.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); label_duploOverlay.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { label_duploOverlayMouseClicked(evt); } }); jPanel22.add(label_duploOverlay); label_duploOverlay.setBounds(510, 40, 230, 220); panel_redBull.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); panel_redBull.setName("panel_redBull"); // NOI18N panel_redBull.setLayout(null); label_redBullName.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N label_redBullName.setText("Red Bull"); panel_redBull.add(label_redBullName); label_redBullName.setBounds(0, 130, 230, 30); label_redBullAmount.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N label_redBullAmount.setText("100 Credits"); panel_redBull.add(label_redBullAmount); label_redBullAmount.setBounds(0, 150, 230, 50); label_redBullLocked.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N label_redBullLocked.setForeground(new java.awt.Color(204, 51, 0)); label_redBullLocked.setText("GESPERRT"); panel_redBull.add(label_redBullLocked); label_redBullLocked.setBounds(50, 10, 230, 110); jPanel22.add(panel_redBull); panel_redBull.setBounds(100, 40, 230, 220); jPanel23.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel23.setLayout(null); label_omniName.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N label_omniName.setText("Verfügbar ab Semester 4"); jPanel23.add(label_omniName); label_omniName.setBounds(0, 120, 230, 50); label_omniLocked.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N label_omniLocked.setForeground(new java.awt.Color(204, 51, 0)); label_omniLocked.setText("GESPERRT"); jPanel23.add(label_omniLocked); label_omniLocked.setBounds(50, 20, 230, 110); label_omniAmount.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N label_omniAmount.setText("5 UCoins"); jPanel23.add(label_omniAmount); label_omniAmount.setBounds(0, 150, 230, 50); jPanel22.add(jPanel23); jPanel23.setBounds(510, 300, 230, 220); panel_duplo.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); panel_duplo.setLayout(null); label_duploName.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N label_duploName.setText("Duplo"); panel_duplo.add(label_duploName); label_duploName.setBounds(0, 130, 230, 30); label_duploAmount.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N label_duploAmount.setText("100 Credits"); panel_duplo.add(label_duploAmount); label_duploAmount.setBounds(0, 150, 230, 50); label_duploLocked.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N label_duploLocked.setForeground(new java.awt.Color(204, 51, 0)); label_duploLocked.setText("GESPERRT"); panel_duplo.add(label_duploLocked); label_duploLocked.setBounds(50, 10, 230, 110); jPanel22.add(panel_duplo); panel_duplo.setBounds(510, 40, 230, 220); panel_cheatSheet.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); panel_cheatSheet.setLayout(null); label_cheatSheetName.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N label_cheatSheetName.setText("Spicker"); panel_cheatSheet.add(label_cheatSheetName); label_cheatSheetName.setBounds(0, 130, 230, 30); label_cheatSheetLocked.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N label_cheatSheetLocked.setForeground(new java.awt.Color(204, 51, 0)); label_cheatSheetLocked.setText("GESPERRT"); panel_cheatSheet.add(label_cheatSheetLocked); label_cheatSheetLocked.setBounds(50, 10, 230, 110); label_cheatSheetAmount.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N label_cheatSheetAmount.setText("5 UCoins"); panel_cheatSheet.add(label_cheatSheetAmount); label_cheatSheetAmount.setBounds(0, 150, 230, 50); jPanel22.add(panel_cheatSheet); panel_cheatSheet.setBounds(100, 300, 230, 220); shop.add(jPanel22); jPanel22.setBounds(150, 110, 830, 550); jPanel2.add(shop, "card4"); gamePlaying.setMinimumSize(new java.awt.Dimension(1024, 768)); gamePlaying.setPreferredSize(new java.awt.Dimension(1024, 768)); gamePlaying.setLayout(null); jPanel3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel3.setLayout(null); jLabel2.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel2.setText("SIMS Logo"); jLabel2.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel2MouseClicked(evt); } }); jPanel3.add(jLabel2); jLabel2.setBounds(0, 0, 150, 110); gamePlaying.add(jPanel3); jPanel3.setBounds(0, 0, 150, 110); jPanel4.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel4.setLayout(null); jLabel11.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel11.setText("Inventar"); jPanel4.add(jLabel11); jLabel11.setBounds(30, 0, 120, 40); label_item3Inv.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel4.add(label_item3Inv); label_item3Inv.setBounds(30, 250, 80, 80); jLabel18.setText("Studenten:"); jPanel4.add(jLabel18); jLabel18.setBounds(10, 450, 80, 14); jLabel19.setText("4 / 40"); jPanel4.add(jLabel19); jLabel19.setBounds(80, 450, 50, 14); jLabel20.setText("Semester: "); jPanel4.add(jLabel20); jLabel20.setBounds(10, 470, 80, 14); jLabel21.setText("3 / 6"); jPanel4.add(jLabel21); jLabel21.setBounds(80, 470, 60, 14); label_ucoinsInv.setText("UCoins: 300"); jPanel4.add(label_ucoinsInv); label_ucoinsInv.setBounds(10, 380, 130, 14); label_item2Inv.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel4.add(label_item2Inv); label_item2Inv.setBounds(30, 150, 80, 80); label_creditsInv.setText("Credits: 700"); jPanel4.add(label_creditsInv); label_creditsInv.setBounds(10, 360, 140, 14); label_item3InvName.setText("Red Bull"); jPanel4.add(label_item3InvName); label_item3InvName.setBounds(30, 260, 80, 30); label_item3InvAmount.setText("3 x"); jPanel4.add(label_item3InvAmount); label_item3InvAmount.setBounds(30, 300, 80, 14); label_item1Inv.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel4.add(label_item1Inv); label_item1Inv.setBounds(30, 50, 80, 80); jLabel13.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel13.setText("Punkte:"); jPanel4.add(jLabel13); jLabel13.setBounds(10, 510, 70, 20); jLabel14.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel14.setText("700"); jPanel4.add(jLabel14); jLabel14.setBounds(90, 500, 40, 40); label_item1InvName.setText("Red Bull"); jPanel4.add(label_item1InvName); label_item1InvName.setBounds(30, 80, 80, 30); label_item2InvName.setText("Red Bull"); jPanel4.add(label_item2InvName); label_item2InvName.setBounds(30, 160, 80, 30); label_item2InvAmount.setText("3 x"); jPanel4.add(label_item2InvAmount); label_item2InvAmount.setBounds(30, 190, 80, 14); label_item1InvAmount.setText("3 x"); jPanel4.add(label_item1InvAmount); label_item1InvAmount.setBounds(30, 110, 80, 14); gamePlaying.add(jPanel4); jPanel4.setBounds(0, 110, 150, 550); jPanel5.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel5.setLayout(null); jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel5.setText("Wissen:"); jPanel5.add(jLabel5); jLabel5.setBounds(10, 10, 70, 20); jLabel6.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel6.setText("Motivation:"); jPanel5.add(jLabel6); jLabel6.setBounds(10, 30, 80, 40); jLabel7.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel7.setText("Müdigkeit:"); jPanel5.add(jLabel7); jLabel7.setBounds(10, 80, 80, 20); jPanel5.add(jProgressBar1); jProgressBar1.setBounds(80, 10, 260, 20); jPanel5.add(jProgressBar2); jProgressBar2.setBounds(80, 40, 260, 20); jPanel5.add(jProgressBar4); jProgressBar4.setBounds(80, 80, 260, 20); jButton1.setText("Fenster : AUF"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jPanel5.add(jButton1); jButton1.setBounds(350, 10, 120, 23); jButton4.setText("Gruppenarbeit"); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); jPanel5.add(jButton4); jButton4.setBounds(350, 40, 120, 23); jButton5.setText("Pause"); jPanel5.add(jButton5); jButton5.setBounds(350, 80, 120, 23); jLabel9.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel9.setText("Lärmpegel:"); jPanel5.add(jLabel9); jLabel9.setBounds(480, 10, 80, 20); jLabel10.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel10.setText("Luftqualität:"); jPanel5.add(jLabel10); jLabel10.setBounds(480, 34, 80, 30); jPanel5.add(jProgressBar5); jProgressBar5.setBounds(560, 10, 130, 20); jPanel5.add(jProgressBar6); jProgressBar6.setBounds(560, 40, 130, 20); gamePlaying.add(jPanel5); jPanel5.setBounds(150, 0, 700, 110); jPanel6.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel6.setLayout(null); label_timer.setFont(new java.awt.Font("Tahoma", 1, 48)); // NOI18N label_timer.setText("--:--"); jPanel6.add(label_timer); label_timer.setBounds(10, 10, 140, 90); gamePlaying.add(jPanel6); jPanel6.setBounds(850, 0, 130, 110); jPanel7.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); gamePlaying.add(jPanel7); jPanel7.setBounds(150, 110, 830, 550); jPanel2.add(gamePlaying, "card2"); jPanel1.add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1024, 768)); getContentPane().add(jPanel1); pack(); }// </editor-fold>//GEN-END:initComponents private void startNewGameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startNewGameActionPerformed // TODO add your handling code here: if(jPanel2.isVisible() == false){ jPanel2.setVisible(true); } cl.show(jPanel2, "card2"); startPlanningGame.setVisible(false); item.createItemInventory(label_item1Inv, label_item1InvName, label_item1InvAmount, game.redBull); item.createItemInventory(label_item2Inv, label_item2InvName, label_item2InvAmount, game.duplo); item.createItemInventory(label_item3Inv, label_item3InvName, label_item3InvAmount, game.omniSenseAudio); label_ucoinsInv.setText("UCoins: "+game.ucoins); label_creditsInv.setText("Credits: "+game.credits); ActivityPhase phase = new ActivityPhase(label_timer); // added by Jörg }//GEN-LAST:event_startNewGameActionPerformed private void exitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitActionPerformed // TODO add your handling code here: System.exit(0); }//GEN-LAST:event_exitActionPerformed private void loadGameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadGameActionPerformed // TODO add your handling code here: if(jPanel2.isVisible() == false){ jPanel2.setVisible(true); } cl.show(jPanel2, "card3"); startPlanningGame.setVisible(false); }//GEN-LAST:event_loadGameActionPerformed private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jButton6ActionPerformed private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jButton7ActionPerformed private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jButton8ActionPerformed private void button_swapperExchangeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button_swapperExchangeActionPerformed int parseResult = 0; int result = 1; try{ parseResult = Integer.parseInt(textfield_swapperUcoins.getText()); } catch(Exception e){ textfield_swapperUcoins.setText(""); } if(parseResult >= 0) result = exchange.ucoinsToCredits(parseResult, 1, textfield_swapperCredits); if(result == 0){ label_swapperCreditsAmount.setText(""+game.credits); label_swapperUcoinsAmount.setText(""+game.ucoins); OpenShop labels = new OpenShop(); labels.changeLabels(creditsShop, punkteShop, ucoinsShop); textfield_swapperUcoins.setText(""); textfield_swapperCredits.setText(""); } }//GEN-LAST:event_button_swapperExchangeActionPerformed private void button_swapperAbordActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button_swapperAbordActionPerformed // TODO add your handling code here: buyCoins.setVisible(false); }//GEN-LAST:event_button_swapperAbordActionPerformed private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jButton4ActionPerformed private void jLab_LogoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLab_LogoMouseClicked // TODO add your handling code here: jPanel2.setVisible(false); startPlanningGame.setVisible(true); }//GEN-LAST:event_jLab_LogoMouseClicked private void jLabel55MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel55MouseClicked // TODO add your handling code here: jPanel2.setVisible(false); startPlanningGame.setVisible(true); }//GEN-LAST:event_jLabel55MouseClicked private void jLabel54MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel54MouseClicked // TODO add your handling code here: cl.show(jPanel2, "card3"); startPlanningGame.setVisible(false); }//GEN-LAST:event_jLabel54MouseClicked private void jButton12ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton12ActionPerformed // TODO add your handling code here: label_swapperCreditsAmount.setText(""+game.credits); label_swapperUcoinsAmount.setText(""+game.ucoins); buyCoins.setVisible(true); }//GEN-LAST:event_jButton12ActionPerformed private void jLabel2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel2MouseClicked // TODO add your handling code here: jPanel2.setVisible(false); startPlanningGame.setVisible(true); }//GEN-LAST:event_jLabel2MouseClicked private void jButton13ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton13ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jButton13ActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed String test = jButton1.getText(); if(test.equals("Fenster : AUF")){ jButton1.setText("Fenster : ZU"); } if(test.equals("Fenster : ZU")){ jButton1.setText("Fenster : AUF"); } }//GEN-LAST:event_jButton1ActionPerformed private void jBut_BackGActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBut_BackGActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jBut_BackGActionPerformed private void jBut_BackG2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBut_BackG2ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jBut_BackG2ActionPerformed private void jBut_PlayActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBut_PlayActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jBut_PlayActionPerformed private void jBut_startShopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBut_startShopActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jBut_startShopActionPerformed private void jBut_17ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBut_17ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jBut_17ActionPerformed private void jBut_startShopMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jBut_startShopMouseClicked // TODO add your handling code here: cl.show(jPanel2, "card4"); startPlanningGame.setVisible(false); OpenShop labels = new OpenShop(); labels.changeLabels(creditsShop, punkteShop, ucoinsShop); item.createItemInventory(label_item1, label_item1Name, label_item1Amount, game.redBull); item.createItemInventory(label_item2, label_item2Name, label_item2Amount, game.duplo); item.createItemInventory(label_item3, label_item3Name, label_item3Amount, game.omniSenseAudio); item.createItemInventory(label_item4, label_item4Name, label_item4Amount, game.cheatSheet); item.createItemShop(label_redBullName, label_redBullAmount, label_redBullLocked, game.redBull); item.createItemShop(label_duploName, label_duploAmount, label_duploLocked, game.duplo); item.createItemShop(label_cheatSheetName, label_cheatSheetAmount, label_cheatSheetLocked, game.cheatSheet); item.createItemShop(label_omniName, label_omniAmount, label_omniLocked, game.omniSenseAudio); }//GEN-LAST:event_jBut_startShopMouseClicked private void label_redBullOverlayMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_label_redBullOverlayMouseClicked int result = item.managePurchase(game.redBull, label_redBullLocked); if(result != 0){ dialog_error.setVisible(true); dialog_error.setBounds(300, 200, 400, 320); } else{ item.updateInventroy(label_item1Amount, game.redBull, creditsShop, game.credits); } }//GEN-LAST:event_label_redBullOverlayMouseClicked private void label_duploOverlayMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_label_duploOverlayMouseClicked int result = item.managePurchase(game.duplo, label_duploLocked); if(result != 0){ dialog_error.setVisible(true); dialog_error.setBounds(300, 200, 400, 320); } else{ item.updateInventroy(label_item2Amount, game.duplo, creditsShop, game.credits); } }//GEN-LAST:event_label_duploOverlayMouseClicked private void label_cheatSheetOverlayMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_label_cheatSheetOverlayMouseClicked int result = item.managePurchase(game.cheatSheet, label_cheatSheetLocked); if(result != 0){ dialog_error.setVisible(true); dialog_error.setBounds(300, 200, 400, 320); } else{ item.updateInventroy(label_item4Amount, game.cheatSheet, ucoinsShop, game.ucoins); } }//GEN-LAST:event_label_cheatSheetOverlayMouseClicked private void label_omniOverlayMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_label_omniOverlayMouseClicked int result = item.managePurchase(game.omniSenseAudio, label_omniLocked); if(result != 0){ dialog_error.setVisible(true); dialog_error.setBounds(300, 200, 400, 320); } else{ item.updateInventroy(label_item3Amount, game.omniSenseAudio, ucoinsShop, game.ucoins); } }//GEN-LAST:event_label_omniOverlayMouseClicked private void button_shopMessageOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button_shopMessageOkActionPerformed dialog_error.setVisible(false); }//GEN-LAST:event_button_shopMessageOkActionPerformed private void jBut_1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBut_1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jBut_1ActionPerformed private void textfield_swapperUcoinsKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textfield_swapperUcoinsKeyReleased int parseResult = 0; try{ parseResult = Integer.parseInt(textfield_swapperUcoins.getText()); } catch(Exception e){ textfield_swapperUcoins.setText(""); } if(parseResult >= 0) exchange.ucoinsToCredits(parseResult, 0, textfield_swapperCredits); }//GEN-LAST:event_textfield_swapperUcoinsKeyReleased /** * @param args the command line arguments */ public static void main(String args[]) { /* * Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* * If Nimbus (introduced in Java SE 6) is not available, stay with the * default look and feel. For details see * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Sims.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Sims.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Sims.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Sims.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> CSVRead read = new CSVRead(); try { read.readCSV(); } catch (Exception ex) { Logger.getLogger(Sims_1.class.getName()).log(Level.SEVERE, null, ex); } /* * Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Sims_1().setVisible(true); } }); } //private javax.swing.JLabel label_timer; // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel Header; private javax.swing.JPanel Logo; private javax.swing.JLabel Menu_overlay; private javax.swing.JPanel Navi; private javax.swing.JPanel Shop; private javax.swing.JPanel StudField; private javax.swing.JButton button_shopMessageOk; private javax.swing.JButton button_swapperAbord; private javax.swing.JButton button_swapperExchange; private javax.swing.JDialog buyCoins; private javax.swing.JLabel creditsShop; private javax.swing.JDialog dialog_error; private javax.swing.JButton exit; private javax.swing.JPanel gamePlanning; private javax.swing.JPanel gamePlaying; private javax.swing.JButton jBut_1; private javax.swing.JButton jBut_10; private javax.swing.JButton jBut_11; private javax.swing.JButton jBut_12; private javax.swing.JButton jBut_13; private javax.swing.JButton jBut_14; private javax.swing.JButton jBut_15; private javax.swing.JButton jBut_16; private javax.swing.JButton jBut_17; private javax.swing.JButton jBut_18; private javax.swing.JButton jBut_19; private javax.swing.JButton jBut_2; private javax.swing.JButton jBut_20; private javax.swing.JButton jBut_21; private javax.swing.JButton jBut_22; private javax.swing.JButton jBut_23; private javax.swing.JButton jBut_24; private javax.swing.JButton jBut_25; private javax.swing.JButton jBut_26; private javax.swing.JButton jBut_27; private javax.swing.JButton jBut_28; private javax.swing.JButton jBut_29; private javax.swing.JButton jBut_3; private javax.swing.JButton jBut_30; private javax.swing.JButton jBut_4; private javax.swing.JButton jBut_5; private javax.swing.JButton jBut_6; private javax.swing.JButton jBut_7; private javax.swing.JButton jBut_8; private javax.swing.JButton jBut_9; private javax.swing.JButton jBut_BackG; private javax.swing.JButton jBut_BackG2; private javax.swing.JButton jBut_ComboB_useItem; private javax.swing.JButton jBut_Dozent; private javax.swing.JButton jBut_Play; private javax.swing.JButton jBut_startShop; private javax.swing.JButton jButton1; private javax.swing.JButton jButton12; private javax.swing.JButton jButton13; private javax.swing.JButton jButton4; private javax.swing.JButton jButton5; private javax.swing.JButton jButton6; private javax.swing.JButton jButton7; private javax.swing.JButton jButton8; private javax.swing.JComboBox jComboB_Items; private javax.swing.JLabel jLab_DozCounter; private javax.swing.JLabel jLab_DozSwitch; private javax.swing.JLabel jLab_Duplo; private javax.swing.JLabel jLab_Logo; private javax.swing.JLabel jLab_OMNI; private javax.swing.JLabel jLab_Redbull; private javax.swing.JLabel jLab_StudCounter; private javax.swing.JLabel jLab_StudSwitch; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel18; private javax.swing.JLabel jLabel19; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel20; private javax.swing.JLabel jLabel21; private javax.swing.JLabel jLabel27; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel41; private javax.swing.JLabel jLabel42; private javax.swing.JLabel jLabel43; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel54; private javax.swing.JLabel jLabel55; private javax.swing.JLabel jLabel58; private javax.swing.JLabel jLabel59; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel60; private javax.swing.JLabel jLabel61; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel70; private javax.swing.JLabel jLabel71; private javax.swing.JLabel jLabel72; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel85; private javax.swing.JLabel jLabel9; private javax.swing.JLabel jLabel90; private javax.swing.JLabel jLabel91; private javax.swing.JPanel jPan_DozSwitch; private javax.swing.JPanel jPan_ItemSelect; private javax.swing.JPanel jPan_ItemStorage; private javax.swing.JPanel jPan_StudSwitch; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel18; private javax.swing.JPanel jPanel19; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel20; private javax.swing.JPanel jPanel21; private javax.swing.JPanel jPanel22; private javax.swing.JPanel jPanel23; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel32; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JPanel jPanel7; private javax.swing.JProgressBar jProgB_Motivation; private javax.swing.JProgressBar jProgB_Müdigkeit; private javax.swing.JProgressBar jProgB_Wissen; private javax.swing.JProgressBar jProgressBar1; private javax.swing.JProgressBar jProgressBar2; private javax.swing.JProgressBar jProgressBar4; private javax.swing.JProgressBar jProgressBar5; private javax.swing.JProgressBar jProgressBar6; private javax.swing.JLabel label_cheatSheetAmount; private javax.swing.JLabel label_cheatSheetLocked; private javax.swing.JLabel label_cheatSheetName; private javax.swing.JLabel label_cheatSheetOverlay; private javax.swing.JLabel label_creditsInv; private javax.swing.JLabel label_currentExchange; private javax.swing.JLabel label_duploAmount; private javax.swing.JLabel label_duploLocked; private javax.swing.JLabel label_duploName; private javax.swing.JLabel label_duploOverlay; private javax.swing.JLabel label_inventar; private javax.swing.JLabel label_item1; private javax.swing.JLabel label_item1Amount; private javax.swing.JLabel label_item1Inv; private javax.swing.JLabel label_item1InvAmount; private javax.swing.JLabel label_item1InvName; private javax.swing.JLabel label_item1Name; private javax.swing.JLabel label_item2; private javax.swing.JLabel label_item2Amount; private javax.swing.JLabel label_item2Inv; private javax.swing.JLabel label_item2InvAmount; private javax.swing.JLabel label_item2InvName; private javax.swing.JLabel label_item2Name; private javax.swing.JLabel label_item3; private javax.swing.JLabel label_item3Amount; private javax.swing.JLabel label_item3Inv; private javax.swing.JLabel label_item3InvAmount; private javax.swing.JLabel label_item3InvName; private javax.swing.JLabel label_item3Name; private javax.swing.JLabel label_item4; private javax.swing.JLabel label_item4Amount; private javax.swing.JLabel label_item4Name; private javax.swing.JLabel label_omniAmount; private javax.swing.JLabel label_omniLocked; private javax.swing.JLabel label_omniName; private javax.swing.JLabel label_omniOverlay; private javax.swing.JLabel label_redBullAmount; private javax.swing.JLabel label_redBullLocked; private javax.swing.JLabel label_redBullName; private javax.swing.JLabel label_redBullOverlay; private javax.swing.JLabel label_shopMessage; private javax.swing.JLabel label_shopMessage1; private javax.swing.JLabel label_shopMessage2; private javax.swing.JLabel label_swapper; private javax.swing.JLabel label_swapperArrow1; private javax.swing.JLabel label_swapperArrow3; private javax.swing.JLabel label_swapperCredits; private javax.swing.JLabel label_swapperCreditsAmount; private javax.swing.JLabel label_swapperUcoins; private javax.swing.JLabel label_swapperUcoinsAmount; private javax.swing.JLabel label_timer; private javax.swing.JLabel label_ucoinsInv; private javax.swing.JButton loadGame; private javax.swing.JPanel panel_cheatSheet; private javax.swing.JPanel panel_duplo; private javax.swing.JPanel panel_redBull; private javax.swing.JLabel punkteShop; private javax.swing.JPanel shop; private javax.swing.JButton startNewGame; private javax.swing.JPanel startPlanningGame; private javax.swing.JTextField textfield_swapperCredits; private javax.swing.JTextField textfield_swapperUcoins; private javax.swing.JLabel ucoinsShop; // End of variables declaration//GEN-END:variables }
true
true
private void initComponents() { buyCoins = new javax.swing.JDialog(); label_swapper = new javax.swing.JLabel(); label_swapperUcoins = new javax.swing.JLabel(); label_swapperUcoinsAmount = new javax.swing.JLabel(); label_swapperCredits = new javax.swing.JLabel(); label_swapperCreditsAmount = new javax.swing.JLabel(); label_currentExchange = new javax.swing.JLabel(); textfield_swapperUcoins = new javax.swing.JTextField(); button_swapperExchange = new javax.swing.JButton(); button_swapperAbord = new javax.swing.JButton(); textfield_swapperCredits = new javax.swing.JTextField(); label_swapperArrow1 = new javax.swing.JLabel(); label_swapperArrow3 = new javax.swing.JLabel(); dialog_error = new javax.swing.JDialog(); label_shopMessage = new javax.swing.JLabel(); label_shopMessage1 = new javax.swing.JLabel(); label_shopMessage2 = new javax.swing.JLabel(); button_shopMessageOk = new javax.swing.JButton(); jPanel1 = new javax.swing.JPanel(); startPlanningGame = new javax.swing.JPanel(); Menu_overlay = new javax.swing.JLabel(); startNewGame = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); exit = new javax.swing.JButton(); loadGame = new javax.swing.JButton(); jButton6 = new javax.swing.JButton(); jButton7 = new javax.swing.JButton(); jButton8 = new javax.swing.JButton(); jButton13 = new javax.swing.JButton(); jPanel2 = new javax.swing.JPanel(); gamePlanning = new javax.swing.JPanel(); Logo = new javax.swing.JPanel(); jLab_Logo = new javax.swing.JLabel(); Header = new javax.swing.JPanel(); jLabel41 = new javax.swing.JLabel(); jLabel42 = new javax.swing.JLabel(); jLabel43 = new javax.swing.JLabel(); jProgB_Müdigkeit = new javax.swing.JProgressBar(); jProgB_Motivation = new javax.swing.JProgressBar(); jProgB_Wissen = new javax.swing.JProgressBar(); jLabel3 = new javax.swing.JLabel(); Shop = new javax.swing.JPanel(); jBut_startShop = new javax.swing.JButton(); Navi = new javax.swing.JPanel(); jPan_StudSwitch = new javax.swing.JPanel(); jLab_StudSwitch = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel90 = new javax.swing.JLabel(); jLab_StudCounter = new javax.swing.JLabel(); jBut_BackG = new javax.swing.JButton(); jPan_DozSwitch = new javax.swing.JPanel(); jLab_DozSwitch = new javax.swing.JLabel(); jLabel91 = new javax.swing.JLabel(); jLabel27 = new javax.swing.JLabel(); jLab_DozCounter = new javax.swing.JLabel(); jBut_BackG2 = new javax.swing.JButton(); jPan_ItemSelect = new javax.swing.JPanel(); jComboB_Items = new javax.swing.JComboBox(); jBut_ComboB_useItem = new javax.swing.JButton(); jPan_ItemStorage = new javax.swing.JPanel(); jLabel8 = new javax.swing.JLabel(); jLab_Redbull = new javax.swing.JLabel(); jLab_Duplo = new javax.swing.JLabel(); jLab_OMNI = new javax.swing.JLabel(); jPanel32 = new javax.swing.JPanel(); jBut_Play = new javax.swing.JButton(); StudField = new javax.swing.JPanel(); jBut_Dozent = new javax.swing.JButton(); jBut_1 = new javax.swing.JButton(); jBut_2 = new javax.swing.JButton(); jBut_3 = new javax.swing.JButton(); jBut_4 = new javax.swing.JButton(); jBut_5 = new javax.swing.JButton(); jBut_6 = new javax.swing.JButton(); jBut_7 = new javax.swing.JButton(); jBut_8 = new javax.swing.JButton(); jBut_9 = new javax.swing.JButton(); jBut_10 = new javax.swing.JButton(); jBut_11 = new javax.swing.JButton(); jBut_12 = new javax.swing.JButton(); jBut_13 = new javax.swing.JButton(); jBut_14 = new javax.swing.JButton(); jBut_15 = new javax.swing.JButton(); jBut_16 = new javax.swing.JButton(); jBut_17 = new javax.swing.JButton(); jBut_18 = new javax.swing.JButton(); jBut_19 = new javax.swing.JButton(); jBut_20 = new javax.swing.JButton(); jBut_21 = new javax.swing.JButton(); jBut_22 = new javax.swing.JButton(); jBut_23 = new javax.swing.JButton(); jBut_24 = new javax.swing.JButton(); jBut_25 = new javax.swing.JButton(); jBut_26 = new javax.swing.JButton(); jBut_27 = new javax.swing.JButton(); jBut_28 = new javax.swing.JButton(); jBut_29 = new javax.swing.JButton(); jBut_30 = new javax.swing.JButton(); shop = new javax.swing.JPanel(); jPanel18 = new javax.swing.JPanel(); jLabel55 = new javax.swing.JLabel(); jPanel19 = new javax.swing.JPanel(); label_inventar = new javax.swing.JLabel(); jLabel58 = new javax.swing.JLabel(); jLabel59 = new javax.swing.JLabel(); jLabel60 = new javax.swing.JLabel(); jLabel61 = new javax.swing.JLabel(); label_item4 = new javax.swing.JLabel(); label_item1 = new javax.swing.JLabel(); label_item2 = new javax.swing.JLabel(); label_item1Name = new javax.swing.JLabel(); label_item1Amount = new javax.swing.JLabel(); label_item2Name = new javax.swing.JLabel(); label_item2Amount = new javax.swing.JLabel(); label_item3Name = new javax.swing.JLabel(); label_item3Amount = new javax.swing.JLabel(); label_item3 = new javax.swing.JLabel(); label_item4Name = new javax.swing.JLabel(); label_item4Amount = new javax.swing.JLabel(); jPanel20 = new javax.swing.JPanel(); ucoinsShop = new javax.swing.JLabel(); creditsShop = new javax.swing.JLabel(); punkteShop = new javax.swing.JLabel(); jButton12 = new javax.swing.JButton(); jLabel70 = new javax.swing.JLabel(); jLabel71 = new javax.swing.JLabel(); jLabel72 = new javax.swing.JLabel(); jLabel85 = new javax.swing.JLabel(); jPanel21 = new javax.swing.JPanel(); jLabel54 = new javax.swing.JLabel(); jPanel22 = new javax.swing.JPanel(); label_redBullOverlay = new javax.swing.JLabel(); label_cheatSheetOverlay = new javax.swing.JLabel(); label_omniOverlay = new javax.swing.JLabel(); label_duploOverlay = new javax.swing.JLabel(); panel_redBull = new javax.swing.JPanel(); label_redBullName = new javax.swing.JLabel(); label_redBullAmount = new javax.swing.JLabel(); label_redBullLocked = new javax.swing.JLabel(); jPanel23 = new javax.swing.JPanel(); label_omniName = new javax.swing.JLabel(); label_omniLocked = new javax.swing.JLabel(); label_omniAmount = new javax.swing.JLabel(); panel_duplo = new javax.swing.JPanel(); label_duploName = new javax.swing.JLabel(); label_duploAmount = new javax.swing.JLabel(); label_duploLocked = new javax.swing.JLabel(); panel_cheatSheet = new javax.swing.JPanel(); label_cheatSheetName = new javax.swing.JLabel(); label_cheatSheetLocked = new javax.swing.JLabel(); label_cheatSheetAmount = new javax.swing.JLabel(); gamePlaying = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jPanel4 = new javax.swing.JPanel(); jLabel11 = new javax.swing.JLabel(); label_item3Inv = new javax.swing.JLabel(); jLabel18 = new javax.swing.JLabel(); jLabel19 = new javax.swing.JLabel(); jLabel20 = new javax.swing.JLabel(); jLabel21 = new javax.swing.JLabel(); label_ucoinsInv = new javax.swing.JLabel(); label_item2Inv = new javax.swing.JLabel(); label_creditsInv = new javax.swing.JLabel(); label_item3InvName = new javax.swing.JLabel(); label_item3InvAmount = new javax.swing.JLabel(); label_item1Inv = new javax.swing.JLabel(); jLabel13 = new javax.swing.JLabel(); jLabel14 = new javax.swing.JLabel(); label_item1InvName = new javax.swing.JLabel(); label_item2InvName = new javax.swing.JLabel(); label_item2InvAmount = new javax.swing.JLabel(); label_item1InvAmount = new javax.swing.JLabel(); jPanel5 = new javax.swing.JPanel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jProgressBar1 = new javax.swing.JProgressBar(); jProgressBar2 = new javax.swing.JProgressBar(); jProgressBar4 = new javax.swing.JProgressBar(); jButton1 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); jButton5 = new javax.swing.JButton(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); jProgressBar5 = new javax.swing.JProgressBar(); jProgressBar6 = new javax.swing.JProgressBar(); jPanel6 = new javax.swing.JPanel(); label_timer = new javax.swing.JLabel(); jPanel7 = new javax.swing.JPanel(); buyCoins.getContentPane().setLayout(null); label_swapper.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N label_swapper.setText("UCoins => Credits Tausch"); buyCoins.getContentPane().add(label_swapper); label_swapper.setBounds(30, 20, 370, 60); label_swapperUcoins.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N label_swapperUcoins.setText("UCoins:"); buyCoins.getContentPane().add(label_swapperUcoins); label_swapperUcoins.setBounds(50, 90, 80, 30); label_swapperUcoinsAmount.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N label_swapperUcoinsAmount.setText("5"); buyCoins.getContentPane().add(label_swapperUcoinsAmount); label_swapperUcoinsAmount.setBounds(120, 80, 80, 50); label_swapperCredits.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N label_swapperCredits.setText("Credits:"); buyCoins.getContentPane().add(label_swapperCredits); label_swapperCredits.setBounds(50, 160, 70, 30); label_swapperCreditsAmount.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N label_swapperCreditsAmount.setText("600"); buyCoins.getContentPane().add(label_swapperCreditsAmount); label_swapperCreditsAmount.setBounds(120, 150, 80, 50); label_currentExchange.setText("1 UCoin = 100 Credits"); buyCoins.getContentPane().add(label_currentExchange); label_currentExchange.setBounds(230, 120, 140, 40); textfield_swapperUcoins.setMinimumSize(new java.awt.Dimension(30, 20)); textfield_swapperUcoins.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { textfield_swapperUcoinsKeyReleased(evt); } }); buyCoins.getContentPane().add(textfield_swapperUcoins); textfield_swapperUcoins.setBounds(170, 90, 50, 30); button_swapperExchange.setText("Tauschen"); button_swapperExchange.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { button_swapperExchangeActionPerformed(evt); } }); buyCoins.getContentPane().add(button_swapperExchange); button_swapperExchange.setBounds(50, 220, 130, 23); button_swapperAbord.setText("Abbrechen"); button_swapperAbord.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { button_swapperAbordActionPerformed(evt); } }); buyCoins.getContentPane().add(button_swapperAbord); button_swapperAbord.setBounds(210, 220, 130, 23); textfield_swapperCredits.setEditable(false); textfield_swapperCredits.setMinimumSize(new java.awt.Dimension(30, 20)); buyCoins.getContentPane().add(textfield_swapperCredits); textfield_swapperCredits.setBounds(170, 160, 50, 30); label_swapperArrow1.setText("||"); buyCoins.getContentPane().add(label_swapperArrow1); label_swapperArrow1.setBounds(190, 130, 8, 14); label_swapperArrow3.setText("\\/"); buyCoins.getContentPane().add(label_swapperArrow3); label_swapperArrow3.setBounds(190, 140, 40, 14); dialog_error.getContentPane().setLayout(null); label_shopMessage.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); label_shopMessage.setText("Shop - Mitteilung"); dialog_error.getContentPane().add(label_shopMessage); label_shopMessage.setBounds(50, 10, 290, 70); label_shopMessage1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); label_shopMessage1.setText("Erwerbe neue Credits im Spiel oder tausche UCoins!"); dialog_error.getContentPane().add(label_shopMessage1); label_shopMessage1.setBounds(10, 110, 380, 70); label_shopMessage2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); label_shopMessage2.setText("Du hast leider nicht mehr genug Credits/UCoins um das Item zu kaufen"); dialog_error.getContentPane().add(label_shopMessage2); label_shopMessage2.setBounds(10, 80, 380, 70); button_shopMessageOk.setText("OK"); button_shopMessageOk.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { button_shopMessageOkActionPerformed(evt); } }); dialog_error.getContentPane().add(button_shopMessageOk); button_shopMessageOk.setBounds(170, 210, 47, 23); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setMaximumSize(new java.awt.Dimension(1000, 700)); setMinimumSize(new java.awt.Dimension(1000, 700)); setResizable(false); getContentPane().setLayout(new java.awt.GridLayout(1, 0)); jPanel1.setMaximumSize(new java.awt.Dimension(1000, 700)); jPanel1.setMinimumSize(new java.awt.Dimension(1000, 700)); jPanel1.setPreferredSize(new java.awt.Dimension(1000, 700)); jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); startPlanningGame.setMaximumSize(new java.awt.Dimension(1000, 700)); startPlanningGame.setMinimumSize(new java.awt.Dimension(1000, 700)); startPlanningGame.setName(""); // NOI18N startPlanningGame.setPreferredSize(new java.awt.Dimension(1000, 700)); startPlanningGame.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); Menu_overlay.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pictures/hauptmenü1000x700_00000.png"))); // NOI18N Menu_overlay.setText("Overlay_hauptmenü"); startPlanningGame.add(Menu_overlay, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1)); startNewGame.setText("Neues Spiel"); startNewGame.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { startNewGameActionPerformed(evt); } }); startPlanningGame.add(startNewGame, new org.netbeans.lib.awtextra.AbsoluteConstraints(640, 200, 160, 40)); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N jLabel1.setText("SIMS Test Menü"); jLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); startPlanningGame.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(340, 100, 330, 80)); exit.setText("Beenden"); exit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exitActionPerformed(evt); } }); startPlanningGame.add(exit, new org.netbeans.lib.awtextra.AbsoluteConstraints(640, 440, 160, 40)); loadGame.setText("Spiel Laden"); loadGame.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { loadGameActionPerformed(evt); } }); startPlanningGame.add(loadGame, new org.netbeans.lib.awtextra.AbsoluteConstraints(620, 240, 210, 40)); jButton6.setText("Credits"); jButton6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton6ActionPerformed(evt); } }); startPlanningGame.add(jButton6, new org.netbeans.lib.awtextra.AbsoluteConstraints(640, 360, 160, 40)); jButton7.setText("Profil"); jButton7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton7ActionPerformed(evt); } }); startPlanningGame.add(jButton7, new org.netbeans.lib.awtextra.AbsoluteConstraints(650, 280, 160, 40)); jButton8.setText("Abmelden"); jButton8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton8ActionPerformed(evt); } }); startPlanningGame.add(jButton8, new org.netbeans.lib.awtextra.AbsoluteConstraints(640, 400, 160, 40)); jButton13.setText("Statistik"); jButton13.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton13ActionPerformed(evt); } }); startPlanningGame.add(jButton13, new org.netbeans.lib.awtextra.AbsoluteConstraints(650, 320, 160, 40)); jPanel1.add(startPlanningGame, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1000, 700)); jPanel2.setLayout(new java.awt.CardLayout()); gamePlanning.setName("card3"); // NOI18N gamePlanning.setLayout(null); Logo.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); Logo.setLayout(null); jLab_Logo.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLab_Logo.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLab_Logo.setText("SIMS Logo"); jLab_Logo.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLab_LogoMouseClicked(evt); } }); Logo.add(jLab_Logo); jLab_Logo.setBounds(0, 0, 150, 110); gamePlanning.add(Logo); Logo.setBounds(0, 0, 150, 110); Header.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); Header.setLayout(null); jLabel41.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel41.setText("Wissen:"); Header.add(jLabel41); jLabel41.setBounds(10, 20, 70, 20); jLabel42.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel42.setText("Motivation:"); Header.add(jLabel42); jLabel42.setBounds(10, 40, 80, 30); jLabel43.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel43.setText("Müdigkeit:"); Header.add(jLabel43); jLabel43.setBounds(10, 80, 90, 20); Header.add(jProgB_Müdigkeit); jProgB_Müdigkeit.setBounds(90, 80, 260, 20); Header.add(jProgB_Motivation); jProgB_Motivation.setBounds(90, 50, 260, 20); Header.add(jProgB_Wissen); jProgB_Wissen.setBounds(90, 20, 260, 20); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N jLabel3.setText("PLANUNGSPHASE"); Header.add(jLabel3); jLabel3.setBounds(360, 10, 340, 90); gamePlanning.add(Header); Header.setBounds(150, 0, 700, 110); Shop.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); Shop.setLayout(null); jBut_startShop.setFont(new java.awt.Font("Lucida Grande", 1, 24)); // NOI18N jBut_startShop.setText("SHOP"); jBut_startShop.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jBut_startShopMouseClicked(evt); } }); jBut_startShop.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBut_startShopActionPerformed(evt); } }); Shop.add(jBut_startShop); jBut_startShop.setBounds(5, 5, 120, 100); gamePlanning.add(Shop); Shop.setBounds(850, 0, 130, 110); Navi.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); Navi.setLayout(null); jPan_StudSwitch.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPan_StudSwitch.setLayout(null); jPan_StudSwitch.add(jLab_StudSwitch); jLab_StudSwitch.setBounds(0, 0, 150, 110); jLabel4.setText("umsetzen"); jPan_StudSwitch.add(jLabel4); jLabel4.setBounds(40, 40, 70, 14); jLabel90.setText("Studenten"); jPan_StudSwitch.add(jLabel90); jLabel90.setBounds(40, 20, 70, 20); jLab_StudCounter.setFont(new java.awt.Font("Lucida Grande", 1, 18)); // NOI18N jLab_StudCounter.setText("5x"); jPan_StudSwitch.add(jLab_StudCounter); jLab_StudCounter.setBounds(60, 60, 30, 24); jBut_BackG.setFont(new java.awt.Font("Lucida Grande", 1, 18)); // NOI18N jBut_BackG.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBut_BackGActionPerformed(evt); } }); jPan_StudSwitch.add(jBut_BackG); jBut_BackG.setBounds(10, 10, 130, 90); Navi.add(jPan_StudSwitch); jPan_StudSwitch.setBounds(0, 0, 150, 110); jPan_StudSwitch.getAccessibleContext().setAccessibleDescription(""); jPan_DozSwitch.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPan_DozSwitch.setLayout(null); jPan_DozSwitch.add(jLab_DozSwitch); jLab_DozSwitch.setBounds(0, 0, 150, 110); jLabel91.setText("Dozenten"); jPan_DozSwitch.add(jLabel91); jLabel91.setBounds(40, 20, 70, 20); jLabel27.setText("tauschen"); jPan_DozSwitch.add(jLabel27); jLabel27.setBounds(40, 40, 60, 20); jLab_DozCounter.setFont(new java.awt.Font("Lucida Grande", 1, 18)); // NOI18N jLab_DozCounter.setText("1x"); jPan_DozSwitch.add(jLab_DozCounter); jLab_DozCounter.setBounds(60, 60, 30, 30); jBut_BackG2.setFont(new java.awt.Font("Lucida Grande", 1, 18)); // NOI18N jBut_BackG2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBut_BackG2ActionPerformed(evt); } }); jPan_DozSwitch.add(jBut_BackG2); jBut_BackG2.setBounds(10, 10, 130, 90); Navi.add(jPan_DozSwitch); jPan_DozSwitch.setBounds(0, 110, 150, 110); jPan_ItemSelect.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPan_ItemSelect.setLayout(null); jComboB_Items.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "wähle Item", "Spicker" })); jPan_ItemSelect.add(jComboB_Items); jComboB_Items.setBounds(10, 20, 130, 30); jBut_ComboB_useItem.setText("Benutzen"); jPan_ItemSelect.add(jBut_ComboB_useItem); jBut_ComboB_useItem.setBounds(10, 60, 120, 23); Navi.add(jPan_ItemSelect); jPan_ItemSelect.setBounds(0, 220, 150, 110); jPan_ItemStorage.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPan_ItemStorage.setLayout(null); jLabel8.setFont(new java.awt.Font("Lucida Grande", 1, 14)); // NOI18N jLabel8.setText("Item-Vorräte"); jPan_ItemStorage.add(jLabel8); jLabel8.setBounds(10, 10, 120, 20); jLab_Redbull.setText("Redbull: 5"); jPan_ItemStorage.add(jLab_Redbull); jLab_Redbull.setBounds(10, 40, 90, 14); jLab_Duplo.setText("Duplo: 3"); jPan_ItemStorage.add(jLab_Duplo); jLab_Duplo.setBounds(10, 60, 90, 14); jLab_OMNI.setText("OMNI Sense Buch: 1"); jPan_ItemStorage.add(jLab_OMNI); jLab_OMNI.setBounds(10, 80, 140, 14); Navi.add(jPan_ItemStorage); jPan_ItemStorage.setBounds(0, 330, 150, 110); jPanel32.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel32.setLayout(null); jBut_Play.setFont(new java.awt.Font("Lucida Grande", 1, 18)); // NOI18N jBut_Play.setText("SPIELEN"); jBut_Play.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBut_PlayActionPerformed(evt); } }); jPanel32.add(jBut_Play); jBut_Play.setBounds(10, 10, 130, 90); Navi.add(jPanel32); jPanel32.setBounds(0, 440, 150, 110); gamePlanning.add(Navi); Navi.setBounds(0, 110, 150, 550); StudField.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); StudField.setLayout(null); jBut_Dozent.setText("Dozent"); StudField.add(jBut_Dozent); jBut_Dozent.setBounds(340, 470, 110, 50); jBut_1.setText("Platz_1"); jBut_1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBut_1ActionPerformed(evt); } }); StudField.add(jBut_1); jBut_1.setBounds(60, 10, 110, 50); jBut_2.setText("Platz_2"); StudField.add(jBut_2); jBut_2.setBounds(210, 10, 110, 50); jBut_3.setText("Platz_3"); StudField.add(jBut_3); jBut_3.setBounds(360, 10, 110, 50); jBut_4.setText("Platz_4"); StudField.add(jBut_4); jBut_4.setBounds(510, 10, 110, 50); jBut_5.setText("Platz_5"); StudField.add(jBut_5); jBut_5.setBounds(660, 10, 110, 50); jBut_6.setText("Platz_6"); StudField.add(jBut_6); jBut_6.setBounds(60, 80, 110, 50); jBut_7.setText("Platz_7"); StudField.add(jBut_7); jBut_7.setBounds(210, 80, 110, 50); jBut_8.setText("Platz_8"); StudField.add(jBut_8); jBut_8.setBounds(360, 80, 110, 50); jBut_9.setText("Platz_9"); StudField.add(jBut_9); jBut_9.setBounds(510, 80, 110, 50); jBut_10.setText("Platz_10"); StudField.add(jBut_10); jBut_10.setBounds(660, 80, 110, 50); jBut_11.setText("Platz_11"); StudField.add(jBut_11); jBut_11.setBounds(60, 150, 110, 50); jBut_12.setText("Platz_12"); StudField.add(jBut_12); jBut_12.setBounds(210, 150, 110, 50); jBut_13.setText("Platz_13"); StudField.add(jBut_13); jBut_13.setBounds(360, 150, 110, 50); jBut_14.setText("Platz_14"); StudField.add(jBut_14); jBut_14.setBounds(510, 150, 110, 50); jBut_15.setText("Platz_15"); StudField.add(jBut_15); jBut_15.setBounds(660, 150, 110, 50); jBut_16.setText("Platz_16"); StudField.add(jBut_16); jBut_16.setBounds(60, 220, 110, 50); jBut_17.setText("Platz_17"); jBut_17.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBut_17ActionPerformed(evt); } }); StudField.add(jBut_17); jBut_17.setBounds(210, 220, 110, 50); jBut_18.setText("Platz_18"); StudField.add(jBut_18); jBut_18.setBounds(360, 220, 110, 50); jBut_19.setText("Platz_19"); StudField.add(jBut_19); jBut_19.setBounds(510, 220, 110, 50); jBut_20.setText("Platz_20"); StudField.add(jBut_20); jBut_20.setBounds(660, 220, 110, 50); jBut_21.setText("Platz_21"); StudField.add(jBut_21); jBut_21.setBounds(60, 290, 110, 50); jBut_22.setText("Platz_22"); StudField.add(jBut_22); jBut_22.setBounds(210, 290, 110, 50); jBut_23.setText("Platz_23"); StudField.add(jBut_23); jBut_23.setBounds(360, 290, 110, 50); jBut_24.setText("Platz_24"); StudField.add(jBut_24); jBut_24.setBounds(510, 290, 110, 50); jBut_25.setText("Platz_25"); StudField.add(jBut_25); jBut_25.setBounds(660, 290, 110, 50); jBut_26.setText("Platz_26"); StudField.add(jBut_26); jBut_26.setBounds(60, 360, 110, 50); jBut_27.setText("Platz_27"); jBut_27.setToolTipText(""); StudField.add(jBut_27); jBut_27.setBounds(210, 360, 110, 50); jBut_28.setText("Platz_28"); StudField.add(jBut_28); jBut_28.setBounds(360, 360, 110, 50); jBut_29.setText("Platz_29"); StudField.add(jBut_29); jBut_29.setBounds(510, 360, 110, 50); jBut_30.setText("Platz_30"); StudField.add(jBut_30); jBut_30.setBounds(660, 360, 110, 50); gamePlanning.add(StudField); StudField.setBounds(150, 110, 830, 550); jPanel2.add(gamePlanning, "card3"); shop.setLayout(null); jPanel18.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel18.setLayout(null); jLabel55.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel55.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel55.setText("SIMS Logo"); jLabel55.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel55MouseClicked(evt); } }); jPanel18.add(jLabel55); jLabel55.setBounds(0, 0, 150, 110); shop.add(jPanel18); jPanel18.setBounds(0, 0, 150, 110); jPanel19.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel19.setLayout(null); label_inventar.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N label_inventar.setText("Inventar"); jPanel19.add(label_inventar); label_inventar.setBounds(30, 0, 120, 40); jLabel58.setText("Studenten:"); jPanel19.add(jLabel58); jLabel58.setBounds(10, 450, 80, 14); jLabel59.setText("4 / 40"); jPanel19.add(jLabel59); jLabel59.setBounds(80, 450, 50, 14); jLabel60.setText("Semester: "); jPanel19.add(jLabel60); jLabel60.setBounds(10, 470, 80, 14); jLabel61.setText("3 / 6"); jPanel19.add(jLabel61); jLabel61.setBounds(80, 470, 60, 14); label_item4.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel19.add(label_item4); label_item4.setBounds(30, 350, 90, 80); label_item1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel19.add(label_item1); label_item1.setBounds(30, 50, 90, 80); label_item2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); label_item2.setPreferredSize(new java.awt.Dimension(20, 20)); jPanel19.add(label_item2); label_item2.setBounds(30, 150, 90, 80); label_item1Name.setText("jLabel4"); jPanel19.add(label_item1Name); label_item1Name.setBounds(60, 80, 34, 14); label_item1Amount.setText("jLabel4"); jPanel19.add(label_item1Amount); label_item1Amount.setBounds(60, 100, 34, 14); label_item2Name.setText("jLabel4"); jPanel19.add(label_item2Name); label_item2Name.setBounds(60, 190, 34, 14); label_item2Amount.setText("jLabel4"); jPanel19.add(label_item2Amount); label_item2Amount.setBounds(60, 210, 34, 14); label_item3Name.setText("jLabel4"); jPanel19.add(label_item3Name); label_item3Name.setBounds(60, 380, 34, 14); label_item3Amount.setText("jLabel26"); jPanel19.add(label_item3Amount); label_item3Amount.setBounds(60, 400, 40, 14); label_item3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel19.add(label_item3); label_item3.setBounds(30, 250, 90, 80); label_item4Name.setText("jLabel4"); jPanel19.add(label_item4Name); label_item4Name.setBounds(60, 280, 34, 14); label_item4Amount.setText("jLabel26"); jPanel19.add(label_item4Amount); label_item4Amount.setBounds(60, 300, 40, 14); shop.add(jPanel19); jPanel19.setBounds(0, 110, 150, 550); jPanel20.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel20.setLayout(null); ucoinsShop.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N ucoinsShop.setText("0"); jPanel20.add(ucoinsShop); ucoinsShop.setBounds(80, 10, 80, 20); creditsShop.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N creditsShop.setText("0"); jPanel20.add(creditsShop); creditsShop.setBounds(80, 40, 70, 17); punkteShop.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N punkteShop.setText("0"); jPanel20.add(punkteShop); punkteShop.setBounds(80, 70, 70, 17); jButton12.setText("UCoins Tauschen"); jButton12.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton12ActionPerformed(evt); } }); jPanel20.add(jButton12); jButton12.setBounds(230, 10, 160, 90); jLabel70.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel70.setText("UCoins:"); jPanel20.add(jLabel70); jLabel70.setBounds(10, 10, 80, 20); jLabel71.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel71.setText("Credits:"); jPanel20.add(jLabel71); jLabel71.setBounds(10, 40, 70, 17); jLabel72.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel72.setText("Punkte:"); jPanel20.add(jLabel72); jLabel72.setBounds(10, 70, 70, 17); jLabel85.setFont(new java.awt.Font("Tahoma", 1, 48)); // NOI18N jLabel85.setText("SHOP"); jPanel20.add(jLabel85); jLabel85.setBounds(470, 0, 210, 110); shop.add(jPanel20); jPanel20.setBounds(150, 0, 700, 110); jPanel21.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel21.setLayout(null); jLabel54.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel54.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel54.setText("SPIEL"); jLabel54.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel54MouseClicked(evt); } }); jPanel21.add(jLabel54); jLabel54.setBounds(0, 0, 130, 110); shop.add(jPanel21); jPanel21.setBounds(850, 0, 130, 110); jPanel22.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel22.setLayout(null); label_redBullOverlay.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); label_redBullOverlay.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { label_redBullOverlayMouseClicked(evt); } }); jPanel22.add(label_redBullOverlay); label_redBullOverlay.setBounds(100, 40, 230, 220); label_cheatSheetOverlay.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); label_cheatSheetOverlay.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { label_cheatSheetOverlayMouseClicked(evt); } }); jPanel22.add(label_cheatSheetOverlay); label_cheatSheetOverlay.setBounds(100, 300, 230, 220); label_omniOverlay.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); label_omniOverlay.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { label_omniOverlayMouseClicked(evt); } }); jPanel22.add(label_omniOverlay); label_omniOverlay.setBounds(510, 300, 230, 220); label_duploOverlay.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); label_duploOverlay.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { label_duploOverlayMouseClicked(evt); } }); jPanel22.add(label_duploOverlay); label_duploOverlay.setBounds(510, 40, 230, 220); panel_redBull.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); panel_redBull.setName("panel_redBull"); // NOI18N panel_redBull.setLayout(null); label_redBullName.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N label_redBullName.setText("Red Bull"); panel_redBull.add(label_redBullName); label_redBullName.setBounds(0, 130, 230, 30); label_redBullAmount.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N label_redBullAmount.setText("100 Credits"); panel_redBull.add(label_redBullAmount); label_redBullAmount.setBounds(0, 150, 230, 50); label_redBullLocked.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N label_redBullLocked.setForeground(new java.awt.Color(204, 51, 0)); label_redBullLocked.setText("GESPERRT"); panel_redBull.add(label_redBullLocked); label_redBullLocked.setBounds(50, 10, 230, 110); jPanel22.add(panel_redBull); panel_redBull.setBounds(100, 40, 230, 220); jPanel23.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel23.setLayout(null); label_omniName.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N label_omniName.setText("Verfügbar ab Semester 4"); jPanel23.add(label_omniName); label_omniName.setBounds(0, 120, 230, 50); label_omniLocked.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N label_omniLocked.setForeground(new java.awt.Color(204, 51, 0)); label_omniLocked.setText("GESPERRT"); jPanel23.add(label_omniLocked); label_omniLocked.setBounds(50, 20, 230, 110); label_omniAmount.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N label_omniAmount.setText("5 UCoins"); jPanel23.add(label_omniAmount); label_omniAmount.setBounds(0, 150, 230, 50); jPanel22.add(jPanel23); jPanel23.setBounds(510, 300, 230, 220); panel_duplo.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); panel_duplo.setLayout(null); label_duploName.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N label_duploName.setText("Duplo"); panel_duplo.add(label_duploName); label_duploName.setBounds(0, 130, 230, 30); label_duploAmount.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N label_duploAmount.setText("100 Credits"); panel_duplo.add(label_duploAmount); label_duploAmount.setBounds(0, 150, 230, 50); label_duploLocked.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N label_duploLocked.setForeground(new java.awt.Color(204, 51, 0)); label_duploLocked.setText("GESPERRT"); panel_duplo.add(label_duploLocked); label_duploLocked.setBounds(50, 10, 230, 110); jPanel22.add(panel_duplo); panel_duplo.setBounds(510, 40, 230, 220); panel_cheatSheet.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); panel_cheatSheet.setLayout(null); label_cheatSheetName.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N label_cheatSheetName.setText("Spicker"); panel_cheatSheet.add(label_cheatSheetName); label_cheatSheetName.setBounds(0, 130, 230, 30); label_cheatSheetLocked.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N label_cheatSheetLocked.setForeground(new java.awt.Color(204, 51, 0)); label_cheatSheetLocked.setText("GESPERRT"); panel_cheatSheet.add(label_cheatSheetLocked); label_cheatSheetLocked.setBounds(50, 10, 230, 110); label_cheatSheetAmount.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N label_cheatSheetAmount.setText("5 UCoins"); panel_cheatSheet.add(label_cheatSheetAmount); label_cheatSheetAmount.setBounds(0, 150, 230, 50); jPanel22.add(panel_cheatSheet); panel_cheatSheet.setBounds(100, 300, 230, 220); shop.add(jPanel22); jPanel22.setBounds(150, 110, 830, 550); jPanel2.add(shop, "card4"); gamePlaying.setMinimumSize(new java.awt.Dimension(1024, 768)); gamePlaying.setPreferredSize(new java.awt.Dimension(1024, 768)); gamePlaying.setLayout(null); jPanel3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel3.setLayout(null); jLabel2.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel2.setText("SIMS Logo"); jLabel2.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel2MouseClicked(evt); } }); jPanel3.add(jLabel2); jLabel2.setBounds(0, 0, 150, 110); gamePlaying.add(jPanel3); jPanel3.setBounds(0, 0, 150, 110); jPanel4.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel4.setLayout(null); jLabel11.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel11.setText("Inventar"); jPanel4.add(jLabel11); jLabel11.setBounds(30, 0, 120, 40); label_item3Inv.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel4.add(label_item3Inv); label_item3Inv.setBounds(30, 250, 80, 80); jLabel18.setText("Studenten:"); jPanel4.add(jLabel18); jLabel18.setBounds(10, 450, 80, 14); jLabel19.setText("4 / 40"); jPanel4.add(jLabel19); jLabel19.setBounds(80, 450, 50, 14); jLabel20.setText("Semester: "); jPanel4.add(jLabel20); jLabel20.setBounds(10, 470, 80, 14); jLabel21.setText("3 / 6"); jPanel4.add(jLabel21); jLabel21.setBounds(80, 470, 60, 14); label_ucoinsInv.setText("UCoins: 300"); jPanel4.add(label_ucoinsInv); label_ucoinsInv.setBounds(10, 380, 130, 14); label_item2Inv.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel4.add(label_item2Inv); label_item2Inv.setBounds(30, 150, 80, 80); label_creditsInv.setText("Credits: 700"); jPanel4.add(label_creditsInv); label_creditsInv.setBounds(10, 360, 140, 14); label_item3InvName.setText("Red Bull"); jPanel4.add(label_item3InvName); label_item3InvName.setBounds(30, 260, 80, 30); label_item3InvAmount.setText("3 x"); jPanel4.add(label_item3InvAmount); label_item3InvAmount.setBounds(30, 300, 80, 14); label_item1Inv.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel4.add(label_item1Inv); label_item1Inv.setBounds(30, 50, 80, 80); jLabel13.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel13.setText("Punkte:"); jPanel4.add(jLabel13); jLabel13.setBounds(10, 510, 70, 20); jLabel14.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel14.setText("700"); jPanel4.add(jLabel14); jLabel14.setBounds(90, 500, 40, 40); label_item1InvName.setText("Red Bull"); jPanel4.add(label_item1InvName); label_item1InvName.setBounds(30, 80, 80, 30); label_item2InvName.setText("Red Bull"); jPanel4.add(label_item2InvName); label_item2InvName.setBounds(30, 160, 80, 30); label_item2InvAmount.setText("3 x"); jPanel4.add(label_item2InvAmount); label_item2InvAmount.setBounds(30, 190, 80, 14); label_item1InvAmount.setText("3 x"); jPanel4.add(label_item1InvAmount); label_item1InvAmount.setBounds(30, 110, 80, 14); gamePlaying.add(jPanel4); jPanel4.setBounds(0, 110, 150, 550); jPanel5.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel5.setLayout(null); jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel5.setText("Wissen:"); jPanel5.add(jLabel5); jLabel5.setBounds(10, 10, 70, 20); jLabel6.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel6.setText("Motivation:"); jPanel5.add(jLabel6); jLabel6.setBounds(10, 30, 80, 40); jLabel7.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel7.setText("Müdigkeit:"); jPanel5.add(jLabel7); jLabel7.setBounds(10, 80, 80, 20); jPanel5.add(jProgressBar1); jProgressBar1.setBounds(80, 10, 260, 20); jPanel5.add(jProgressBar2); jProgressBar2.setBounds(80, 40, 260, 20); jPanel5.add(jProgressBar4); jProgressBar4.setBounds(80, 80, 260, 20); jButton1.setText("Fenster : AUF"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jPanel5.add(jButton1); jButton1.setBounds(350, 10, 120, 23); jButton4.setText("Gruppenarbeit"); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); jPanel5.add(jButton4); jButton4.setBounds(350, 40, 120, 23); jButton5.setText("Pause"); jPanel5.add(jButton5); jButton5.setBounds(350, 80, 120, 23); jLabel9.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel9.setText("Lärmpegel:"); jPanel5.add(jLabel9); jLabel9.setBounds(480, 10, 80, 20); jLabel10.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel10.setText("Luftqualität:"); jPanel5.add(jLabel10); jLabel10.setBounds(480, 34, 80, 30); jPanel5.add(jProgressBar5); jProgressBar5.setBounds(560, 10, 130, 20); jPanel5.add(jProgressBar6); jProgressBar6.setBounds(560, 40, 130, 20); gamePlaying.add(jPanel5); jPanel5.setBounds(150, 0, 700, 110); jPanel6.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel6.setLayout(null); label_timer.setFont(new java.awt.Font("Tahoma", 1, 48)); // NOI18N label_timer.setText("--:--"); jPanel6.add(label_timer); label_timer.setBounds(10, 10, 140, 90); gamePlaying.add(jPanel6); jPanel6.setBounds(850, 0, 130, 110); jPanel7.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); gamePlaying.add(jPanel7); jPanel7.setBounds(150, 110, 830, 550); jPanel2.add(gamePlaying, "card2"); jPanel1.add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1024, 768)); getContentPane().add(jPanel1); pack(); }// </editor-fold>//GEN-END:initComponents
private void initComponents() { buyCoins = new javax.swing.JDialog(); label_swapper = new javax.swing.JLabel(); label_swapperUcoins = new javax.swing.JLabel(); label_swapperUcoinsAmount = new javax.swing.JLabel(); label_swapperCredits = new javax.swing.JLabel(); label_swapperCreditsAmount = new javax.swing.JLabel(); label_currentExchange = new javax.swing.JLabel(); textfield_swapperUcoins = new javax.swing.JTextField(); button_swapperExchange = new javax.swing.JButton(); button_swapperAbord = new javax.swing.JButton(); textfield_swapperCredits = new javax.swing.JTextField(); label_swapperArrow1 = new javax.swing.JLabel(); label_swapperArrow3 = new javax.swing.JLabel(); dialog_error = new javax.swing.JDialog(); label_shopMessage = new javax.swing.JLabel(); label_shopMessage1 = new javax.swing.JLabel(); label_shopMessage2 = new javax.swing.JLabel(); button_shopMessageOk = new javax.swing.JButton(); jPanel1 = new javax.swing.JPanel(); startPlanningGame = new javax.swing.JPanel(); Menu_overlay = new javax.swing.JLabel(); startNewGame = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); exit = new javax.swing.JButton(); loadGame = new javax.swing.JButton(); jButton6 = new javax.swing.JButton(); jButton7 = new javax.swing.JButton(); jButton8 = new javax.swing.JButton(); jButton13 = new javax.swing.JButton(); jPanel2 = new javax.swing.JPanel(); gamePlanning = new javax.swing.JPanel(); Logo = new javax.swing.JPanel(); jLab_Logo = new javax.swing.JLabel(); Header = new javax.swing.JPanel(); jLabel41 = new javax.swing.JLabel(); jLabel42 = new javax.swing.JLabel(); jLabel43 = new javax.swing.JLabel(); jProgB_Müdigkeit = new javax.swing.JProgressBar(); jProgB_Motivation = new javax.swing.JProgressBar(); jProgB_Wissen = new javax.swing.JProgressBar(); jLabel3 = new javax.swing.JLabel(); Shop = new javax.swing.JPanel(); jBut_startShop = new javax.swing.JButton(); Navi = new javax.swing.JPanel(); jPan_StudSwitch = new javax.swing.JPanel(); jLab_StudSwitch = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel90 = new javax.swing.JLabel(); jLab_StudCounter = new javax.swing.JLabel(); jBut_BackG = new javax.swing.JButton(); jPan_DozSwitch = new javax.swing.JPanel(); jLab_DozSwitch = new javax.swing.JLabel(); jLabel91 = new javax.swing.JLabel(); jLabel27 = new javax.swing.JLabel(); jLab_DozCounter = new javax.swing.JLabel(); jBut_BackG2 = new javax.swing.JButton(); jPan_ItemSelect = new javax.swing.JPanel(); jComboB_Items = new javax.swing.JComboBox(); jBut_ComboB_useItem = new javax.swing.JButton(); jPan_ItemStorage = new javax.swing.JPanel(); jLabel8 = new javax.swing.JLabel(); jLab_Redbull = new javax.swing.JLabel(); jLab_Duplo = new javax.swing.JLabel(); jLab_OMNI = new javax.swing.JLabel(); jPanel32 = new javax.swing.JPanel(); jBut_Play = new javax.swing.JButton(); StudField = new javax.swing.JPanel(); jBut_Dozent = new javax.swing.JButton(); jBut_1 = new javax.swing.JButton(); jBut_2 = new javax.swing.JButton(); jBut_3 = new javax.swing.JButton(); jBut_4 = new javax.swing.JButton(); jBut_5 = new javax.swing.JButton(); jBut_6 = new javax.swing.JButton(); jBut_7 = new javax.swing.JButton(); jBut_8 = new javax.swing.JButton(); jBut_9 = new javax.swing.JButton(); jBut_10 = new javax.swing.JButton(); jBut_11 = new javax.swing.JButton(); jBut_12 = new javax.swing.JButton(); jBut_13 = new javax.swing.JButton(); jBut_14 = new javax.swing.JButton(); jBut_15 = new javax.swing.JButton(); jBut_16 = new javax.swing.JButton(); jBut_17 = new javax.swing.JButton(); jBut_18 = new javax.swing.JButton(); jBut_19 = new javax.swing.JButton(); jBut_20 = new javax.swing.JButton(); jBut_21 = new javax.swing.JButton(); jBut_22 = new javax.swing.JButton(); jBut_23 = new javax.swing.JButton(); jBut_24 = new javax.swing.JButton(); jBut_25 = new javax.swing.JButton(); jBut_26 = new javax.swing.JButton(); jBut_27 = new javax.swing.JButton(); jBut_28 = new javax.swing.JButton(); jBut_29 = new javax.swing.JButton(); jBut_30 = new javax.swing.JButton(); shop = new javax.swing.JPanel(); jPanel18 = new javax.swing.JPanel(); jLabel55 = new javax.swing.JLabel(); jPanel19 = new javax.swing.JPanel(); label_inventar = new javax.swing.JLabel(); jLabel58 = new javax.swing.JLabel(); jLabel59 = new javax.swing.JLabel(); jLabel60 = new javax.swing.JLabel(); jLabel61 = new javax.swing.JLabel(); label_item4 = new javax.swing.JLabel(); label_item1 = new javax.swing.JLabel(); label_item2 = new javax.swing.JLabel(); label_item1Name = new javax.swing.JLabel(); label_item1Amount = new javax.swing.JLabel(); label_item2Name = new javax.swing.JLabel(); label_item2Amount = new javax.swing.JLabel(); label_item3Name = new javax.swing.JLabel(); label_item3Amount = new javax.swing.JLabel(); label_item3 = new javax.swing.JLabel(); label_item4Name = new javax.swing.JLabel(); label_item4Amount = new javax.swing.JLabel(); jPanel20 = new javax.swing.JPanel(); ucoinsShop = new javax.swing.JLabel(); creditsShop = new javax.swing.JLabel(); punkteShop = new javax.swing.JLabel(); jButton12 = new javax.swing.JButton(); jLabel70 = new javax.swing.JLabel(); jLabel71 = new javax.swing.JLabel(); jLabel72 = new javax.swing.JLabel(); jLabel85 = new javax.swing.JLabel(); jPanel21 = new javax.swing.JPanel(); jLabel54 = new javax.swing.JLabel(); jPanel22 = new javax.swing.JPanel(); label_redBullOverlay = new javax.swing.JLabel(); label_cheatSheetOverlay = new javax.swing.JLabel(); label_omniOverlay = new javax.swing.JLabel(); label_duploOverlay = new javax.swing.JLabel(); panel_redBull = new javax.swing.JPanel(); label_redBullName = new javax.swing.JLabel(); label_redBullAmount = new javax.swing.JLabel(); label_redBullLocked = new javax.swing.JLabel(); jPanel23 = new javax.swing.JPanel(); label_omniName = new javax.swing.JLabel(); label_omniLocked = new javax.swing.JLabel(); label_omniAmount = new javax.swing.JLabel(); panel_duplo = new javax.swing.JPanel(); label_duploName = new javax.swing.JLabel(); label_duploAmount = new javax.swing.JLabel(); label_duploLocked = new javax.swing.JLabel(); panel_cheatSheet = new javax.swing.JPanel(); label_cheatSheetName = new javax.swing.JLabel(); label_cheatSheetLocked = new javax.swing.JLabel(); label_cheatSheetAmount = new javax.swing.JLabel(); gamePlaying = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jPanel4 = new javax.swing.JPanel(); jLabel11 = new javax.swing.JLabel(); label_item3Inv = new javax.swing.JLabel(); jLabel18 = new javax.swing.JLabel(); jLabel19 = new javax.swing.JLabel(); jLabel20 = new javax.swing.JLabel(); jLabel21 = new javax.swing.JLabel(); label_ucoinsInv = new javax.swing.JLabel(); label_item2Inv = new javax.swing.JLabel(); label_creditsInv = new javax.swing.JLabel(); label_item3InvName = new javax.swing.JLabel(); label_item3InvAmount = new javax.swing.JLabel(); label_item1Inv = new javax.swing.JLabel(); jLabel13 = new javax.swing.JLabel(); jLabel14 = new javax.swing.JLabel(); label_item1InvName = new javax.swing.JLabel(); label_item2InvName = new javax.swing.JLabel(); label_item2InvAmount = new javax.swing.JLabel(); label_item1InvAmount = new javax.swing.JLabel(); jPanel5 = new javax.swing.JPanel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jProgressBar1 = new javax.swing.JProgressBar(); jProgressBar2 = new javax.swing.JProgressBar(); jProgressBar4 = new javax.swing.JProgressBar(); jButton1 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); jButton5 = new javax.swing.JButton(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); jProgressBar5 = new javax.swing.JProgressBar(); jProgressBar6 = new javax.swing.JProgressBar(); jPanel6 = new javax.swing.JPanel(); label_timer = new javax.swing.JLabel(); jPanel7 = new javax.swing.JPanel(); buyCoins.getContentPane().setLayout(null); label_swapper.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N label_swapper.setText("UCoins => Credits Tausch"); buyCoins.getContentPane().add(label_swapper); label_swapper.setBounds(30, 20, 370, 60); label_swapperUcoins.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N label_swapperUcoins.setText("UCoins:"); buyCoins.getContentPane().add(label_swapperUcoins); label_swapperUcoins.setBounds(50, 90, 80, 30); label_swapperUcoinsAmount.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N label_swapperUcoinsAmount.setText("5"); buyCoins.getContentPane().add(label_swapperUcoinsAmount); label_swapperUcoinsAmount.setBounds(120, 80, 80, 50); label_swapperCredits.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N label_swapperCredits.setText("Credits:"); buyCoins.getContentPane().add(label_swapperCredits); label_swapperCredits.setBounds(50, 160, 70, 30); label_swapperCreditsAmount.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N label_swapperCreditsAmount.setText("600"); buyCoins.getContentPane().add(label_swapperCreditsAmount); label_swapperCreditsAmount.setBounds(120, 150, 80, 50); label_currentExchange.setText("1 UCoin = 100 Credits"); buyCoins.getContentPane().add(label_currentExchange); label_currentExchange.setBounds(230, 120, 140, 40); textfield_swapperUcoins.setMinimumSize(new java.awt.Dimension(30, 20)); textfield_swapperUcoins.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { textfield_swapperUcoinsKeyReleased(evt); } }); buyCoins.getContentPane().add(textfield_swapperUcoins); textfield_swapperUcoins.setBounds(170, 90, 50, 30); button_swapperExchange.setText("Tauschen"); button_swapperExchange.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { button_swapperExchangeActionPerformed(evt); } }); buyCoins.getContentPane().add(button_swapperExchange); button_swapperExchange.setBounds(50, 220, 130, 23); button_swapperAbord.setText("Abbrechen"); button_swapperAbord.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { button_swapperAbordActionPerformed(evt); } }); buyCoins.getContentPane().add(button_swapperAbord); button_swapperAbord.setBounds(210, 220, 130, 23); textfield_swapperCredits.setEditable(false); textfield_swapperCredits.setMinimumSize(new java.awt.Dimension(30, 20)); buyCoins.getContentPane().add(textfield_swapperCredits); textfield_swapperCredits.setBounds(170, 160, 50, 30); label_swapperArrow1.setText("||"); buyCoins.getContentPane().add(label_swapperArrow1); label_swapperArrow1.setBounds(190, 130, 8, 14); label_swapperArrow3.setText("\\/"); buyCoins.getContentPane().add(label_swapperArrow3); label_swapperArrow3.setBounds(190, 140, 40, 14); dialog_error.getContentPane().setLayout(null); label_shopMessage.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); label_shopMessage.setText("Shop - Mitteilung"); dialog_error.getContentPane().add(label_shopMessage); label_shopMessage.setBounds(50, 10, 290, 70); label_shopMessage1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); label_shopMessage1.setText("Erwerbe neue Credits im Spiel oder tausche UCoins!"); dialog_error.getContentPane().add(label_shopMessage1); label_shopMessage1.setBounds(10, 110, 380, 70); label_shopMessage2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); label_shopMessage2.setText("Du hast leider nicht mehr genug Credits/UCoins um das Item zu kaufen"); dialog_error.getContentPane().add(label_shopMessage2); label_shopMessage2.setBounds(10, 80, 380, 70); button_shopMessageOk.setText("OK"); button_shopMessageOk.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { button_shopMessageOkActionPerformed(evt); } }); dialog_error.getContentPane().add(button_shopMessageOk); button_shopMessageOk.setBounds(170, 210, 47, 23); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setMaximumSize(new java.awt.Dimension(1000, 700)); setMinimumSize(new java.awt.Dimension(1000, 700)); setResizable(false); getContentPane().setLayout(new java.awt.GridLayout(1, 0)); jPanel1.setMaximumSize(new java.awt.Dimension(1000, 700)); jPanel1.setMinimumSize(new java.awt.Dimension(1000, 700)); jPanel1.setPreferredSize(new java.awt.Dimension(1000, 700)); jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); startPlanningGame.setMaximumSize(new java.awt.Dimension(1000, 700)); startPlanningGame.setMinimumSize(new java.awt.Dimension(1000, 700)); startPlanningGame.setName(""); // NOI18N startPlanningGame.setPreferredSize(new java.awt.Dimension(1000, 700)); startPlanningGame.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); Menu_overlay.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pictures/hauptmenue1000x700.png"))); // NOI18N Menu_overlay.setText("Overlay_hauptmenü"); startPlanningGame.add(Menu_overlay, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1)); startNewGame.setText("Neues Spiel"); startNewGame.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { startNewGameActionPerformed(evt); } }); startPlanningGame.add(startNewGame, new org.netbeans.lib.awtextra.AbsoluteConstraints(640, 200, 160, 40)); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N jLabel1.setText("SIMS Test Menü"); jLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); startPlanningGame.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(340, 100, 330, 80)); exit.setText("Beenden"); exit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exitActionPerformed(evt); } }); startPlanningGame.add(exit, new org.netbeans.lib.awtextra.AbsoluteConstraints(640, 440, 160, 40)); loadGame.setText("Spiel Laden"); loadGame.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { loadGameActionPerformed(evt); } }); startPlanningGame.add(loadGame, new org.netbeans.lib.awtextra.AbsoluteConstraints(620, 240, 210, 40)); jButton6.setText("Credits"); jButton6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton6ActionPerformed(evt); } }); startPlanningGame.add(jButton6, new org.netbeans.lib.awtextra.AbsoluteConstraints(640, 360, 160, 40)); jButton7.setText("Profil"); jButton7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton7ActionPerformed(evt); } }); startPlanningGame.add(jButton7, new org.netbeans.lib.awtextra.AbsoluteConstraints(650, 280, 160, 40)); jButton8.setText("Abmelden"); jButton8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton8ActionPerformed(evt); } }); startPlanningGame.add(jButton8, new org.netbeans.lib.awtextra.AbsoluteConstraints(640, 400, 160, 40)); jButton13.setText("Statistik"); jButton13.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton13ActionPerformed(evt); } }); startPlanningGame.add(jButton13, new org.netbeans.lib.awtextra.AbsoluteConstraints(650, 320, 160, 40)); jPanel1.add(startPlanningGame, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1000, 700)); jPanel2.setLayout(new java.awt.CardLayout()); gamePlanning.setName("card3"); // NOI18N gamePlanning.setLayout(null); Logo.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); Logo.setLayout(null); jLab_Logo.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLab_Logo.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLab_Logo.setText("SIMS Logo"); jLab_Logo.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLab_LogoMouseClicked(evt); } }); Logo.add(jLab_Logo); jLab_Logo.setBounds(0, 0, 150, 110); gamePlanning.add(Logo); Logo.setBounds(0, 0, 150, 110); Header.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); Header.setLayout(null); jLabel41.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel41.setText("Wissen:"); Header.add(jLabel41); jLabel41.setBounds(10, 20, 70, 20); jLabel42.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel42.setText("Motivation:"); Header.add(jLabel42); jLabel42.setBounds(10, 40, 80, 30); jLabel43.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel43.setText("Müdigkeit:"); Header.add(jLabel43); jLabel43.setBounds(10, 80, 90, 20); Header.add(jProgB_Müdigkeit); jProgB_Müdigkeit.setBounds(90, 80, 260, 20); Header.add(jProgB_Motivation); jProgB_Motivation.setBounds(90, 50, 260, 20); Header.add(jProgB_Wissen); jProgB_Wissen.setBounds(90, 20, 260, 20); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N jLabel3.setText("PLANUNGSPHASE"); Header.add(jLabel3); jLabel3.setBounds(360, 10, 340, 90); gamePlanning.add(Header); Header.setBounds(150, 0, 700, 110); Shop.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); Shop.setLayout(null); jBut_startShop.setFont(new java.awt.Font("Lucida Grande", 1, 24)); // NOI18N jBut_startShop.setText("SHOP"); jBut_startShop.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jBut_startShopMouseClicked(evt); } }); jBut_startShop.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBut_startShopActionPerformed(evt); } }); Shop.add(jBut_startShop); jBut_startShop.setBounds(5, 5, 120, 100); gamePlanning.add(Shop); Shop.setBounds(850, 0, 130, 110); Navi.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); Navi.setLayout(null); jPan_StudSwitch.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPan_StudSwitch.setLayout(null); jPan_StudSwitch.add(jLab_StudSwitch); jLab_StudSwitch.setBounds(0, 0, 150, 110); jLabel4.setText("umsetzen"); jPan_StudSwitch.add(jLabel4); jLabel4.setBounds(40, 40, 70, 14); jLabel90.setText("Studenten"); jPan_StudSwitch.add(jLabel90); jLabel90.setBounds(40, 20, 70, 20); jLab_StudCounter.setFont(new java.awt.Font("Lucida Grande", 1, 18)); // NOI18N jLab_StudCounter.setText("5x"); jPan_StudSwitch.add(jLab_StudCounter); jLab_StudCounter.setBounds(60, 60, 30, 24); jBut_BackG.setFont(new java.awt.Font("Lucida Grande", 1, 18)); // NOI18N jBut_BackG.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBut_BackGActionPerformed(evt); } }); jPan_StudSwitch.add(jBut_BackG); jBut_BackG.setBounds(10, 10, 130, 90); Navi.add(jPan_StudSwitch); jPan_StudSwitch.setBounds(0, 0, 150, 110); jPan_StudSwitch.getAccessibleContext().setAccessibleDescription(""); jPan_DozSwitch.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPan_DozSwitch.setLayout(null); jPan_DozSwitch.add(jLab_DozSwitch); jLab_DozSwitch.setBounds(0, 0, 150, 110); jLabel91.setText("Dozenten"); jPan_DozSwitch.add(jLabel91); jLabel91.setBounds(40, 20, 70, 20); jLabel27.setText("tauschen"); jPan_DozSwitch.add(jLabel27); jLabel27.setBounds(40, 40, 60, 20); jLab_DozCounter.setFont(new java.awt.Font("Lucida Grande", 1, 18)); // NOI18N jLab_DozCounter.setText("1x"); jPan_DozSwitch.add(jLab_DozCounter); jLab_DozCounter.setBounds(60, 60, 30, 30); jBut_BackG2.setFont(new java.awt.Font("Lucida Grande", 1, 18)); // NOI18N jBut_BackG2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBut_BackG2ActionPerformed(evt); } }); jPan_DozSwitch.add(jBut_BackG2); jBut_BackG2.setBounds(10, 10, 130, 90); Navi.add(jPan_DozSwitch); jPan_DozSwitch.setBounds(0, 110, 150, 110); jPan_ItemSelect.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPan_ItemSelect.setLayout(null); jComboB_Items.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "wähle Item", "Spicker" })); jPan_ItemSelect.add(jComboB_Items); jComboB_Items.setBounds(10, 20, 130, 30); jBut_ComboB_useItem.setText("Benutzen"); jPan_ItemSelect.add(jBut_ComboB_useItem); jBut_ComboB_useItem.setBounds(10, 60, 120, 23); Navi.add(jPan_ItemSelect); jPan_ItemSelect.setBounds(0, 220, 150, 110); jPan_ItemStorage.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPan_ItemStorage.setLayout(null); jLabel8.setFont(new java.awt.Font("Lucida Grande", 1, 14)); // NOI18N jLabel8.setText("Item-Vorräte"); jPan_ItemStorage.add(jLabel8); jLabel8.setBounds(10, 10, 120, 20); jLab_Redbull.setText("Redbull: 5"); jPan_ItemStorage.add(jLab_Redbull); jLab_Redbull.setBounds(10, 40, 90, 14); jLab_Duplo.setText("Duplo: 3"); jPan_ItemStorage.add(jLab_Duplo); jLab_Duplo.setBounds(10, 60, 90, 14); jLab_OMNI.setText("OMNI Sense Buch: 1"); jPan_ItemStorage.add(jLab_OMNI); jLab_OMNI.setBounds(10, 80, 140, 14); Navi.add(jPan_ItemStorage); jPan_ItemStorage.setBounds(0, 330, 150, 110); jPanel32.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel32.setLayout(null); jBut_Play.setFont(new java.awt.Font("Lucida Grande", 1, 18)); // NOI18N jBut_Play.setText("SPIELEN"); jBut_Play.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBut_PlayActionPerformed(evt); } }); jPanel32.add(jBut_Play); jBut_Play.setBounds(10, 10, 130, 90); Navi.add(jPanel32); jPanel32.setBounds(0, 440, 150, 110); gamePlanning.add(Navi); Navi.setBounds(0, 110, 150, 550); StudField.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); StudField.setLayout(null); jBut_Dozent.setText("Dozent"); StudField.add(jBut_Dozent); jBut_Dozent.setBounds(340, 470, 110, 50); jBut_1.setText("Platz_1"); jBut_1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBut_1ActionPerformed(evt); } }); StudField.add(jBut_1); jBut_1.setBounds(60, 10, 110, 50); jBut_2.setText("Platz_2"); StudField.add(jBut_2); jBut_2.setBounds(210, 10, 110, 50); jBut_3.setText("Platz_3"); StudField.add(jBut_3); jBut_3.setBounds(360, 10, 110, 50); jBut_4.setText("Platz_4"); StudField.add(jBut_4); jBut_4.setBounds(510, 10, 110, 50); jBut_5.setText("Platz_5"); StudField.add(jBut_5); jBut_5.setBounds(660, 10, 110, 50); jBut_6.setText("Platz_6"); StudField.add(jBut_6); jBut_6.setBounds(60, 80, 110, 50); jBut_7.setText("Platz_7"); StudField.add(jBut_7); jBut_7.setBounds(210, 80, 110, 50); jBut_8.setText("Platz_8"); StudField.add(jBut_8); jBut_8.setBounds(360, 80, 110, 50); jBut_9.setText("Platz_9"); StudField.add(jBut_9); jBut_9.setBounds(510, 80, 110, 50); jBut_10.setText("Platz_10"); StudField.add(jBut_10); jBut_10.setBounds(660, 80, 110, 50); jBut_11.setText("Platz_11"); StudField.add(jBut_11); jBut_11.setBounds(60, 150, 110, 50); jBut_12.setText("Platz_12"); StudField.add(jBut_12); jBut_12.setBounds(210, 150, 110, 50); jBut_13.setText("Platz_13"); StudField.add(jBut_13); jBut_13.setBounds(360, 150, 110, 50); jBut_14.setText("Platz_14"); StudField.add(jBut_14); jBut_14.setBounds(510, 150, 110, 50); jBut_15.setText("Platz_15"); StudField.add(jBut_15); jBut_15.setBounds(660, 150, 110, 50); jBut_16.setText("Platz_16"); StudField.add(jBut_16); jBut_16.setBounds(60, 220, 110, 50); jBut_17.setText("Platz_17"); jBut_17.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBut_17ActionPerformed(evt); } }); StudField.add(jBut_17); jBut_17.setBounds(210, 220, 110, 50); jBut_18.setText("Platz_18"); StudField.add(jBut_18); jBut_18.setBounds(360, 220, 110, 50); jBut_19.setText("Platz_19"); StudField.add(jBut_19); jBut_19.setBounds(510, 220, 110, 50); jBut_20.setText("Platz_20"); StudField.add(jBut_20); jBut_20.setBounds(660, 220, 110, 50); jBut_21.setText("Platz_21"); StudField.add(jBut_21); jBut_21.setBounds(60, 290, 110, 50); jBut_22.setText("Platz_22"); StudField.add(jBut_22); jBut_22.setBounds(210, 290, 110, 50); jBut_23.setText("Platz_23"); StudField.add(jBut_23); jBut_23.setBounds(360, 290, 110, 50); jBut_24.setText("Platz_24"); StudField.add(jBut_24); jBut_24.setBounds(510, 290, 110, 50); jBut_25.setText("Platz_25"); StudField.add(jBut_25); jBut_25.setBounds(660, 290, 110, 50); jBut_26.setText("Platz_26"); StudField.add(jBut_26); jBut_26.setBounds(60, 360, 110, 50); jBut_27.setText("Platz_27"); jBut_27.setToolTipText(""); StudField.add(jBut_27); jBut_27.setBounds(210, 360, 110, 50); jBut_28.setText("Platz_28"); StudField.add(jBut_28); jBut_28.setBounds(360, 360, 110, 50); jBut_29.setText("Platz_29"); StudField.add(jBut_29); jBut_29.setBounds(510, 360, 110, 50); jBut_30.setText("Platz_30"); StudField.add(jBut_30); jBut_30.setBounds(660, 360, 110, 50); gamePlanning.add(StudField); StudField.setBounds(150, 110, 830, 550); jPanel2.add(gamePlanning, "card3"); shop.setLayout(null); jPanel18.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel18.setLayout(null); jLabel55.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel55.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel55.setText("SIMS Logo"); jLabel55.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel55MouseClicked(evt); } }); jPanel18.add(jLabel55); jLabel55.setBounds(0, 0, 150, 110); shop.add(jPanel18); jPanel18.setBounds(0, 0, 150, 110); jPanel19.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel19.setLayout(null); label_inventar.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N label_inventar.setText("Inventar"); jPanel19.add(label_inventar); label_inventar.setBounds(30, 0, 120, 40); jLabel58.setText("Studenten:"); jPanel19.add(jLabel58); jLabel58.setBounds(10, 450, 80, 14); jLabel59.setText("4 / 40"); jPanel19.add(jLabel59); jLabel59.setBounds(80, 450, 50, 14); jLabel60.setText("Semester: "); jPanel19.add(jLabel60); jLabel60.setBounds(10, 470, 80, 14); jLabel61.setText("3 / 6"); jPanel19.add(jLabel61); jLabel61.setBounds(80, 470, 60, 14); label_item4.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel19.add(label_item4); label_item4.setBounds(30, 350, 90, 80); label_item1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel19.add(label_item1); label_item1.setBounds(30, 50, 90, 80); label_item2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); label_item2.setPreferredSize(new java.awt.Dimension(20, 20)); jPanel19.add(label_item2); label_item2.setBounds(30, 150, 90, 80); label_item1Name.setText("jLabel4"); jPanel19.add(label_item1Name); label_item1Name.setBounds(60, 80, 34, 14); label_item1Amount.setText("jLabel4"); jPanel19.add(label_item1Amount); label_item1Amount.setBounds(60, 100, 34, 14); label_item2Name.setText("jLabel4"); jPanel19.add(label_item2Name); label_item2Name.setBounds(60, 190, 34, 14); label_item2Amount.setText("jLabel4"); jPanel19.add(label_item2Amount); label_item2Amount.setBounds(60, 210, 34, 14); label_item3Name.setText("jLabel4"); jPanel19.add(label_item3Name); label_item3Name.setBounds(60, 380, 34, 14); label_item3Amount.setText("jLabel26"); jPanel19.add(label_item3Amount); label_item3Amount.setBounds(60, 400, 40, 14); label_item3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel19.add(label_item3); label_item3.setBounds(30, 250, 90, 80); label_item4Name.setText("jLabel4"); jPanel19.add(label_item4Name); label_item4Name.setBounds(60, 280, 34, 14); label_item4Amount.setText("jLabel26"); jPanel19.add(label_item4Amount); label_item4Amount.setBounds(60, 300, 40, 14); shop.add(jPanel19); jPanel19.setBounds(0, 110, 150, 550); jPanel20.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel20.setLayout(null); ucoinsShop.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N ucoinsShop.setText("0"); jPanel20.add(ucoinsShop); ucoinsShop.setBounds(80, 10, 80, 20); creditsShop.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N creditsShop.setText("0"); jPanel20.add(creditsShop); creditsShop.setBounds(80, 40, 70, 17); punkteShop.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N punkteShop.setText("0"); jPanel20.add(punkteShop); punkteShop.setBounds(80, 70, 70, 17); jButton12.setText("UCoins Tauschen"); jButton12.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton12ActionPerformed(evt); } }); jPanel20.add(jButton12); jButton12.setBounds(230, 10, 160, 90); jLabel70.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel70.setText("UCoins:"); jPanel20.add(jLabel70); jLabel70.setBounds(10, 10, 80, 20); jLabel71.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel71.setText("Credits:"); jPanel20.add(jLabel71); jLabel71.setBounds(10, 40, 70, 17); jLabel72.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel72.setText("Punkte:"); jPanel20.add(jLabel72); jLabel72.setBounds(10, 70, 70, 17); jLabel85.setFont(new java.awt.Font("Tahoma", 1, 48)); // NOI18N jLabel85.setText("SHOP"); jPanel20.add(jLabel85); jLabel85.setBounds(470, 0, 210, 110); shop.add(jPanel20); jPanel20.setBounds(150, 0, 700, 110); jPanel21.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel21.setLayout(null); jLabel54.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel54.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel54.setText("SPIEL"); jLabel54.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel54MouseClicked(evt); } }); jPanel21.add(jLabel54); jLabel54.setBounds(0, 0, 130, 110); shop.add(jPanel21); jPanel21.setBounds(850, 0, 130, 110); jPanel22.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel22.setLayout(null); label_redBullOverlay.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); label_redBullOverlay.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { label_redBullOverlayMouseClicked(evt); } }); jPanel22.add(label_redBullOverlay); label_redBullOverlay.setBounds(100, 40, 230, 220); label_cheatSheetOverlay.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); label_cheatSheetOverlay.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { label_cheatSheetOverlayMouseClicked(evt); } }); jPanel22.add(label_cheatSheetOverlay); label_cheatSheetOverlay.setBounds(100, 300, 230, 220); label_omniOverlay.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); label_omniOverlay.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { label_omniOverlayMouseClicked(evt); } }); jPanel22.add(label_omniOverlay); label_omniOverlay.setBounds(510, 300, 230, 220); label_duploOverlay.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); label_duploOverlay.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { label_duploOverlayMouseClicked(evt); } }); jPanel22.add(label_duploOverlay); label_duploOverlay.setBounds(510, 40, 230, 220); panel_redBull.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); panel_redBull.setName("panel_redBull"); // NOI18N panel_redBull.setLayout(null); label_redBullName.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N label_redBullName.setText("Red Bull"); panel_redBull.add(label_redBullName); label_redBullName.setBounds(0, 130, 230, 30); label_redBullAmount.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N label_redBullAmount.setText("100 Credits"); panel_redBull.add(label_redBullAmount); label_redBullAmount.setBounds(0, 150, 230, 50); label_redBullLocked.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N label_redBullLocked.setForeground(new java.awt.Color(204, 51, 0)); label_redBullLocked.setText("GESPERRT"); panel_redBull.add(label_redBullLocked); label_redBullLocked.setBounds(50, 10, 230, 110); jPanel22.add(panel_redBull); panel_redBull.setBounds(100, 40, 230, 220); jPanel23.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel23.setLayout(null); label_omniName.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N label_omniName.setText("Verfügbar ab Semester 4"); jPanel23.add(label_omniName); label_omniName.setBounds(0, 120, 230, 50); label_omniLocked.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N label_omniLocked.setForeground(new java.awt.Color(204, 51, 0)); label_omniLocked.setText("GESPERRT"); jPanel23.add(label_omniLocked); label_omniLocked.setBounds(50, 20, 230, 110); label_omniAmount.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N label_omniAmount.setText("5 UCoins"); jPanel23.add(label_omniAmount); label_omniAmount.setBounds(0, 150, 230, 50); jPanel22.add(jPanel23); jPanel23.setBounds(510, 300, 230, 220); panel_duplo.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); panel_duplo.setLayout(null); label_duploName.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N label_duploName.setText("Duplo"); panel_duplo.add(label_duploName); label_duploName.setBounds(0, 130, 230, 30); label_duploAmount.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N label_duploAmount.setText("100 Credits"); panel_duplo.add(label_duploAmount); label_duploAmount.setBounds(0, 150, 230, 50); label_duploLocked.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N label_duploLocked.setForeground(new java.awt.Color(204, 51, 0)); label_duploLocked.setText("GESPERRT"); panel_duplo.add(label_duploLocked); label_duploLocked.setBounds(50, 10, 230, 110); jPanel22.add(panel_duplo); panel_duplo.setBounds(510, 40, 230, 220); panel_cheatSheet.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); panel_cheatSheet.setLayout(null); label_cheatSheetName.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N label_cheatSheetName.setText("Spicker"); panel_cheatSheet.add(label_cheatSheetName); label_cheatSheetName.setBounds(0, 130, 230, 30); label_cheatSheetLocked.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N label_cheatSheetLocked.setForeground(new java.awt.Color(204, 51, 0)); label_cheatSheetLocked.setText("GESPERRT"); panel_cheatSheet.add(label_cheatSheetLocked); label_cheatSheetLocked.setBounds(50, 10, 230, 110); label_cheatSheetAmount.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N label_cheatSheetAmount.setText("5 UCoins"); panel_cheatSheet.add(label_cheatSheetAmount); label_cheatSheetAmount.setBounds(0, 150, 230, 50); jPanel22.add(panel_cheatSheet); panel_cheatSheet.setBounds(100, 300, 230, 220); shop.add(jPanel22); jPanel22.setBounds(150, 110, 830, 550); jPanel2.add(shop, "card4"); gamePlaying.setMinimumSize(new java.awt.Dimension(1024, 768)); gamePlaying.setPreferredSize(new java.awt.Dimension(1024, 768)); gamePlaying.setLayout(null); jPanel3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel3.setLayout(null); jLabel2.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel2.setText("SIMS Logo"); jLabel2.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel2MouseClicked(evt); } }); jPanel3.add(jLabel2); jLabel2.setBounds(0, 0, 150, 110); gamePlaying.add(jPanel3); jPanel3.setBounds(0, 0, 150, 110); jPanel4.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel4.setLayout(null); jLabel11.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel11.setText("Inventar"); jPanel4.add(jLabel11); jLabel11.setBounds(30, 0, 120, 40); label_item3Inv.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel4.add(label_item3Inv); label_item3Inv.setBounds(30, 250, 80, 80); jLabel18.setText("Studenten:"); jPanel4.add(jLabel18); jLabel18.setBounds(10, 450, 80, 14); jLabel19.setText("4 / 40"); jPanel4.add(jLabel19); jLabel19.setBounds(80, 450, 50, 14); jLabel20.setText("Semester: "); jPanel4.add(jLabel20); jLabel20.setBounds(10, 470, 80, 14); jLabel21.setText("3 / 6"); jPanel4.add(jLabel21); jLabel21.setBounds(80, 470, 60, 14); label_ucoinsInv.setText("UCoins: 300"); jPanel4.add(label_ucoinsInv); label_ucoinsInv.setBounds(10, 380, 130, 14); label_item2Inv.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel4.add(label_item2Inv); label_item2Inv.setBounds(30, 150, 80, 80); label_creditsInv.setText("Credits: 700"); jPanel4.add(label_creditsInv); label_creditsInv.setBounds(10, 360, 140, 14); label_item3InvName.setText("Red Bull"); jPanel4.add(label_item3InvName); label_item3InvName.setBounds(30, 260, 80, 30); label_item3InvAmount.setText("3 x"); jPanel4.add(label_item3InvAmount); label_item3InvAmount.setBounds(30, 300, 80, 14); label_item1Inv.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel4.add(label_item1Inv); label_item1Inv.setBounds(30, 50, 80, 80); jLabel13.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel13.setText("Punkte:"); jPanel4.add(jLabel13); jLabel13.setBounds(10, 510, 70, 20); jLabel14.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel14.setText("700"); jPanel4.add(jLabel14); jLabel14.setBounds(90, 500, 40, 40); label_item1InvName.setText("Red Bull"); jPanel4.add(label_item1InvName); label_item1InvName.setBounds(30, 80, 80, 30); label_item2InvName.setText("Red Bull"); jPanel4.add(label_item2InvName); label_item2InvName.setBounds(30, 160, 80, 30); label_item2InvAmount.setText("3 x"); jPanel4.add(label_item2InvAmount); label_item2InvAmount.setBounds(30, 190, 80, 14); label_item1InvAmount.setText("3 x"); jPanel4.add(label_item1InvAmount); label_item1InvAmount.setBounds(30, 110, 80, 14); gamePlaying.add(jPanel4); jPanel4.setBounds(0, 110, 150, 550); jPanel5.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel5.setLayout(null); jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel5.setText("Wissen:"); jPanel5.add(jLabel5); jLabel5.setBounds(10, 10, 70, 20); jLabel6.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel6.setText("Motivation:"); jPanel5.add(jLabel6); jLabel6.setBounds(10, 30, 80, 40); jLabel7.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel7.setText("Müdigkeit:"); jPanel5.add(jLabel7); jLabel7.setBounds(10, 80, 80, 20); jPanel5.add(jProgressBar1); jProgressBar1.setBounds(80, 10, 260, 20); jPanel5.add(jProgressBar2); jProgressBar2.setBounds(80, 40, 260, 20); jPanel5.add(jProgressBar4); jProgressBar4.setBounds(80, 80, 260, 20); jButton1.setText("Fenster : AUF"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jPanel5.add(jButton1); jButton1.setBounds(350, 10, 120, 23); jButton4.setText("Gruppenarbeit"); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); jPanel5.add(jButton4); jButton4.setBounds(350, 40, 120, 23); jButton5.setText("Pause"); jPanel5.add(jButton5); jButton5.setBounds(350, 80, 120, 23); jLabel9.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel9.setText("Lärmpegel:"); jPanel5.add(jLabel9); jLabel9.setBounds(480, 10, 80, 20); jLabel10.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel10.setText("Luftqualität:"); jPanel5.add(jLabel10); jLabel10.setBounds(480, 34, 80, 30); jPanel5.add(jProgressBar5); jProgressBar5.setBounds(560, 10, 130, 20); jPanel5.add(jProgressBar6); jProgressBar6.setBounds(560, 40, 130, 20); gamePlaying.add(jPanel5); jPanel5.setBounds(150, 0, 700, 110); jPanel6.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel6.setLayout(null); label_timer.setFont(new java.awt.Font("Tahoma", 1, 48)); // NOI18N label_timer.setText("--:--"); jPanel6.add(label_timer); label_timer.setBounds(10, 10, 140, 90); gamePlaying.add(jPanel6); jPanel6.setBounds(850, 0, 130, 110); jPanel7.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); gamePlaying.add(jPanel7); jPanel7.setBounds(150, 110, 830, 550); jPanel2.add(gamePlaying, "card2"); jPanel1.add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1024, 768)); getContentPane().add(jPanel1); pack(); }// </editor-fold>//GEN-END:initComponents
diff --git a/src/filius/software/transportschicht/TransportProtokoll.java b/src/filius/software/transportschicht/TransportProtokoll.java index 60a1388..559163e 100644 --- a/src/filius/software/transportschicht/TransportProtokoll.java +++ b/src/filius/software/transportschicht/TransportProtokoll.java @@ -1,233 +1,229 @@ /* ** This file is part of Filius, a network construction and simulation software. ** ** Originally created at the University of Siegen, Institute "Didactics of ** Informatics and E-Learning" by a students' project group: ** members (2006-2007): ** André Asschoff, Johannes Bade, Carsten Dittich, Thomas Gerding, ** Nadja Haßler, Ernst Johannes Klebert, Michell Weyer ** supervisors: ** Stefan Freischlad (maintainer until 2009), Peer Stechert ** Project is maintained since 2010 by Christian Eibl <[email protected]> ** and Stefan Freischlad ** Filius 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) version 3. ** ** Filius 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 Filius. If not, see <http://www.gnu.org/licenses/>. */ package filius.software.transportschicht; import java.lang.Thread.State; import java.util.Hashtable; import java.util.LinkedList; import java.util.Random; import filius.Main; import filius.exception.SocketException; import filius.exception.VerbindungsException; import filius.rahmenprogramm.I18n; import filius.software.Protokoll; import filius.software.system.InternetKnotenBetriebssystem; public abstract class TransportProtokoll extends Protokoll implements I18n, Runnable { private static final int PORT_UNTERE_GRENZE = 1024; private static final int PORT_OBERE_GRENZE = 65535; protected static final int TTL = 64; private int typ; /** IP-Adresse und Segment, das in einem neuen Thread verschickt wird */ private LinkedList<Object[]> segmentListe = new LinkedList<Object[]>(); private Hashtable<Integer, SocketSchnittstelle> portTabelle; private TransportProtokollThread thread; /** * Dieser Thread fuehrt die run()-Methode dieser Klasse aus und wird dazu * verwendet, Segmente zu verschicken. */ private Thread sendeThread = null; /** * In diesem Attribut wird gespeichert, ob der Thread zum Versenden von * Segmenten laeuft. */ private boolean running = false; /** * @author carsten * @param betriebssystem */ public TransportProtokoll(InternetKnotenBetriebssystem betriebssystem, int typ) { super(betriebssystem); Main.debug.println("INVOKED-2 ("+this.hashCode()+") "+getClass()+" (TransportProtokoll), constr: TransportProtokoll("+betriebssystem+","+typ+")"); this.typ = typ; portTabelle = new Hashtable<Integer, SocketSchnittstelle>(); } public Hashtable<Integer, SocketSchnittstelle> holeAktiveSockets() { return this.portTabelle; } public int holeTyp() { return typ; } public int reserviereFreienPort(Socket socket) { Main.debug.println("INVOKED ("+this.hashCode()+") "+getClass()+" (TransportProtokoll), reserviereFreienPort("+socket+")"); // Freien Port suchen boolean portGefunden = false; int freienPort; do { freienPort = sucheFreienPort(); if (!portTabelle.containsKey(freienPort)) { portGefunden = true; } } while (!portGefunden); reservierePort(freienPort, socket); return freienPort; } public SocketSchnittstelle holeSocket(int port) throws SocketException { Main.debug.println("INVOKED ("+this.hashCode()+") "+getClass()+" (TransportProtokoll), holeSocket("+port+")"); if (port == -1 ) { throw new SocketException(messages.getString("sw_transportprotokoll_msg3")); } if (!portTabelle.containsKey(port)) throw new SocketException(messages .getString("sw_transportprotokoll_msg1") + " " + port + " " + messages.getString("sw_transportprotokoll_msg2")); return (SocketSchnittstelle) portTabelle.get(port); } public boolean isUsed(int port) { return portTabelle.containsKey(port); } private int sucheFreienPort() { Main.debug.println("INVOKED ("+this.hashCode()+") "+getClass()+" (TransportProtokoll), sucheFreienPort()"); int spanne = PORT_OBERE_GRENZE - PORT_UNTERE_GRENZE; Random random = new Random(); int zufallsZahl = Math.abs(random.nextInt()); int zahl = (zufallsZahl) % spanne; return (PORT_UNTERE_GRENZE + zahl); } public boolean reservierePort(int port, SocketSchnittstelle socket) { Main.debug.println("INVOKED ("+this.hashCode()+") "+getClass()+" (TransportProtokoll), reservierePort("+port+","+socket+")"); if (portTabelle.containsKey(port)) { Main.debug.println("ERROR ("+this.hashCode()+"): Port "+port+" ist bereits belegt!"); return false; } else { portTabelle.put(port, socket); return true; } } public boolean gibPortFrei(int port) { Main.debug.println("INVOKED ("+this.hashCode()+") "+getClass()+" (TransportProtokoll), gibPortFrei("+port+")"); if (portTabelle.containsKey(port)) { portTabelle.remove(port); return true; } else { return false; } } /** * @param zielIp - * Ip des Empfaengers * @param protokoll - * Protokollnummer des Protokolls, auf dass aufgesetzt wird. * @param segment - * Segment mit Daten zur IP-Schicht */ protected void senden(String zielIp, Object segment) { Main.debug.println("INVOKED ("+this.hashCode()+") "+getClass()+" (TransportProtokoll), senden("+zielIp+","+segment+")"); // Main.debug.println(getClass().toString() // + "\n\tsenden() wurde aufgerufen" + "\n\tZiel-Adresse: " // + zielIp + ":" + ((Segment) segment).getZielPort() // + "\n\tDaten: " + ((Segment) segment).getDaten()); segmentListe.addLast((new Object[] { zielIp, segment })); synchronized (segmentListe) { segmentListe.notifyAll(); } } public void run() { Main.debug.println("INVOKED ("+this.hashCode()+") "+getClass()+" (TransportProtokoll), run()"); InternetKnotenBetriebssystem bs; Object[] temp; while (running) { synchronized (segmentListe) { if (segmentListe.size() < 1) { try { segmentListe.wait(); } catch (InterruptedException e1) { } } if (segmentListe.size() > 0) { temp = (Object[]) segmentListe.removeFirst(); bs = (InternetKnotenBetriebssystem) holeSystemSoftware(); - try { - bs.holeIP().senden((String) temp[0], holeTyp(), TTL, - temp[1]); - } catch (VerbindungsException e) { - e.printStackTrace(Main.debug); - } + bs.holeIP().senden((String) temp[0], holeTyp(), TTL, + temp[1]); } } } } public void starten() { Main.debug.println("INVOKED ("+this.hashCode()+") "+getClass()+" (TransportProtokoll), starten()"); portTabelle = new Hashtable<Integer, SocketSchnittstelle>(); thread = new TransportProtokollThread(this); thread.starten(); if (!running) { running = true; if (sendeThread != null && (sendeThread.getState().equals(State.WAITING) || sendeThread .getState().equals(State.BLOCKED))) { } else { sendeThread = new Thread(this); sendeThread.start(); } } } public void beenden() { Main.debug.println("INVOKED ("+this.hashCode()+") "+getClass()+" (TransportProtokoll), beenden()"); thread.beenden(); running = false; if (sendeThread != null && (sendeThread.getState().equals(State.WAITING) || sendeThread .getState().equals(State.BLOCKED))) { sendeThread.interrupt(); } } }
true
true
public void run() { Main.debug.println("INVOKED ("+this.hashCode()+") "+getClass()+" (TransportProtokoll), run()"); InternetKnotenBetriebssystem bs; Object[] temp; while (running) { synchronized (segmentListe) { if (segmentListe.size() < 1) { try { segmentListe.wait(); } catch (InterruptedException e1) { } } if (segmentListe.size() > 0) { temp = (Object[]) segmentListe.removeFirst(); bs = (InternetKnotenBetriebssystem) holeSystemSoftware(); try { bs.holeIP().senden((String) temp[0], holeTyp(), TTL, temp[1]); } catch (VerbindungsException e) { e.printStackTrace(Main.debug); } } } } }
public void run() { Main.debug.println("INVOKED ("+this.hashCode()+") "+getClass()+" (TransportProtokoll), run()"); InternetKnotenBetriebssystem bs; Object[] temp; while (running) { synchronized (segmentListe) { if (segmentListe.size() < 1) { try { segmentListe.wait(); } catch (InterruptedException e1) { } } if (segmentListe.size() > 0) { temp = (Object[]) segmentListe.removeFirst(); bs = (InternetKnotenBetriebssystem) holeSystemSoftware(); bs.holeIP().senden((String) temp[0], holeTyp(), TTL, temp[1]); } } } }
diff --git a/loci/plugins/LociUploader.java b/loci/plugins/LociUploader.java index 10c3852dc..0915c1c21 100644 --- a/loci/plugins/LociUploader.java +++ b/loci/plugins/LociUploader.java @@ -1,214 +1,215 @@ // // LociUploader.java // /* LOCI Plugins for ImageJ: a collection of ImageJ plugins including the 4D Data Browser, OME Plugin and Bio-Formats Exporter. Copyright (C) 2006-@year@ Melissa Linkert, Christopher Peterson, Curtis Rueden, Philip Huettl and Francis Wong. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library 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 Library General Public License for more details. You should have received a copy of the GNU Library 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.plugins; import java.awt.TextField; import ij.*; import ij.gui.GenericDialog; import ij.plugin.PlugIn; import ij.process.*; import ij.io.FileInfo; import loci.formats.*; import loci.formats.ome.*; /** * ImageJ plugin for uploading images to an OME server. * * @author Melissa Linkert linket at wisc.edu */ public class LociUploader implements PlugIn { // -- Fields -- private String server; private String user; private String pass; // -- PlugIn API methods -- public synchronized void run(String arg) { // check that we can safely execute the plugin if (Util.checkVersion() && Util.checkLibraries(true, true, true, false)) { promptForLogin(); uploadStack(); } else { } } // -- Helper methods -- /** Open a dialog box that prompts for a username, password, and server. */ private void promptForLogin() { GenericDialog prompt = new GenericDialog("Login to OME"); prompt.addStringField("Server: ", Prefs.get("uploader.server", ""), 60); prompt.addStringField("Username: ", Prefs.get("uploader.user", ""), 60); prompt.addStringField("Password: ", "", 60); ((TextField) prompt.getStringFields().get(2)).setEchoChar('*'); prompt.showDialog(); server = prompt.getNextString(); user = prompt.getNextString(); pass = prompt.getNextString(); Prefs.set("uploader.server", server); Prefs.set("uploader.user", user); } /** Log in to the OME server and upload the current image stack. */ private void uploadStack() { try { IJ.showStatus("Starting upload..."); OMEWriter ul = new OMEWriter(); String id = server + "?user=" + user + "&password=" + pass; + ul.setId(id); ImagePlus imp = WindowManager.getCurrentImage(); if (imp == null) { IJ.error("No open images!"); IJ.showStatus(""); return; } ImageStack is = imp.getImageStack(); FileInfo fi = imp.getOriginalFileInfo(); OMEXMLMetadataStore store = new OMEXMLMetadataStore(); // if we opened this stack with the Bio-Formats importer, then the // appropriate OME-XML is in fi.description if (fi != null && fi.description != null && fi.description.endsWith("</OME>")) { store.createRoot(fi.description); } else { store.createRoot(); int pixelType = FormatTools.UINT8; switch (imp.getBitDepth()) { case 16: pixelType = FormatTools.UINT16; break; case 32: pixelType = FormatTools.FLOAT; break; } store.setPixels( new Integer(imp.getWidth()), new Integer(imp.getHeight()), new Integer(imp.getNSlices()), new Integer(imp.getNChannels()), new Integer(imp.getNFrames()), new Integer(pixelType), fi == null ? Boolean.TRUE : new Boolean(!fi.intelByteOrder), "XYCZT", // TODO : figure out a way to calculate the dimension order null, null); String name = fi == null ? imp.getTitle() : fi.fileName; store.setImage(name, null, fi == null ? null : fi.info, null); } if (is.getProcessor(1) instanceof ColorProcessor) { store.setPixels(null, null, null, null, null, new Integer(FormatTools.UINT8), null, null, null, null); } ul.setMetadataStore(store); boolean little = !store.getBigEndian(null).booleanValue(); for (int i=0; i<is.getSize(); i++) { IJ.showStatus("Reading plane " + (i+1) + "/" + is.getSize()); Object pix = is.getProcessor(i + 1).getPixels(); byte[] toUpload = null; if (pix instanceof byte[]) { toUpload = (byte[]) pix; } else if (pix instanceof short[]) { short[] s = (short[]) pix; toUpload = new byte[s.length * 2]; for (int j=0; j<s.length; j++) { toUpload[j*2] = little ? (byte) (s[j] & 0xff) : (byte) ((s[j] >>> 8) & 0xff); toUpload[j*2 + 1] = little ? (byte) ((s[j] >>> 8) & 0xff): (byte) (s[j] & 0xff); } } else if (pix instanceof int[]) { if (is.getProcessor(i+1) instanceof ColorProcessor) { byte[][] rgb = new byte[3][((int[]) pix).length]; ((ColorProcessor) is.getProcessor(i+1)).getRGB(rgb[0], rgb[1], rgb[2]); int channels = store.getSizeC(null).intValue(); if (channels > 3) channels = 3; toUpload = new byte[channels * rgb[0].length]; for (int j=0; j<channels; j++) { System.arraycopy(rgb[j], 0, toUpload, 0, rgb[j].length); } } else { int[] p = (int[]) pix; toUpload = new byte[4 * p.length]; for (int j=0; j<p.length; j++) { toUpload[j*4] = little ? (byte) (p[j] & 0xff) : (byte) ((p[j] >> 24) & 0xff); toUpload[j*4 + 1] = little ? (byte) ((p[j] >> 8) & 0xff) : (byte) ((p[j] >> 16) & 0xff); toUpload[j*4 + 2] = little ? (byte) ((p[j] >> 16) & 0xff) : (byte) ((p[j] >> 8) & 0xff); toUpload[j*4 + 3] = little ? (byte) ((p[j] >> 24) & 0xff) : (byte) (p[j] & 0xff); } } } else if (pix instanceof float[]) { float[] f = (float[]) pix; toUpload = new byte[f.length * 4]; for (int j=0; j<f.length; j++) { int k = Float.floatToIntBits(f[j]); toUpload[j*4] = little ? (byte) (k & 0xff) : (byte) ((k >> 24) & 0xff); toUpload[j*4 + 1] = little ? (byte) ((k >> 8) & 0xff) : (byte) ((k >> 16) & 0xff); toUpload[j*4 + 2] = little ? (byte) ((k >> 16) & 0xff) : (byte) ((k >> 8) & 0xff); toUpload[j*4 + 3] = little ? (byte) ((k >> 24) & 0xff) : (byte) (k & 0xff); } } - ul.saveBytes(id, toUpload, i == is.getSize() - 1); + ul.saveBytes(toUpload, i == is.getSize() - 1); } IJ.showStatus("Sending data to server..."); ul.close(); IJ.showStatus("Upload finished."); } catch (Exception e) { IJ.error("Upload failed:\n" + e); e.printStackTrace(); } } }
false
true
private void uploadStack() { try { IJ.showStatus("Starting upload..."); OMEWriter ul = new OMEWriter(); String id = server + "?user=" + user + "&password=" + pass; ImagePlus imp = WindowManager.getCurrentImage(); if (imp == null) { IJ.error("No open images!"); IJ.showStatus(""); return; } ImageStack is = imp.getImageStack(); FileInfo fi = imp.getOriginalFileInfo(); OMEXMLMetadataStore store = new OMEXMLMetadataStore(); // if we opened this stack with the Bio-Formats importer, then the // appropriate OME-XML is in fi.description if (fi != null && fi.description != null && fi.description.endsWith("</OME>")) { store.createRoot(fi.description); } else { store.createRoot(); int pixelType = FormatTools.UINT8; switch (imp.getBitDepth()) { case 16: pixelType = FormatTools.UINT16; break; case 32: pixelType = FormatTools.FLOAT; break; } store.setPixels( new Integer(imp.getWidth()), new Integer(imp.getHeight()), new Integer(imp.getNSlices()), new Integer(imp.getNChannels()), new Integer(imp.getNFrames()), new Integer(pixelType), fi == null ? Boolean.TRUE : new Boolean(!fi.intelByteOrder), "XYCZT", // TODO : figure out a way to calculate the dimension order null, null); String name = fi == null ? imp.getTitle() : fi.fileName; store.setImage(name, null, fi == null ? null : fi.info, null); } if (is.getProcessor(1) instanceof ColorProcessor) { store.setPixels(null, null, null, null, null, new Integer(FormatTools.UINT8), null, null, null, null); } ul.setMetadataStore(store); boolean little = !store.getBigEndian(null).booleanValue(); for (int i=0; i<is.getSize(); i++) { IJ.showStatus("Reading plane " + (i+1) + "/" + is.getSize()); Object pix = is.getProcessor(i + 1).getPixels(); byte[] toUpload = null; if (pix instanceof byte[]) { toUpload = (byte[]) pix; } else if (pix instanceof short[]) { short[] s = (short[]) pix; toUpload = new byte[s.length * 2]; for (int j=0; j<s.length; j++) { toUpload[j*2] = little ? (byte) (s[j] & 0xff) : (byte) ((s[j] >>> 8) & 0xff); toUpload[j*2 + 1] = little ? (byte) ((s[j] >>> 8) & 0xff): (byte) (s[j] & 0xff); } } else if (pix instanceof int[]) { if (is.getProcessor(i+1) instanceof ColorProcessor) { byte[][] rgb = new byte[3][((int[]) pix).length]; ((ColorProcessor) is.getProcessor(i+1)).getRGB(rgb[0], rgb[1], rgb[2]); int channels = store.getSizeC(null).intValue(); if (channels > 3) channels = 3; toUpload = new byte[channels * rgb[0].length]; for (int j=0; j<channels; j++) { System.arraycopy(rgb[j], 0, toUpload, 0, rgb[j].length); } } else { int[] p = (int[]) pix; toUpload = new byte[4 * p.length]; for (int j=0; j<p.length; j++) { toUpload[j*4] = little ? (byte) (p[j] & 0xff) : (byte) ((p[j] >> 24) & 0xff); toUpload[j*4 + 1] = little ? (byte) ((p[j] >> 8) & 0xff) : (byte) ((p[j] >> 16) & 0xff); toUpload[j*4 + 2] = little ? (byte) ((p[j] >> 16) & 0xff) : (byte) ((p[j] >> 8) & 0xff); toUpload[j*4 + 3] = little ? (byte) ((p[j] >> 24) & 0xff) : (byte) (p[j] & 0xff); } } } else if (pix instanceof float[]) { float[] f = (float[]) pix; toUpload = new byte[f.length * 4]; for (int j=0; j<f.length; j++) { int k = Float.floatToIntBits(f[j]); toUpload[j*4] = little ? (byte) (k & 0xff) : (byte) ((k >> 24) & 0xff); toUpload[j*4 + 1] = little ? (byte) ((k >> 8) & 0xff) : (byte) ((k >> 16) & 0xff); toUpload[j*4 + 2] = little ? (byte) ((k >> 16) & 0xff) : (byte) ((k >> 8) & 0xff); toUpload[j*4 + 3] = little ? (byte) ((k >> 24) & 0xff) : (byte) (k & 0xff); } } ul.saveBytes(id, toUpload, i == is.getSize() - 1); } IJ.showStatus("Sending data to server..."); ul.close(); IJ.showStatus("Upload finished."); } catch (Exception e) { IJ.error("Upload failed:\n" + e); e.printStackTrace(); } }
private void uploadStack() { try { IJ.showStatus("Starting upload..."); OMEWriter ul = new OMEWriter(); String id = server + "?user=" + user + "&password=" + pass; ul.setId(id); ImagePlus imp = WindowManager.getCurrentImage(); if (imp == null) { IJ.error("No open images!"); IJ.showStatus(""); return; } ImageStack is = imp.getImageStack(); FileInfo fi = imp.getOriginalFileInfo(); OMEXMLMetadataStore store = new OMEXMLMetadataStore(); // if we opened this stack with the Bio-Formats importer, then the // appropriate OME-XML is in fi.description if (fi != null && fi.description != null && fi.description.endsWith("</OME>")) { store.createRoot(fi.description); } else { store.createRoot(); int pixelType = FormatTools.UINT8; switch (imp.getBitDepth()) { case 16: pixelType = FormatTools.UINT16; break; case 32: pixelType = FormatTools.FLOAT; break; } store.setPixels( new Integer(imp.getWidth()), new Integer(imp.getHeight()), new Integer(imp.getNSlices()), new Integer(imp.getNChannels()), new Integer(imp.getNFrames()), new Integer(pixelType), fi == null ? Boolean.TRUE : new Boolean(!fi.intelByteOrder), "XYCZT", // TODO : figure out a way to calculate the dimension order null, null); String name = fi == null ? imp.getTitle() : fi.fileName; store.setImage(name, null, fi == null ? null : fi.info, null); } if (is.getProcessor(1) instanceof ColorProcessor) { store.setPixels(null, null, null, null, null, new Integer(FormatTools.UINT8), null, null, null, null); } ul.setMetadataStore(store); boolean little = !store.getBigEndian(null).booleanValue(); for (int i=0; i<is.getSize(); i++) { IJ.showStatus("Reading plane " + (i+1) + "/" + is.getSize()); Object pix = is.getProcessor(i + 1).getPixels(); byte[] toUpload = null; if (pix instanceof byte[]) { toUpload = (byte[]) pix; } else if (pix instanceof short[]) { short[] s = (short[]) pix; toUpload = new byte[s.length * 2]; for (int j=0; j<s.length; j++) { toUpload[j*2] = little ? (byte) (s[j] & 0xff) : (byte) ((s[j] >>> 8) & 0xff); toUpload[j*2 + 1] = little ? (byte) ((s[j] >>> 8) & 0xff): (byte) (s[j] & 0xff); } } else if (pix instanceof int[]) { if (is.getProcessor(i+1) instanceof ColorProcessor) { byte[][] rgb = new byte[3][((int[]) pix).length]; ((ColorProcessor) is.getProcessor(i+1)).getRGB(rgb[0], rgb[1], rgb[2]); int channels = store.getSizeC(null).intValue(); if (channels > 3) channels = 3; toUpload = new byte[channels * rgb[0].length]; for (int j=0; j<channels; j++) { System.arraycopy(rgb[j], 0, toUpload, 0, rgb[j].length); } } else { int[] p = (int[]) pix; toUpload = new byte[4 * p.length]; for (int j=0; j<p.length; j++) { toUpload[j*4] = little ? (byte) (p[j] & 0xff) : (byte) ((p[j] >> 24) & 0xff); toUpload[j*4 + 1] = little ? (byte) ((p[j] >> 8) & 0xff) : (byte) ((p[j] >> 16) & 0xff); toUpload[j*4 + 2] = little ? (byte) ((p[j] >> 16) & 0xff) : (byte) ((p[j] >> 8) & 0xff); toUpload[j*4 + 3] = little ? (byte) ((p[j] >> 24) & 0xff) : (byte) (p[j] & 0xff); } } } else if (pix instanceof float[]) { float[] f = (float[]) pix; toUpload = new byte[f.length * 4]; for (int j=0; j<f.length; j++) { int k = Float.floatToIntBits(f[j]); toUpload[j*4] = little ? (byte) (k & 0xff) : (byte) ((k >> 24) & 0xff); toUpload[j*4 + 1] = little ? (byte) ((k >> 8) & 0xff) : (byte) ((k >> 16) & 0xff); toUpload[j*4 + 2] = little ? (byte) ((k >> 16) & 0xff) : (byte) ((k >> 8) & 0xff); toUpload[j*4 + 3] = little ? (byte) ((k >> 24) & 0xff) : (byte) (k & 0xff); } } ul.saveBytes(toUpload, i == is.getSize() - 1); } IJ.showStatus("Sending data to server..."); ul.close(); IJ.showStatus("Upload finished."); } catch (Exception e) { IJ.error("Upload failed:\n" + e); e.printStackTrace(); } }
diff --git a/src/java/com/idega/block/navigation/presentation/NavigationMenu.java b/src/java/com/idega/block/navigation/presentation/NavigationMenu.java index 6ac53b9..620fc0e 100644 --- a/src/java/com/idega/block/navigation/presentation/NavigationMenu.java +++ b/src/java/com/idega/block/navigation/presentation/NavigationMenu.java @@ -1,460 +1,460 @@ package com.idega.block.navigation.presentation; import java.util.Iterator; import java.util.Vector; import com.idega.builder.business.PageTreeNode; import com.idega.builder.handler.HorizontalAlignmentHandler; import com.idega.builder.handler.HorizontalVerticalViewHandler; import com.idega.builder.handler.VerticalAlignmentHandler; import com.idega.core.builder.business.BuilderService; import com.idega.core.builder.data.ICPage; import com.idega.idegaweb.IWBundle; import com.idega.idegaweb.IWResourceBundle; import com.idega.idegaweb.IWStyleManager; import com.idega.presentation.Block; import com.idega.presentation.IWContext; import com.idega.presentation.Image; import com.idega.presentation.Table; import com.idega.presentation.text.Link; import com.idega.util.text.StyleConstants; import com.idega.util.text.TextStyler; /** * Title: * Description: * Copyright: Copyright (c) 2000-2001 idega.is All Rights Reserved * Company: idega *@author <a href="mailto:[email protected]">Aron Birkir</a> & <a href="mailto:[email protected]">Thorhallur Helgason</a> * @version 1.0 */ public class NavigationMenu extends Block { private final static int VERTICAL = HorizontalVerticalViewHandler.VERTICAL, HORIZONTAL = HorizontalVerticalViewHandler.HORIZONTAL; private int viewType = 1; private int rootNode = -1; private IWBundle iwb; private IWResourceBundle iwrb; private final static String IW_BUNDLE_IDENTIFIER = "com.idega.block.navigation"; private int fontSize = 2; private String fontColor = "#000000"; private String bgrColor = "#FFFFFF"; private String highlightFontColor = "#999999"; private String subHighlightFontColor = "#999999"; private String higlightBgrColor = "#FFFFFF"; private String tableBackGroundColor = null; private String width = null; private String height = null; private boolean _styles = true; private boolean _subStyles = true; private String _name; private String _hoverName; private String _subName; private String _subHoverName; private String fontStyle; private String subFontStyle; private String fontHoverColor; private boolean fontHoverUnderline = false; private String subFontHoverColor; private boolean subFontHoverUnderline = false; private Image _iconImage; private Image _iconOverImage; private Image _subIconImage; private Image _subIconOverImage; private Image _spacer; private Image spacer; private Image subNodeImage; private int _widthFromIcon = 5; private int _subWidthFromParent = 10; private int cellPadding = 0; private int cellSpacing = 0; private int _spaceBetween = 0; private int currentPageId = -1; private int parentPageId = -1; private boolean _addParentID = false; private boolean asTab = false; private boolean asButton = false; private boolean asFlipped = false; private boolean withRootAsHome = true; private boolean _showSubPages = false; private boolean _showAllSubPages = false; private String HomeVerticalAlignment = VerticalAlignmentHandler.BOTTOM; private String HomeHorizontalAlignment = HorizontalAlignmentHandler.RIGHT; public NavigationMenu() { this.setSpacing(2); } public void main(IWContext iwc) throws Exception{ setStyles(); BuilderService bs = getBuilderService(iwc); if (rootNode == -1) { rootNode = bs.getRootPageId(); } //String sCurrentPageId = iwc.getParameter(com.idega.builder.business.BuilderLogic.IB_PAGE_PARAMETER); currentPageId = bs.getCurrentPageId(iwc); try { parentPageId = Integer.parseInt(iwc.getParameter("parent_id")); } catch (NumberFormatException e) { parentPageId = -1; } if (parentPageId == -1 && _addParentID) { try { parentPageId = ((Integer) iwc.getSessionAttribute("parent_id")).intValue(); } catch (Exception e) { parentPageId = -1; parentPageId = rootNode; } } if (parentPageId != -1) { iwc.setSessionAttribute("parent_id", new Integer(parentPageId)); } PageTreeNode node = new PageTreeNode(rootNode, iwc); boolean bottom = !HomeVerticalAlignment.equals(VerticalAlignmentHandler.TOP); boolean left = !HomeHorizontalAlignment.equals(HorizontalAlignmentHandler.RIGHT); boolean vertical = viewType == VERTICAL; Vector nodeVector = new Vector(); if (withRootAsHome && ((!bottom && vertical) || (!vertical && left))) { nodeVector.add(node); withRootAsHome = false; } Iterator iter = node.getChildren(); while (iter.hasNext()) nodeVector.add((PageTreeNode) iter.next()); if (withRootAsHome && (bottom || !left)) nodeVector.add(node); int row = 1, col = 1; Table T = new Table(); T.setCellpadding(cellPadding); T.setCellspacing(cellSpacing); if (tableBackGroundColor != null) T.setColor(tableBackGroundColor); if (width != null) T.setWidth(width); if (height != null) T.setHeight(height); Link L = null; spacer = Table.getTransparentCell(iwc); spacer.setWidth(_widthFromIcon); subNodeImage = (Image) spacer.clone(); subNodeImage.setWidth(_subWidthFromParent); subNodeImage.setHeight(2); Image spaceBetween = (Image) spacer.clone(); spaceBetween.setHeight(_spaceBetween); Iterator iterator = nodeVector.iterator(); while (iterator.hasNext()) { PageTreeNode n = (PageTreeNode) iterator.next(); L = getLink(n.getLocalizedNodeName(iwc), n.getNodeID(), rootNode, _addParentID, false); if (_iconImage != null) { Image image = new Image(_iconImage.getMediaURL(iwc)); if (_iconOverImage != null) L.setOnMouseOverImage(image, _iconOverImage); T.add(image, col, row); T.add(spacer, col, row); if (!vertical) col++; } if (!vertical) T.add(L, col++, row); else { - T.mergeCells(col, row, col + 1, row); - T.add(L, col, row++); + //T.mergeCells(col, row, col + 1, row); //merging the cells causes wrong behaviour on the vertical alignment of the link + T.add(L, col+1, row++); if (_showAllSubPages) { if (n.getNodeID() != rootNode) row = addSubLinks(iwc, T, col, row, L, n); } else { if (_showSubPages && (n.getNodeID() == currentPageId || n.getNodeID() == parentPageId) && n.getNodeID() != rootNode) { row = addSubLinks(iwc, T, col, row, L, n); } } } if (_spacer != null && iterator.hasNext()) { if (!vertical) T.add(_spacer, col++, row); else T.add(_spacer, col, row++); } if (_spaceBetween > 0 && vertical) { T.add(spaceBetween, col, row++); } } add(T); } private int addSubLinks(IWContext iwc, Table table, int column, int row, Link link, PageTreeNode node) { Table subTable = new Table(); subTable.setColumns(2); subTable.setCellpadding(0); subTable.setCellspacing(0); int subRow = 1; Iterator i = node.getChildren(); while (i.hasNext()) { PageTreeNode subNode = (PageTreeNode) i.next(); link = getLink(subNode.getLocalizedNodeName(iwc), subNode.getNodeID(), node.getNodeID(), true, true); if (_subWidthFromParent > 0) { subTable.add(subNodeImage, 1, subRow); } if (_subIconImage != null) { Image image = new Image(_subIconImage.getMediaURL(iwc)); if (_subIconOverImage != null) link.setOnMouseOverImage(image, _subIconOverImage); subTable.add(image, 2, subRow); subTable.add(spacer, 2, subRow); } subTable.add(link, 2, subRow++); } table.add(subTable, column, row++); return row; } private Link getLink(String text, int PageId, int parentPageID, boolean addParentID, boolean isSubPage) { Link L = new Link(text); if (_styles) { if (isSubPage && _subStyles) { if (PageId == currentPageId) L.setStyle(_subHoverName); else L.setStyle(_subName); } else { if (PageId == currentPageId) L.setStyle(_hoverName); else L.setStyle(_name); } } else { if (PageId == currentPageId) L.setFontColor(highlightFontColor); else L.setFontColor(fontColor); L.setFontSize(fontSize); } L.setPage(PageId); if (addParentID) L.addParameter("parent_id", parentPageID); if (asButton) { L.setAsImageButton(asButton, true); } else if (asTab) { L.setAsImageTab(asTab, true, asFlipped); } return L; } private void setStyles() { if (_name == null) _name = this.getName(); if (_name == null) { if (getICObjectInstanceID() != -1) _name = "nav_" + Integer.toString(getICObjectInstanceID()); else _name = "nav_" + Double.toString(Math.random()); } _hoverName = "hover_" + _name; _subName = "sub_" + _name; _subHoverName = "subHover_" + _name; if (fontStyle == null) { fontStyle = IWStyleManager.getInstance().getStyle("A"); } if (getParentPage() != null && fontStyle != null) { TextStyler styler = new TextStyler(fontStyle); if (fontHoverUnderline) styler.setStyleValue(StyleConstants.ATTRIBUTE_TEXT_DECORATION, StyleConstants.TEXT_DECORATION_UNDERLINE); if (fontHoverColor != null) styler.setStyleValue(StyleConstants.ATTRIBUTE_COLOR, fontHoverColor); getParentPage().setStyleDefinition("A." + _name, fontStyle); getParentPage().setStyleDefinition("A." + _name + ":hover", styler.getStyleString()); TextStyler styler2 = new TextStyler(fontStyle); if (highlightFontColor != null) styler2.setStyleValue(StyleConstants.ATTRIBUTE_COLOR, highlightFontColor); String style = styler2.getStyleString(); getParentPage().setStyleDefinition("A." + _hoverName, style); if (fontHoverUnderline) styler2.setStyleValue(StyleConstants.ATTRIBUTE_TEXT_DECORATION, StyleConstants.TEXT_DECORATION_UNDERLINE); if (fontHoverColor != null) styler2.setStyleValue(StyleConstants.ATTRIBUTE_COLOR, fontHoverColor); getParentPage().setStyleDefinition("A." + _hoverName + ":hover", styler2.getStyleString()); } else { _styles = false; } if (getParentPage() != null && subFontStyle != null) { TextStyler styler = new TextStyler(subFontStyle); if (subFontHoverUnderline) styler.setStyleValue(StyleConstants.ATTRIBUTE_TEXT_DECORATION, StyleConstants.TEXT_DECORATION_UNDERLINE); if (subFontHoverColor != null) styler.setStyleValue(StyleConstants.ATTRIBUTE_COLOR, subFontHoverColor); getParentPage().setStyleDefinition("A." + _subName, subFontStyle); getParentPage().setStyleDefinition("A." + _subName + ":hover", styler.getStyleString()); TextStyler styler2 = new TextStyler(subFontStyle); if (subHighlightFontColor != null) styler2.setStyleValue(StyleConstants.ATTRIBUTE_COLOR, subHighlightFontColor); String style = styler2.getStyleString(); getParentPage().setStyleDefinition("A." + _subHoverName, style); if (subFontHoverUnderline) styler2.setStyleValue(StyleConstants.ATTRIBUTE_TEXT_DECORATION, StyleConstants.TEXT_DECORATION_UNDERLINE); if (subFontHoverColor != null) styler2.setStyleValue(StyleConstants.ATTRIBUTE_COLOR, subFontHoverColor); getParentPage().setStyleDefinition("A." + _subHoverName + ":hover", styler2.getStyleString()); } else { _subStyles = false; } } public void setViewType(int type) { viewType = type; } public void setHorizontal(boolean horizontal) { if (horizontal) viewType = HORIZONTAL; } public void setVertical(boolean vertical) { if (vertical) viewType = VERTICAL; } public void setRootNode(ICPage page) { rootNode = page.getID(); } public void setRootNode(int rootId) { rootNode = rootId; } public void setFontColor(String color) { fontColor = color; } public void setFontSize(int size) { fontSize = size; } public void setFontStyle(String style) { fontStyle = style; } public void setSubFontStyle(String style) { subFontStyle = style; } public void setFontHoverColor(String color) { fontHoverColor = color; } public void setSubpagesFontHoverColor(String color) { subFontHoverColor = color; } public void setFontHoverUnderline(boolean underline) { fontHoverUnderline = underline; } public void setSubpagesFontHoverUnderline(boolean underline) { subFontHoverUnderline = underline; } public void setBackgroundColor(String color) { bgrColor = color; } public void setTableBackgroundColor(String color) { tableBackGroundColor = color; } public void setHighlightFontColor(String color) { highlightFontColor = color; } public void setSubpagesHighlightFontColor(String color) { subHighlightFontColor = color; } public void setHighligtBackgroundColor(String color) { highlightFontColor = color; } public void setWidth(String width) { this.width = width; } public void setHeight(String height) { this.height = height; } public void setUseRootAsHome(boolean useRootAsHome) { withRootAsHome = useRootAsHome; } public void setPadding(int padding) { cellPadding = padding; } public void setSpacing(int spacing) { cellSpacing = spacing; } public void setSpaceBetween(int spaceBetween) { _spaceBetween = spaceBetween; } public void setHomeHorizontalAlignment(String align) { if (align.equals(HorizontalAlignmentHandler.LEFT) || align.equals(HorizontalAlignmentHandler.RIGHT)) HomeHorizontalAlignment = align; } public void setHomeVerticalAlignment(String align) { if (align.equals(VerticalAlignmentHandler.BOTTOM) || align.equals(VerticalAlignmentHandler.TOP)) HomeVerticalAlignment = align; } public void setAsButtons(boolean asButtons) { asButton = asButtons; } public void setAsTabs(boolean asTabs, boolean Flipped) { asTab = asTabs; asFlipped = Flipped; } public void setIconImage(Image iconImage) { _iconImage = iconImage; } public void setSubpageIconImage(Image iconImage) { _subIconImage = iconImage; } public void setIconOverImage(Image iconOverImage) { _iconOverImage = iconOverImage; } public void setSubpageIconOverImage(Image iconOverImage) { _subIconOverImage = iconOverImage; } public void setWidthFromIcon(int widthFromIcon) { _widthFromIcon = widthFromIcon; } public void setSubPageWidthFromParent(int subWidthFromParent) { _subWidthFromParent = subWidthFromParent; } public void setSpacerImage(Image spacerImage) { _spacer = spacerImage; } public void setAddParentID(boolean addID) { if (addID && (!_showSubPages || !_showAllSubPages)) _addParentID = addID; } public void setShowSubPages(boolean showSubPages) { _showSubPages = showSubPages; setAddParentID(true); } public void setShowAllSubPages(boolean showAllSubPages) { _showAllSubPages = showAllSubPages; setAddParentID(true); } public Object clone() { NavigationMenu obj = null; try { obj = (NavigationMenu) super.clone(); if (this._iconImage != null) { obj._iconImage = (Image) this._iconImage.clone(); } if (this._iconOverImage != null) { obj._iconOverImage = (Image) this._iconOverImage.clone(); } if (this._subIconImage != null) { obj._subIconImage = (Image) this._subIconImage.clone(); } if (this._subIconOverImage != null) { obj._subIconOverImage = (Image) this._subIconOverImage.clone(); } if (this._spacer != null) { obj._spacer = (Image) this._spacer.clone(); } if (this.spacer != null) { obj.spacer = (Image) this.spacer.clone(); } if (this.subNodeImage != null) { obj.subNodeImage = (Image) this.subNodeImage.clone(); } } catch (Exception ex) { ex.printStackTrace(System.err); } return obj; } public String getBundleIdentifier() { return IW_BUNDLE_IDENTIFIER; } }
true
true
public void main(IWContext iwc) throws Exception{ setStyles(); BuilderService bs = getBuilderService(iwc); if (rootNode == -1) { rootNode = bs.getRootPageId(); } //String sCurrentPageId = iwc.getParameter(com.idega.builder.business.BuilderLogic.IB_PAGE_PARAMETER); currentPageId = bs.getCurrentPageId(iwc); try { parentPageId = Integer.parseInt(iwc.getParameter("parent_id")); } catch (NumberFormatException e) { parentPageId = -1; } if (parentPageId == -1 && _addParentID) { try { parentPageId = ((Integer) iwc.getSessionAttribute("parent_id")).intValue(); } catch (Exception e) { parentPageId = -1; parentPageId = rootNode; } } if (parentPageId != -1) { iwc.setSessionAttribute("parent_id", new Integer(parentPageId)); } PageTreeNode node = new PageTreeNode(rootNode, iwc); boolean bottom = !HomeVerticalAlignment.equals(VerticalAlignmentHandler.TOP); boolean left = !HomeHorizontalAlignment.equals(HorizontalAlignmentHandler.RIGHT); boolean vertical = viewType == VERTICAL; Vector nodeVector = new Vector(); if (withRootAsHome && ((!bottom && vertical) || (!vertical && left))) { nodeVector.add(node); withRootAsHome = false; } Iterator iter = node.getChildren(); while (iter.hasNext()) nodeVector.add((PageTreeNode) iter.next()); if (withRootAsHome && (bottom || !left)) nodeVector.add(node); int row = 1, col = 1; Table T = new Table(); T.setCellpadding(cellPadding); T.setCellspacing(cellSpacing); if (tableBackGroundColor != null) T.setColor(tableBackGroundColor); if (width != null) T.setWidth(width); if (height != null) T.setHeight(height); Link L = null; spacer = Table.getTransparentCell(iwc); spacer.setWidth(_widthFromIcon); subNodeImage = (Image) spacer.clone(); subNodeImage.setWidth(_subWidthFromParent); subNodeImage.setHeight(2); Image spaceBetween = (Image) spacer.clone(); spaceBetween.setHeight(_spaceBetween); Iterator iterator = nodeVector.iterator(); while (iterator.hasNext()) { PageTreeNode n = (PageTreeNode) iterator.next(); L = getLink(n.getLocalizedNodeName(iwc), n.getNodeID(), rootNode, _addParentID, false); if (_iconImage != null) { Image image = new Image(_iconImage.getMediaURL(iwc)); if (_iconOverImage != null) L.setOnMouseOverImage(image, _iconOverImage); T.add(image, col, row); T.add(spacer, col, row); if (!vertical) col++; } if (!vertical) T.add(L, col++, row); else { T.mergeCells(col, row, col + 1, row); T.add(L, col, row++); if (_showAllSubPages) { if (n.getNodeID() != rootNode) row = addSubLinks(iwc, T, col, row, L, n); } else { if (_showSubPages && (n.getNodeID() == currentPageId || n.getNodeID() == parentPageId) && n.getNodeID() != rootNode) { row = addSubLinks(iwc, T, col, row, L, n); } } } if (_spacer != null && iterator.hasNext()) { if (!vertical) T.add(_spacer, col++, row); else T.add(_spacer, col, row++); } if (_spaceBetween > 0 && vertical) { T.add(spaceBetween, col, row++); } } add(T); }
public void main(IWContext iwc) throws Exception{ setStyles(); BuilderService bs = getBuilderService(iwc); if (rootNode == -1) { rootNode = bs.getRootPageId(); } //String sCurrentPageId = iwc.getParameter(com.idega.builder.business.BuilderLogic.IB_PAGE_PARAMETER); currentPageId = bs.getCurrentPageId(iwc); try { parentPageId = Integer.parseInt(iwc.getParameter("parent_id")); } catch (NumberFormatException e) { parentPageId = -1; } if (parentPageId == -1 && _addParentID) { try { parentPageId = ((Integer) iwc.getSessionAttribute("parent_id")).intValue(); } catch (Exception e) { parentPageId = -1; parentPageId = rootNode; } } if (parentPageId != -1) { iwc.setSessionAttribute("parent_id", new Integer(parentPageId)); } PageTreeNode node = new PageTreeNode(rootNode, iwc); boolean bottom = !HomeVerticalAlignment.equals(VerticalAlignmentHandler.TOP); boolean left = !HomeHorizontalAlignment.equals(HorizontalAlignmentHandler.RIGHT); boolean vertical = viewType == VERTICAL; Vector nodeVector = new Vector(); if (withRootAsHome && ((!bottom && vertical) || (!vertical && left))) { nodeVector.add(node); withRootAsHome = false; } Iterator iter = node.getChildren(); while (iter.hasNext()) nodeVector.add((PageTreeNode) iter.next()); if (withRootAsHome && (bottom || !left)) nodeVector.add(node); int row = 1, col = 1; Table T = new Table(); T.setCellpadding(cellPadding); T.setCellspacing(cellSpacing); if (tableBackGroundColor != null) T.setColor(tableBackGroundColor); if (width != null) T.setWidth(width); if (height != null) T.setHeight(height); Link L = null; spacer = Table.getTransparentCell(iwc); spacer.setWidth(_widthFromIcon); subNodeImage = (Image) spacer.clone(); subNodeImage.setWidth(_subWidthFromParent); subNodeImage.setHeight(2); Image spaceBetween = (Image) spacer.clone(); spaceBetween.setHeight(_spaceBetween); Iterator iterator = nodeVector.iterator(); while (iterator.hasNext()) { PageTreeNode n = (PageTreeNode) iterator.next(); L = getLink(n.getLocalizedNodeName(iwc), n.getNodeID(), rootNode, _addParentID, false); if (_iconImage != null) { Image image = new Image(_iconImage.getMediaURL(iwc)); if (_iconOverImage != null) L.setOnMouseOverImage(image, _iconOverImage); T.add(image, col, row); T.add(spacer, col, row); if (!vertical) col++; } if (!vertical) T.add(L, col++, row); else { //T.mergeCells(col, row, col + 1, row); //merging the cells causes wrong behaviour on the vertical alignment of the link T.add(L, col+1, row++); if (_showAllSubPages) { if (n.getNodeID() != rootNode) row = addSubLinks(iwc, T, col, row, L, n); } else { if (_showSubPages && (n.getNodeID() == currentPageId || n.getNodeID() == parentPageId) && n.getNodeID() != rootNode) { row = addSubLinks(iwc, T, col, row, L, n); } } } if (_spacer != null && iterator.hasNext()) { if (!vertical) T.add(_spacer, col++, row); else T.add(_spacer, col, row++); } if (_spaceBetween > 0 && vertical) { T.add(spaceBetween, col, row++); } } add(T); }
diff --git a/com.mobilesorcery.sdk.profiles.ui/src/com/mobilesorcery/sdk/profiles/ui/internal/actions/FinalizeForProfileAction.java b/com.mobilesorcery.sdk.profiles.ui/src/com/mobilesorcery/sdk/profiles/ui/internal/actions/FinalizeForProfileAction.java index 336d847b..6792f655 100644 --- a/com.mobilesorcery.sdk.profiles.ui/src/com/mobilesorcery/sdk/profiles/ui/internal/actions/FinalizeForProfileAction.java +++ b/com.mobilesorcery.sdk.profiles.ui/src/com/mobilesorcery/sdk/profiles/ui/internal/actions/FinalizeForProfileAction.java @@ -1,59 +1,61 @@ /* Copyright (C) 2010 Mobile Sorcery AB This program is free software; you can redistribute it and/or modify it under the terms of the Eclipse Public License v1.0. 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 Eclipse Public License v1.0 for more details. You should have received a copy of the Eclipse Public License v1.0 along with this program. It is also available at http://www.eclipse.org/legal/epl-v10.html */ package com.mobilesorcery.sdk.profiles.ui.internal.actions; import org.eclipse.jface.action.Action; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import com.mobilesorcery.sdk.core.FinalizerBuildJob; import com.mobilesorcery.sdk.core.BuildVariant; import com.mobilesorcery.sdk.core.IBuildConfiguration; import com.mobilesorcery.sdk.core.MoSyncProject; import com.mobilesorcery.sdk.finalizer.core.FinalizerParser; import com.mobilesorcery.sdk.profiles.IProfile; import com.mobilesorcery.sdk.profiles.ui.Activator; public class FinalizeForProfileAction extends Action { private ISelection selection; private MoSyncProject project; public FinalizeForProfileAction() { super("Finalize for this profile", Activator.getDefault().getImageRegistry().getDescriptor(Activator.BUILD_FOR_PROFILE_IMAGE)); } public void run() { if (selection instanceof IStructuredSelection) { Object selected = ((IStructuredSelection)selection).getFirstElement(); if (selected instanceof IProfile && project != null) { //FinalizerParser.autoSwitchConfiguration(project); IProfile profile = (IProfile) selected; - IBuildConfiguration cfg = project.getActiveBuildConfiguration(); + // Temporary bug fix + project.setTargetProfile(profile); + /*IBuildConfiguration cfg = project.getActiveBuildConfiguration(); BuildVariant variant = new BuildVariant(profile, cfg == null ? null : cfg.getId(), true); FinalizerBuildJob job = new FinalizerBuildJob(project, variant); - job.schedule(); + job.schedule();*/ } } } public void setCurrentProject(MoSyncProject currentProject) { this.project = currentProject; } public void setSelection(ISelection selection) { this.selection = selection; } }
false
true
public void run() { if (selection instanceof IStructuredSelection) { Object selected = ((IStructuredSelection)selection).getFirstElement(); if (selected instanceof IProfile && project != null) { //FinalizerParser.autoSwitchConfiguration(project); IProfile profile = (IProfile) selected; IBuildConfiguration cfg = project.getActiveBuildConfiguration(); BuildVariant variant = new BuildVariant(profile, cfg == null ? null : cfg.getId(), true); FinalizerBuildJob job = new FinalizerBuildJob(project, variant); job.schedule(); } } }
public void run() { if (selection instanceof IStructuredSelection) { Object selected = ((IStructuredSelection)selection).getFirstElement(); if (selected instanceof IProfile && project != null) { //FinalizerParser.autoSwitchConfiguration(project); IProfile profile = (IProfile) selected; // Temporary bug fix project.setTargetProfile(profile); /*IBuildConfiguration cfg = project.getActiveBuildConfiguration(); BuildVariant variant = new BuildVariant(profile, cfg == null ? null : cfg.getId(), true); FinalizerBuildJob job = new FinalizerBuildJob(project, variant); job.schedule();*/ } } }
diff --git a/gui/src/main/java/fi/smaa/jsmaa/gui/components/DiscreteMeasurementPanel.java b/gui/src/main/java/fi/smaa/jsmaa/gui/components/DiscreteMeasurementPanel.java index 656dc2d..3770d1e 100644 --- a/gui/src/main/java/fi/smaa/jsmaa/gui/components/DiscreteMeasurementPanel.java +++ b/gui/src/main/java/fi/smaa/jsmaa/gui/components/DiscreteMeasurementPanel.java @@ -1,207 +1,211 @@ /* This file is part of JSMAA. JSMAA is distributed from http://smaa.fi/. (c) Tommi Tervonen, 2009-2010. (c) Tommi Tervonen, Gert van Valkenhoef 2011. (c) Tommi Tervonen, Gert van Valkenhoef, Joel Kuiper, Daan Reid 2012. (c) Tommi Tervonen, Gert van Valkenhoef, Joel Kuiper, Daan Reid, Raymond Vermaas 2013. JSMAA 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. JSMAA 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 JSMAA. If not, see <http://www.gnu.org/licenses/>. */ package fi.smaa.jsmaa.gui.components; import java.awt.Color; import java.awt.FlowLayout; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import com.jgoodies.binding.PresentationModel; import fi.smaa.jsmaa.model.DiscreteMeasurement; import fi.smaa.jsmaa.model.Point2D; public class DiscreteMeasurementPanel extends JPanel implements ListSelectionListener { private static final long serialVersionUID = 3084366501203897609L; private JList jlist; private DiscreteMeasurement dm; private JComponent parent; private JButton addButton; private JButton deleteButton; private JTextField valueText; private JTextField probabilityText; private JLabel sumProbabilityLabel; public DiscreteMeasurementPanel(JComponent parent, PresentationModel<DiscreteMeasurement> m) { setLayout(new FlowLayout()); dm = m.getBean(); this.parent = parent; jlist = new JList(dm); jlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); jlist.setSelectedIndex(0); jlist.addListSelectionListener(this); add("Discrete points: ", new JScrollPane(jlist)); valueText = new JTextField(); valueText.addActionListener(new AddButtonListener()); - String strvalue = "" + dm.getElementAt(jlist.getSelectedIndex()).getX(); - valueText.setText(strvalue); + if(dm.getSize() > 0) { + String strvalue = "" + dm.getElementAt(jlist.getSelectedIndex()).getX(); + valueText.setText(strvalue); + } valueText.setHorizontalAlignment(JTextField.CENTER); valueText.setColumns(5); add(new JLabel("P(X=")); add("Value:", valueText); add(new JLabel(") = ")); probabilityText = new JTextField(); probabilityText.addActionListener(new AddButtonListener()); - String strprobability = "" + if(dm.getSize() > 0) { + String strprobability = "" + dm.getElementAt(jlist.getSelectedIndex()).getY(); - probabilityText.setText(strprobability); + probabilityText.setText(strprobability); + } probabilityText.setHorizontalAlignment(JTextField.CENTER); probabilityText.setColumns(5); add("Probability:", probabilityText); addButton = new JButton("+"); addButton.addActionListener(new AddButtonListener()); add(addButton); deleteButton = new JButton("-"); deleteButton.addActionListener(new DeleteButtonListener()); add(deleteButton); add(new JLabel("P(\u2126) = ")); sumProbabilityLabel = new JLabel("1.0"); refreshSummedProbability(); add(sumProbabilityLabel); addFocusListener(new FocusTransferrer(valueText)); setFocusTraversalPolicyProvider(true); setFocusTraversalPolicy(new TwoComponentFocusTraversalPolicy(valueText, probabilityText)); } private void refreshSummedProbability() { double totalprob = dm.getTotalProbability(); if (totalprob != 1.0) { sumProbabilityLabel.setForeground(Color.red); } else { sumProbabilityLabel.setForeground(Color.black); } sumProbabilityLabel.setText(""+totalprob); } @Override public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting() == false) { if (jlist.getSelectedIndex() == -1) { //No selection: disable delete, up, and down buttons. deleteButton.setEnabled(false); valueText.setText(""); probabilityText.setText(""); } else { //Single selection: permit all operations. deleteButton.setEnabled(true); valueText.setText(""+((Point2D) jlist.getSelectedValue()).getX()); probabilityText.setText(""+((Point2D) jlist.getSelectedValue()).getY()); } } } private class DeleteButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { ListSelectionModel lsm = jlist.getSelectionModel(); int selected = lsm.getMinSelectionIndex(); dm.remove(selected); refreshSummedProbability(); int size = dm.size(); if (size == 0) { // List is empty: disable delete, up, and down buttons. deleteButton.setEnabled(false); } else { // Adjust the selection. if (selected == dm.getSize()) { // Removed item in last position. selected--; } jlist.setSelectedIndex(selected); } } } /** A listener shared by the text field and add button. */ private class AddButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { if (valueText.getText().equals("") || probabilityText.getText().equals("")) { Toolkit.getDefaultToolkit().beep(); return; } double val = 0; double prob = 0; try { val = Double.parseDouble(valueText.getText()); prob = Double.parseDouble(probabilityText.getText()); } catch (NumberFormatException ex) { Toolkit.getDefaultToolkit().beep(); return; } if(prob <= 0.0 || prob > 1.0) { JOptionPane.showMessageDialog(parent, "The probability has to be between 0.0 and 1.0!", "Point not added!", JOptionPane.ERROR_MESSAGE); return; } int size = dm.getSize(); Point2D point = new Point2D(val, prob); if(!dm.add(point)) { JOptionPane.showMessageDialog(parent, "The summed probability exeeds 1.0", "Point not added!", JOptionPane.ERROR_MESSAGE); return; } refreshSummedProbability(); jlist.setSelectedIndex(size); } } }
false
true
public DiscreteMeasurementPanel(JComponent parent, PresentationModel<DiscreteMeasurement> m) { setLayout(new FlowLayout()); dm = m.getBean(); this.parent = parent; jlist = new JList(dm); jlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); jlist.setSelectedIndex(0); jlist.addListSelectionListener(this); add("Discrete points: ", new JScrollPane(jlist)); valueText = new JTextField(); valueText.addActionListener(new AddButtonListener()); String strvalue = "" + dm.getElementAt(jlist.getSelectedIndex()).getX(); valueText.setText(strvalue); valueText.setHorizontalAlignment(JTextField.CENTER); valueText.setColumns(5); add(new JLabel("P(X=")); add("Value:", valueText); add(new JLabel(") = ")); probabilityText = new JTextField(); probabilityText.addActionListener(new AddButtonListener()); String strprobability = "" + dm.getElementAt(jlist.getSelectedIndex()).getY(); probabilityText.setText(strprobability); probabilityText.setHorizontalAlignment(JTextField.CENTER); probabilityText.setColumns(5); add("Probability:", probabilityText); addButton = new JButton("+"); addButton.addActionListener(new AddButtonListener()); add(addButton); deleteButton = new JButton("-"); deleteButton.addActionListener(new DeleteButtonListener()); add(deleteButton); add(new JLabel("P(\u2126) = ")); sumProbabilityLabel = new JLabel("1.0"); refreshSummedProbability(); add(sumProbabilityLabel); addFocusListener(new FocusTransferrer(valueText)); setFocusTraversalPolicyProvider(true); setFocusTraversalPolicy(new TwoComponentFocusTraversalPolicy(valueText, probabilityText)); }
public DiscreteMeasurementPanel(JComponent parent, PresentationModel<DiscreteMeasurement> m) { setLayout(new FlowLayout()); dm = m.getBean(); this.parent = parent; jlist = new JList(dm); jlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); jlist.setSelectedIndex(0); jlist.addListSelectionListener(this); add("Discrete points: ", new JScrollPane(jlist)); valueText = new JTextField(); valueText.addActionListener(new AddButtonListener()); if(dm.getSize() > 0) { String strvalue = "" + dm.getElementAt(jlist.getSelectedIndex()).getX(); valueText.setText(strvalue); } valueText.setHorizontalAlignment(JTextField.CENTER); valueText.setColumns(5); add(new JLabel("P(X=")); add("Value:", valueText); add(new JLabel(") = ")); probabilityText = new JTextField(); probabilityText.addActionListener(new AddButtonListener()); if(dm.getSize() > 0) { String strprobability = "" + dm.getElementAt(jlist.getSelectedIndex()).getY(); probabilityText.setText(strprobability); } probabilityText.setHorizontalAlignment(JTextField.CENTER); probabilityText.setColumns(5); add("Probability:", probabilityText); addButton = new JButton("+"); addButton.addActionListener(new AddButtonListener()); add(addButton); deleteButton = new JButton("-"); deleteButton.addActionListener(new DeleteButtonListener()); add(deleteButton); add(new JLabel("P(\u2126) = ")); sumProbabilityLabel = new JLabel("1.0"); refreshSummedProbability(); add(sumProbabilityLabel); addFocusListener(new FocusTransferrer(valueText)); setFocusTraversalPolicyProvider(true); setFocusTraversalPolicy(new TwoComponentFocusTraversalPolicy(valueText, probabilityText)); }
diff --git a/loci/formats/tools/ImageInfo.java b/loci/formats/tools/ImageInfo.java index 428e1b305..b72956572 100644 --- a/loci/formats/tools/ImageInfo.java +++ b/loci/formats/tools/ImageInfo.java @@ -1,638 +1,645 @@ // // ImageInfo.java // /* LOCI Bio-Formats package for reading and converting biological file formats. Copyright (C) 2005-@year@ Melissa Linkert, Curtis Rueden, Chris Allan, Eric Kjellman and Brian Loranger. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library 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 Library General Public License for more details. You should have received a copy of the GNU Library 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.tools; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Arrays; import java.util.Hashtable; import java.util.StringTokenizer; import loci.formats.*; import loci.formats.meta.MetadataRetrieve; import loci.formats.meta.MetadataStore; /** * ImageInfo is a utility class for reading a file * and reporting information about it. * * <dl><dt><b>Source code:</b></dt> * <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/loci/formats/tools/ImageInfo.java">Trac</a>, * <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/loci/formats/tools/ImageInfo.java">SVN</a></dd></dl> */ public final class ImageInfo { // -- Constructor -- private ImageInfo() { } // -- Utility methods -- /** * A utility method for reading a file from the command line, * and displaying the results in a simple display. */ public static boolean testRead(IFormatReader reader, String[] args) throws FormatException, IOException { String id = null; boolean pixels = true; boolean doMeta = true; boolean thumbs = false; boolean minmax = false; boolean merge = false; boolean stitch = false; boolean separate = false; boolean expand = false; boolean omexml = false; boolean normalize = false; boolean fastBlit = false; boolean preload = false; String omexmlVersion = null; int start = 0; int end = Integer.MAX_VALUE; int series = 0; int xCoordinate = 0, yCoordinate = 0, width = 0, height = 0; String swapOrder = null; String map = null; if (args != null) { for (int i=0; i<args.length; i++) { if (args[i].startsWith("-") && args.length > 1) { if (args[i].equals("-nopix")) pixels = false; else if (args[i].equals("-nometa")) doMeta = false; else if (args[i].equals("-thumbs")) thumbs = true; else if (args[i].equals("-minmax")) minmax = true; else if (args[i].equals("-merge")) merge = true; else if (args[i].equals("-stitch")) stitch = true; else if (args[i].equals("-separate")) separate = true; else if (args[i].equals("-expand")) expand = true; else if (args[i].equals("-omexml")) omexml = true; else if (args[i].equals("-normalize")) normalize = true; else if (args[i].equals("-fast")) fastBlit = true; else if (args[i].equals("-debug")) FormatHandler.setDebug(true); else if (args[i].equals("-preload")) preload = true; else if (args[i].equals("-version")) omexmlVersion = args[++i]; else if (args[i].equals("-crop")) { StringTokenizer st = new StringTokenizer(args[++i], ","); xCoordinate = Integer.parseInt(st.nextToken()); yCoordinate = Integer.parseInt(st.nextToken()); width = Integer.parseInt(st.nextToken()); height = Integer.parseInt(st.nextToken()); } else if (args[i].equals("-level")) { try { FormatHandler.setDebugLevel(Integer.parseInt(args[++i])); } catch (NumberFormatException exc) { } } else if (args[i].equals("-range")) { try { start = Integer.parseInt(args[++i]); end = Integer.parseInt(args[++i]); } catch (NumberFormatException exc) { } } else if (args[i].equals("-series")) { try { series = Integer.parseInt(args[++i]); } catch (NumberFormatException exc) { } } else if (args[i].equals("-swap")) { swapOrder = args[++i].toUpperCase(); } else if (args[i].equals("-map")) map = args[++i]; else LogTools.println("Ignoring unknown command flag: " + args[i]); } else { if (id == null) id = args[i]; else LogTools.println("Ignoring unknown argument: " + args[i]); } } } if (FormatHandler.debug) { LogTools.println("Debugging at level " + FormatHandler.debugLevel); } if (id == null) { String className = reader.getClass().getName(); String fmt = reader instanceof ImageReader ? "any" : reader.getFormat(); String[] s = { "To test read a file in " + fmt + " format, run:", " showinf [-nopix] [-nometa] [-thumbs] [-minmax] ", " [-merge] [-stitch] [-separate] [-expand] [-omexml]", " [-normalize] [-fast] [-debug] [-range start end] [-series num]", " [-swap order] [-map id] [-preload] [-version v] file", "", " file: the image file to read", " -nopix: read metadata only, not pixels", " -nometa: output only core metadata", " -thumbs: read thumbnails instead of normal pixels", " -minmax: compute min/max statistics", " -merge: combine separate channels into RGB image", " -stitch: stitch files with similar names", " -separate: split RGB image into separate channels", " -expand: expand indexed color to RGB", " -omexml: populate OME-XML metadata", "-normalize: normalize floating point images*", " -fast: paint RGB images as quickly as possible*", " -debug: turn on debugging output", " -range: specify range of planes to read (inclusive)", " -series: specify which image series to read", " -swap: override the default dimension order", " -map: specify file on disk to which name should be mapped", " -preload: pre-read entire file into a buffer; significantly", " reduces the time required to read the images, but", " requires more memory", " -version: specify which OME-XML version should be generated", " -crop: crop images before displaying; argument is 'x,y,w,h'", "", "* = may result in loss of precision", "" }; for (int i=0; i<s.length; i++) LogTools.println(s[i]); return false; } if (map != null) Location.mapId(id, map); else if (preload) { RandomAccessStream f = new RandomAccessStream(id); byte[] b = new byte[(int) f.length()]; f.read(b); f.close(); RABytes file = new RABytes(b); Location.mapFile(id, file); } if (omexml) { reader.setOriginalMetadataPopulated(true); MetadataStore store = MetadataTools.createOMEXMLMetadata(null, omexmlVersion); if (store != null) reader.setMetadataStore(store); } // check file format if (reader instanceof ImageReader) { // determine format ImageReader ir = (ImageReader) reader; LogTools.print("Checking file format "); LogTools.println("[" + ir.getFormat(id) + "]"); } else { // verify format LogTools.print("Checking " + reader.getFormat() + " format "); LogTools.println(reader.isThisType(id) ? "[yes]" : "[no]"); } LogTools.println("Initializing reader"); if (stitch) { reader = new FileStitcher(reader, true); String pat = FilePattern.findPattern(new Location(id)); if (pat != null) id = pat; } if (expand) reader = new ChannelFiller(reader); if (separate) reader = new ChannelSeparator(reader); if (merge) reader = new ChannelMerger(reader); MinMaxCalculator minMaxCalc = null; if (minmax) reader = minMaxCalc = new MinMaxCalculator(reader); DimensionSwapper dimSwapper = null; if (swapOrder != null) reader = dimSwapper = new DimensionSwapper(reader); StatusEchoer status = new StatusEchoer(); reader.addStatusListener(status); reader.close(); reader.setNormalized(normalize); reader.setMetadataFiltered(true); reader.setMetadataCollected(doMeta); long s1 = System.currentTimeMillis(); reader.setId(id); long e1 = System.currentTimeMillis(); float sec1 = (e1 - s1) / 1000f; LogTools.println("Initialization took " + sec1 + "s"); if (swapOrder != null) dimSwapper.swapDimensions(swapOrder); if (!normalize && reader.getPixelType() == FormatTools.FLOAT) { LogTools.println("Warning: Java does not support " + "display of unnormalized floating point data."); LogTools.println("Please use the '-normalize' option " + "to avoid receiving a cryptic exception."); } // read basic metadata LogTools.println(); LogTools.println("Reading core metadata"); LogTools.println(stitch ? "File pattern = " + id : "Filename = " + reader.getCurrentFile()); if (map != null) LogTools.println("Mapped filename = " + map); String[] used = reader.getUsedFiles(); boolean usedValid = used != null && used.length > 0; if (usedValid) { for (int u=0; u<used.length; u++) { if (used[u] == null) { usedValid = false; break; } } } if (!usedValid) { LogTools.println( "************ Warning: invalid used files list ************"); } if (used == null) { LogTools.println("Used files = null"); } else if (used.length == 0) { LogTools.println("Used files = []"); } else if (used.length > 1) { LogTools.println("Used files:"); for (int u=0; u<used.length; u++) LogTools.println("\t" + used[u]); } else if (!id.equals(used[0])) { LogTools.println("Used files = [" + used[0] + "]"); } int seriesCount = reader.getSeriesCount(); LogTools.println("Series count = " + seriesCount); MetadataStore ms = reader.getMetadataStore(); MetadataRetrieve mr = ms instanceof MetadataRetrieve ? (MetadataRetrieve) ms : null; for (int j=0; j<seriesCount; j++) { reader.setSeries(j); // read basic metadata for series #i int imageCount = reader.getImageCount(); boolean rgb = reader.isRGB(); int sizeX = reader.getSizeX(); int sizeY = reader.getSizeY(); int sizeZ = reader.getSizeZ(); int sizeC = reader.getSizeC(); int sizeT = reader.getSizeT(); int pixelType = reader.getPixelType(); int effSizeC = reader.getEffectiveSizeC(); int rgbChanCount = reader.getRGBChannelCount(); boolean indexed = reader.isIndexed(); byte[][] table8 = reader.get8BitLookupTable(); short[][] table16 = reader.get16BitLookupTable(); int[] cLengths = reader.getChannelDimLengths(); String[] cTypes = reader.getChannelDimTypes(); int thumbSizeX = reader.getThumbSizeX(); int thumbSizeY = reader.getThumbSizeY(); boolean little = reader.isLittleEndian(); String dimOrder = reader.getDimensionOrder(); boolean orderCertain = reader.isOrderCertain(); boolean interleaved = reader.isInterleaved(); boolean metadataComplete = reader.isMetadataComplete(); // output basic metadata for series #i String seriesName = mr == null ? null : mr.getImageName(j); LogTools.println("Series #" + j + (seriesName == null ? "" : " -- " + seriesName) + ":"); LogTools.println("\tImage count = " + imageCount); LogTools.print("\tRGB = " + rgb + " (" + rgbChanCount + ")"); if (merge) LogTools.print(" (merged)"); else if (separate) LogTools.print(" (separated)"); LogTools.println(); if (rgb != (rgbChanCount != 1)) { LogTools.println("\t************ Warning: RGB mismatch ************"); } LogTools.println("\tInterleaved = " + interleaved); LogTools.print("\tIndexed = " + indexed); if (table8 != null) { int len0 = table8.length; int len1 = table8[0].length; LogTools.print(" (8-bit LUT: " + table8.length + " x "); LogTools.print(table8[0] == null ? "null" : "" + table8[0].length); LogTools.print(")"); } if (table16 != null) { int len0 = table16.length; int len1 = table16[0].length; LogTools.print(" (16-bit LUT: " + table16.length + " x "); LogTools.print(table16[0] == null ? "null" : "" + table16[0].length); LogTools.print(")"); } LogTools.println(); if (indexed && table8 == null && table16 == null) { LogTools.println("\t************ Warning: no LUT ************"); } if (table8 != null && table16 != null) { LogTools.println( "\t************ Warning: multiple LUTs ************"); } LogTools.println("\tWidth = " + sizeX); LogTools.println("\tHeight = " + sizeY); LogTools.println("\tSizeZ = " + sizeZ); LogTools.println("\tSizeT = " + sizeT); LogTools.print("\tSizeC = " + sizeC); if (sizeC != effSizeC) { LogTools.print(" (effectively " + effSizeC + ")"); } int cProduct = 1; if (cLengths.length == 1 && FormatTools.CHANNEL.equals(cTypes[0])) { cProduct = cLengths[0]; } else { LogTools.print(" ("); for (int i=0; i<cLengths.length; i++) { if (i > 0) LogTools.print(" x "); LogTools.print(cLengths[i] + " " + cTypes[i]); cProduct *= cLengths[i]; } LogTools.print(")"); } LogTools.println(); if (cLengths.length == 0 || cProduct != sizeC) { LogTools.println( "\t************ Warning: C dimension mismatch ************"); } if (imageCount != sizeZ * effSizeC * sizeT) { LogTools.println("\t************ Warning: ZCT mismatch ************"); } LogTools.println("\tThumbnail size = " + thumbSizeX + " x " + thumbSizeY); LogTools.println("\tEndianness = " + (little ? "intel (little)" : "motorola (big)")); LogTools.println("\tDimension order = " + dimOrder + (orderCertain ? " (certain)" : " (uncertain)")); LogTools.println("\tPixel type = " + FormatTools.getPixelTypeString(pixelType)); LogTools.println("\tMetadata complete = " + metadataComplete); if (doMeta) { LogTools.println("\t-----"); int[] indices; if (imageCount > 6) { int q = imageCount / 2; indices = new int[] { 0, q - 2, q - 1, q, q + 1, q + 2, imageCount - 1 }; } else if (imageCount > 2) { indices = new int[] {0, imageCount / 2, imageCount - 1}; } else if (imageCount > 1) indices = new int[] {0, 1}; else indices = new int[] {0}; int[][] zct = new int[indices.length][]; int[] indices2 = new int[indices.length]; for (int i=0; i<indices.length; i++) { zct[i] = reader.getZCTCoords(indices[i]); indices2[i] = reader.getIndex(zct[i][0], zct[i][1], zct[i][2]); LogTools.print("\tPlane #" + indices[i] + " <=> Z " + zct[i][0] + ", C " + zct[i][1] + ", T " + zct[i][2]); if (indices[i] != indices2[i]) { LogTools.println(" [mismatch: " + indices2[i] + "]"); } else LogTools.println(); } } } reader.setSeries(series); String s = seriesCount > 1 ? (" series #" + series) : ""; int pixelType = reader.getPixelType(); int sizeC = reader.getSizeC(); // get a priori min/max values Double[] preGlobalMin = null, preGlobalMax = null; Double[] preKnownMin = null, preKnownMax = null; Double[] prePlaneMin = null, prePlaneMax = null; boolean preIsMinMaxPop = false; if (minmax) { preGlobalMin = new Double[sizeC]; preGlobalMax = new Double[sizeC]; preKnownMin = new Double[sizeC]; preKnownMax = new Double[sizeC]; for (int c=0; c<sizeC; c++) { preGlobalMin[c] = minMaxCalc.getChannelGlobalMinimum(c); preGlobalMax[c] = minMaxCalc.getChannelGlobalMaximum(c); preKnownMin[c] = minMaxCalc.getChannelKnownMinimum(c); preKnownMax[c] = minMaxCalc.getChannelKnownMaximum(c); } prePlaneMin = minMaxCalc.getPlaneMinimum(0); prePlaneMax = minMaxCalc.getPlaneMaximum(0); preIsMinMaxPop = minMaxCalc.isMinMaxPopulated(); } // read pixels if (pixels) { LogTools.println(); LogTools.print("Reading" + s + " pixel data "); status.setVerbose(false); int num = reader.getImageCount(); if (start < 0) start = 0; if (start >= num) start = num - 1; if (end < 0) end = 0; if (end >= num) end = num - 1; if (end < start) end = start; if (width == 0) width = reader.getSizeX(); if (height == 0) height = reader.getSizeY(); LogTools.print("(" + start + "-" + end + ") "); BufferedImage[] images = new BufferedImage[end - start + 1]; long s2 = System.currentTimeMillis(); boolean mismatch = false; for (int i=start; i<=end; i++) { status.setEchoNext(true); if (!fastBlit) { images[i - start] = thumbs ? reader.openThumbImage(i) : reader.openImage(i, xCoordinate, yCoordinate, width, height); } else { int x = reader.getSizeX(); int y = reader.getSizeY(); byte[] b = thumbs ? reader.openThumbBytes(i) : reader.openBytes(i, xCoordinate, yCoordinate, width, height); Object pix = DataTools.makeDataArray(b, FormatTools.getBytesPerPixel(reader.getPixelType()), reader.getPixelType() == FormatTools.FLOAT, reader.isLittleEndian()); images[i - start] = ImageTools.makeImage(ImageTools.make24Bits(pix, x, y, false, false), x, y); } // check for pixel type mismatch int pixType = ImageTools.getPixelType(images[i - start]); if (pixType != pixelType && pixType != pixelType + 1 && !fastBlit) { if (!mismatch) { LogTools.println(); mismatch = true; } LogTools.println("\tPlane #" + i + ": pixel type mismatch: " + FormatTools.getPixelTypeString(pixType) + "/" + FormatTools.getPixelTypeString(pixelType)); } else { mismatch = false; LogTools.print("."); } } long e2 = System.currentTimeMillis(); if (!mismatch) LogTools.print(" "); LogTools.println("[done]"); // output timing results float sec2 = (e2 - s2) / 1000f; float avg = (float) (e2 - s2) / images.length; LogTools.println(sec2 + "s elapsed (" + avg + "ms per image)"); if (minmax) { // get computed min/max values Double[] globalMin = new Double[sizeC]; Double[] globalMax = new Double[sizeC]; Double[] knownMin = new Double[sizeC]; Double[] knownMax = new Double[sizeC]; for (int c=0; c<sizeC; c++) { globalMin[c] = minMaxCalc.getChannelGlobalMinimum(c); globalMax[c] = minMaxCalc.getChannelGlobalMaximum(c); knownMin[c] = minMaxCalc.getChannelKnownMinimum(c); knownMax[c] = minMaxCalc.getChannelKnownMaximum(c); } Double[] planeMin = minMaxCalc.getPlaneMinimum(0); Double[] planeMax = minMaxCalc.getPlaneMaximum(0); boolean isMinMaxPop = minMaxCalc.isMinMaxPopulated(); // output min/max results LogTools.println(); LogTools.println("Min/max values:"); for (int c=0; c<sizeC; c++) { LogTools.println("\tChannel " + c + ":"); LogTools.println("\t\tGlobal minimum = " + globalMin[c] + " (initially " + preGlobalMin[c] + ")"); LogTools.println("\t\tGlobal maximum = " + globalMax[c] + " (initially " + preGlobalMax[c] + ")"); LogTools.println("\t\tKnown minimum = " + knownMin[c] + " (initially " + preKnownMin[c] + ")"); LogTools.println("\t\tKnown maximum = " + knownMax[c] + " (initially " + preKnownMax[c] + ")"); } LogTools.print("\tFirst plane minimum(s) ="); if (planeMin == null) LogTools.print(" none"); else { for (int subC=0; subC<planeMin.length; subC++) { LogTools.print(" " + planeMin[subC]); } } LogTools.print(" (initially"); if (prePlaneMin == null) LogTools.print(" none"); else { for (int subC=0; subC<prePlaneMin.length; subC++) { LogTools.print(" " + prePlaneMin[subC]); } } LogTools.println(")"); LogTools.print("\tFirst plane maximum(s) ="); if (planeMax == null) LogTools.print(" none"); else { for (int subC=0; subC<planeMax.length; subC++) { LogTools.print(" " + planeMax[subC]); } } LogTools.print(" (initially"); if (prePlaneMax == null) LogTools.print(" none"); else { for (int subC=0; subC<prePlaneMax.length; subC++) { LogTools.print(" " + prePlaneMax[subC]); } } LogTools.println(")"); LogTools.println("\tMin/max populated = " + isMinMaxPop + " (initially " + preIsMinMaxPop + ")"); } // display pixels in image viewer // NB: avoid dependencies on optional loci.formats.gui package ReflectedUniverse r = new ReflectedUniverse(); try { r.exec("import loci.formats.gui.ImageViewer"); r.exec("viewer = new ImageViewer()"); r.setVar("reader", reader); r.setVar("images", images); r.setVar("true", true); r.exec("viewer.setImages(reader, images)"); r.exec("viewer.setVisible(true)"); } catch (ReflectException exc) { throw new FormatException(exc); } } // read format-specific metadata table if (doMeta) { LogTools.println(); LogTools.println("Reading" + s + " metadata"); Hashtable meta = reader.getMetadata(); String[] keys = (String[]) meta.keySet().toArray(new String[0]); Arrays.sort(keys); for (int i=0; i<keys.length; i++) { LogTools.print(keys[i] + ": "); LogTools.println(reader.getMetadataValue(keys[i])); } } // output and validate OME-XML if (omexml) { LogTools.println(); String version = MetadataTools.getOMEXMLVersion(ms); if (version == null) LogTools.println("Generating OME-XML"); else { LogTools.println("Generating OME-XML (schema version " + version + ")"); } if (MetadataTools.isOMEXMLMetadata(ms)) { String xml = MetadataTools.getOMEXML((MetadataRetrieve) ms); LogTools.println(XMLTools.indentXML(xml)); MetadataTools.validateOMEXML(xml); } else { - LogTools.println("OME-Java library not found; no OME-XML available"); + LogTools.println("The metadata could not be converted to OME-XML."); + if (omexmlVersion == null) { + LogTools.println("The OME-Java library is probably not available."); + } + else { + LogTools.println(omexmlVersion + + " is probably not a legal schema version."); + } } } return true; } // -- Main method -- public static void main(String[] args) throws FormatException, IOException { if (!testRead(new ImageReader(), args)) System.exit(1); } // -- Helper classes -- /** Used by testRead to echo status messages to the console. */ private static class StatusEchoer implements StatusListener { private boolean verbose = true; private boolean next = true; public void setVerbose(boolean value) { verbose = value; } public void setEchoNext(boolean value) { next = value; } public void statusUpdated(StatusEvent e) { if (verbose) LogTools.println("\t" + e.getStatusMessage()); else if (next) { LogTools.print(";"); next = false; } } } }
true
true
public static boolean testRead(IFormatReader reader, String[] args) throws FormatException, IOException { String id = null; boolean pixels = true; boolean doMeta = true; boolean thumbs = false; boolean minmax = false; boolean merge = false; boolean stitch = false; boolean separate = false; boolean expand = false; boolean omexml = false; boolean normalize = false; boolean fastBlit = false; boolean preload = false; String omexmlVersion = null; int start = 0; int end = Integer.MAX_VALUE; int series = 0; int xCoordinate = 0, yCoordinate = 0, width = 0, height = 0; String swapOrder = null; String map = null; if (args != null) { for (int i=0; i<args.length; i++) { if (args[i].startsWith("-") && args.length > 1) { if (args[i].equals("-nopix")) pixels = false; else if (args[i].equals("-nometa")) doMeta = false; else if (args[i].equals("-thumbs")) thumbs = true; else if (args[i].equals("-minmax")) minmax = true; else if (args[i].equals("-merge")) merge = true; else if (args[i].equals("-stitch")) stitch = true; else if (args[i].equals("-separate")) separate = true; else if (args[i].equals("-expand")) expand = true; else if (args[i].equals("-omexml")) omexml = true; else if (args[i].equals("-normalize")) normalize = true; else if (args[i].equals("-fast")) fastBlit = true; else if (args[i].equals("-debug")) FormatHandler.setDebug(true); else if (args[i].equals("-preload")) preload = true; else if (args[i].equals("-version")) omexmlVersion = args[++i]; else if (args[i].equals("-crop")) { StringTokenizer st = new StringTokenizer(args[++i], ","); xCoordinate = Integer.parseInt(st.nextToken()); yCoordinate = Integer.parseInt(st.nextToken()); width = Integer.parseInt(st.nextToken()); height = Integer.parseInt(st.nextToken()); } else if (args[i].equals("-level")) { try { FormatHandler.setDebugLevel(Integer.parseInt(args[++i])); } catch (NumberFormatException exc) { } } else if (args[i].equals("-range")) { try { start = Integer.parseInt(args[++i]); end = Integer.parseInt(args[++i]); } catch (NumberFormatException exc) { } } else if (args[i].equals("-series")) { try { series = Integer.parseInt(args[++i]); } catch (NumberFormatException exc) { } } else if (args[i].equals("-swap")) { swapOrder = args[++i].toUpperCase(); } else if (args[i].equals("-map")) map = args[++i]; else LogTools.println("Ignoring unknown command flag: " + args[i]); } else { if (id == null) id = args[i]; else LogTools.println("Ignoring unknown argument: " + args[i]); } } } if (FormatHandler.debug) { LogTools.println("Debugging at level " + FormatHandler.debugLevel); } if (id == null) { String className = reader.getClass().getName(); String fmt = reader instanceof ImageReader ? "any" : reader.getFormat(); String[] s = { "To test read a file in " + fmt + " format, run:", " showinf [-nopix] [-nometa] [-thumbs] [-minmax] ", " [-merge] [-stitch] [-separate] [-expand] [-omexml]", " [-normalize] [-fast] [-debug] [-range start end] [-series num]", " [-swap order] [-map id] [-preload] [-version v] file", "", " file: the image file to read", " -nopix: read metadata only, not pixels", " -nometa: output only core metadata", " -thumbs: read thumbnails instead of normal pixels", " -minmax: compute min/max statistics", " -merge: combine separate channels into RGB image", " -stitch: stitch files with similar names", " -separate: split RGB image into separate channels", " -expand: expand indexed color to RGB", " -omexml: populate OME-XML metadata", "-normalize: normalize floating point images*", " -fast: paint RGB images as quickly as possible*", " -debug: turn on debugging output", " -range: specify range of planes to read (inclusive)", " -series: specify which image series to read", " -swap: override the default dimension order", " -map: specify file on disk to which name should be mapped", " -preload: pre-read entire file into a buffer; significantly", " reduces the time required to read the images, but", " requires more memory", " -version: specify which OME-XML version should be generated", " -crop: crop images before displaying; argument is 'x,y,w,h'", "", "* = may result in loss of precision", "" }; for (int i=0; i<s.length; i++) LogTools.println(s[i]); return false; } if (map != null) Location.mapId(id, map); else if (preload) { RandomAccessStream f = new RandomAccessStream(id); byte[] b = new byte[(int) f.length()]; f.read(b); f.close(); RABytes file = new RABytes(b); Location.mapFile(id, file); } if (omexml) { reader.setOriginalMetadataPopulated(true); MetadataStore store = MetadataTools.createOMEXMLMetadata(null, omexmlVersion); if (store != null) reader.setMetadataStore(store); } // check file format if (reader instanceof ImageReader) { // determine format ImageReader ir = (ImageReader) reader; LogTools.print("Checking file format "); LogTools.println("[" + ir.getFormat(id) + "]"); } else { // verify format LogTools.print("Checking " + reader.getFormat() + " format "); LogTools.println(reader.isThisType(id) ? "[yes]" : "[no]"); } LogTools.println("Initializing reader"); if (stitch) { reader = new FileStitcher(reader, true); String pat = FilePattern.findPattern(new Location(id)); if (pat != null) id = pat; } if (expand) reader = new ChannelFiller(reader); if (separate) reader = new ChannelSeparator(reader); if (merge) reader = new ChannelMerger(reader); MinMaxCalculator minMaxCalc = null; if (minmax) reader = minMaxCalc = new MinMaxCalculator(reader); DimensionSwapper dimSwapper = null; if (swapOrder != null) reader = dimSwapper = new DimensionSwapper(reader); StatusEchoer status = new StatusEchoer(); reader.addStatusListener(status); reader.close(); reader.setNormalized(normalize); reader.setMetadataFiltered(true); reader.setMetadataCollected(doMeta); long s1 = System.currentTimeMillis(); reader.setId(id); long e1 = System.currentTimeMillis(); float sec1 = (e1 - s1) / 1000f; LogTools.println("Initialization took " + sec1 + "s"); if (swapOrder != null) dimSwapper.swapDimensions(swapOrder); if (!normalize && reader.getPixelType() == FormatTools.FLOAT) { LogTools.println("Warning: Java does not support " + "display of unnormalized floating point data."); LogTools.println("Please use the '-normalize' option " + "to avoid receiving a cryptic exception."); } // read basic metadata LogTools.println(); LogTools.println("Reading core metadata"); LogTools.println(stitch ? "File pattern = " + id : "Filename = " + reader.getCurrentFile()); if (map != null) LogTools.println("Mapped filename = " + map); String[] used = reader.getUsedFiles(); boolean usedValid = used != null && used.length > 0; if (usedValid) { for (int u=0; u<used.length; u++) { if (used[u] == null) { usedValid = false; break; } } } if (!usedValid) { LogTools.println( "************ Warning: invalid used files list ************"); } if (used == null) { LogTools.println("Used files = null"); } else if (used.length == 0) { LogTools.println("Used files = []"); } else if (used.length > 1) { LogTools.println("Used files:"); for (int u=0; u<used.length; u++) LogTools.println("\t" + used[u]); } else if (!id.equals(used[0])) { LogTools.println("Used files = [" + used[0] + "]"); } int seriesCount = reader.getSeriesCount(); LogTools.println("Series count = " + seriesCount); MetadataStore ms = reader.getMetadataStore(); MetadataRetrieve mr = ms instanceof MetadataRetrieve ? (MetadataRetrieve) ms : null; for (int j=0; j<seriesCount; j++) { reader.setSeries(j); // read basic metadata for series #i int imageCount = reader.getImageCount(); boolean rgb = reader.isRGB(); int sizeX = reader.getSizeX(); int sizeY = reader.getSizeY(); int sizeZ = reader.getSizeZ(); int sizeC = reader.getSizeC(); int sizeT = reader.getSizeT(); int pixelType = reader.getPixelType(); int effSizeC = reader.getEffectiveSizeC(); int rgbChanCount = reader.getRGBChannelCount(); boolean indexed = reader.isIndexed(); byte[][] table8 = reader.get8BitLookupTable(); short[][] table16 = reader.get16BitLookupTable(); int[] cLengths = reader.getChannelDimLengths(); String[] cTypes = reader.getChannelDimTypes(); int thumbSizeX = reader.getThumbSizeX(); int thumbSizeY = reader.getThumbSizeY(); boolean little = reader.isLittleEndian(); String dimOrder = reader.getDimensionOrder(); boolean orderCertain = reader.isOrderCertain(); boolean interleaved = reader.isInterleaved(); boolean metadataComplete = reader.isMetadataComplete(); // output basic metadata for series #i String seriesName = mr == null ? null : mr.getImageName(j); LogTools.println("Series #" + j + (seriesName == null ? "" : " -- " + seriesName) + ":"); LogTools.println("\tImage count = " + imageCount); LogTools.print("\tRGB = " + rgb + " (" + rgbChanCount + ")"); if (merge) LogTools.print(" (merged)"); else if (separate) LogTools.print(" (separated)"); LogTools.println(); if (rgb != (rgbChanCount != 1)) { LogTools.println("\t************ Warning: RGB mismatch ************"); } LogTools.println("\tInterleaved = " + interleaved); LogTools.print("\tIndexed = " + indexed); if (table8 != null) { int len0 = table8.length; int len1 = table8[0].length; LogTools.print(" (8-bit LUT: " + table8.length + " x "); LogTools.print(table8[0] == null ? "null" : "" + table8[0].length); LogTools.print(")"); } if (table16 != null) { int len0 = table16.length; int len1 = table16[0].length; LogTools.print(" (16-bit LUT: " + table16.length + " x "); LogTools.print(table16[0] == null ? "null" : "" + table16[0].length); LogTools.print(")"); } LogTools.println(); if (indexed && table8 == null && table16 == null) { LogTools.println("\t************ Warning: no LUT ************"); } if (table8 != null && table16 != null) { LogTools.println( "\t************ Warning: multiple LUTs ************"); } LogTools.println("\tWidth = " + sizeX); LogTools.println("\tHeight = " + sizeY); LogTools.println("\tSizeZ = " + sizeZ); LogTools.println("\tSizeT = " + sizeT); LogTools.print("\tSizeC = " + sizeC); if (sizeC != effSizeC) { LogTools.print(" (effectively " + effSizeC + ")"); } int cProduct = 1; if (cLengths.length == 1 && FormatTools.CHANNEL.equals(cTypes[0])) { cProduct = cLengths[0]; } else { LogTools.print(" ("); for (int i=0; i<cLengths.length; i++) { if (i > 0) LogTools.print(" x "); LogTools.print(cLengths[i] + " " + cTypes[i]); cProduct *= cLengths[i]; } LogTools.print(")"); } LogTools.println(); if (cLengths.length == 0 || cProduct != sizeC) { LogTools.println( "\t************ Warning: C dimension mismatch ************"); } if (imageCount != sizeZ * effSizeC * sizeT) { LogTools.println("\t************ Warning: ZCT mismatch ************"); } LogTools.println("\tThumbnail size = " + thumbSizeX + " x " + thumbSizeY); LogTools.println("\tEndianness = " + (little ? "intel (little)" : "motorola (big)")); LogTools.println("\tDimension order = " + dimOrder + (orderCertain ? " (certain)" : " (uncertain)")); LogTools.println("\tPixel type = " + FormatTools.getPixelTypeString(pixelType)); LogTools.println("\tMetadata complete = " + metadataComplete); if (doMeta) { LogTools.println("\t-----"); int[] indices; if (imageCount > 6) { int q = imageCount / 2; indices = new int[] { 0, q - 2, q - 1, q, q + 1, q + 2, imageCount - 1 }; } else if (imageCount > 2) { indices = new int[] {0, imageCount / 2, imageCount - 1}; } else if (imageCount > 1) indices = new int[] {0, 1}; else indices = new int[] {0}; int[][] zct = new int[indices.length][]; int[] indices2 = new int[indices.length]; for (int i=0; i<indices.length; i++) { zct[i] = reader.getZCTCoords(indices[i]); indices2[i] = reader.getIndex(zct[i][0], zct[i][1], zct[i][2]); LogTools.print("\tPlane #" + indices[i] + " <=> Z " + zct[i][0] + ", C " + zct[i][1] + ", T " + zct[i][2]); if (indices[i] != indices2[i]) { LogTools.println(" [mismatch: " + indices2[i] + "]"); } else LogTools.println(); } } } reader.setSeries(series); String s = seriesCount > 1 ? (" series #" + series) : ""; int pixelType = reader.getPixelType(); int sizeC = reader.getSizeC(); // get a priori min/max values Double[] preGlobalMin = null, preGlobalMax = null; Double[] preKnownMin = null, preKnownMax = null; Double[] prePlaneMin = null, prePlaneMax = null; boolean preIsMinMaxPop = false; if (minmax) { preGlobalMin = new Double[sizeC]; preGlobalMax = new Double[sizeC]; preKnownMin = new Double[sizeC]; preKnownMax = new Double[sizeC]; for (int c=0; c<sizeC; c++) { preGlobalMin[c] = minMaxCalc.getChannelGlobalMinimum(c); preGlobalMax[c] = minMaxCalc.getChannelGlobalMaximum(c); preKnownMin[c] = minMaxCalc.getChannelKnownMinimum(c); preKnownMax[c] = minMaxCalc.getChannelKnownMaximum(c); } prePlaneMin = minMaxCalc.getPlaneMinimum(0); prePlaneMax = minMaxCalc.getPlaneMaximum(0); preIsMinMaxPop = minMaxCalc.isMinMaxPopulated(); } // read pixels if (pixels) { LogTools.println(); LogTools.print("Reading" + s + " pixel data "); status.setVerbose(false); int num = reader.getImageCount(); if (start < 0) start = 0; if (start >= num) start = num - 1; if (end < 0) end = 0; if (end >= num) end = num - 1; if (end < start) end = start; if (width == 0) width = reader.getSizeX(); if (height == 0) height = reader.getSizeY(); LogTools.print("(" + start + "-" + end + ") "); BufferedImage[] images = new BufferedImage[end - start + 1]; long s2 = System.currentTimeMillis(); boolean mismatch = false; for (int i=start; i<=end; i++) { status.setEchoNext(true); if (!fastBlit) { images[i - start] = thumbs ? reader.openThumbImage(i) : reader.openImage(i, xCoordinate, yCoordinate, width, height); } else { int x = reader.getSizeX(); int y = reader.getSizeY(); byte[] b = thumbs ? reader.openThumbBytes(i) : reader.openBytes(i, xCoordinate, yCoordinate, width, height); Object pix = DataTools.makeDataArray(b, FormatTools.getBytesPerPixel(reader.getPixelType()), reader.getPixelType() == FormatTools.FLOAT, reader.isLittleEndian()); images[i - start] = ImageTools.makeImage(ImageTools.make24Bits(pix, x, y, false, false), x, y); } // check for pixel type mismatch int pixType = ImageTools.getPixelType(images[i - start]); if (pixType != pixelType && pixType != pixelType + 1 && !fastBlit) { if (!mismatch) { LogTools.println(); mismatch = true; } LogTools.println("\tPlane #" + i + ": pixel type mismatch: " + FormatTools.getPixelTypeString(pixType) + "/" + FormatTools.getPixelTypeString(pixelType)); } else { mismatch = false; LogTools.print("."); } } long e2 = System.currentTimeMillis(); if (!mismatch) LogTools.print(" "); LogTools.println("[done]"); // output timing results float sec2 = (e2 - s2) / 1000f; float avg = (float) (e2 - s2) / images.length; LogTools.println(sec2 + "s elapsed (" + avg + "ms per image)"); if (minmax) { // get computed min/max values Double[] globalMin = new Double[sizeC]; Double[] globalMax = new Double[sizeC]; Double[] knownMin = new Double[sizeC]; Double[] knownMax = new Double[sizeC]; for (int c=0; c<sizeC; c++) { globalMin[c] = minMaxCalc.getChannelGlobalMinimum(c); globalMax[c] = minMaxCalc.getChannelGlobalMaximum(c); knownMin[c] = minMaxCalc.getChannelKnownMinimum(c); knownMax[c] = minMaxCalc.getChannelKnownMaximum(c); } Double[] planeMin = minMaxCalc.getPlaneMinimum(0); Double[] planeMax = minMaxCalc.getPlaneMaximum(0); boolean isMinMaxPop = minMaxCalc.isMinMaxPopulated(); // output min/max results LogTools.println(); LogTools.println("Min/max values:"); for (int c=0; c<sizeC; c++) { LogTools.println("\tChannel " + c + ":"); LogTools.println("\t\tGlobal minimum = " + globalMin[c] + " (initially " + preGlobalMin[c] + ")"); LogTools.println("\t\tGlobal maximum = " + globalMax[c] + " (initially " + preGlobalMax[c] + ")"); LogTools.println("\t\tKnown minimum = " + knownMin[c] + " (initially " + preKnownMin[c] + ")"); LogTools.println("\t\tKnown maximum = " + knownMax[c] + " (initially " + preKnownMax[c] + ")"); } LogTools.print("\tFirst plane minimum(s) ="); if (planeMin == null) LogTools.print(" none"); else { for (int subC=0; subC<planeMin.length; subC++) { LogTools.print(" " + planeMin[subC]); } } LogTools.print(" (initially"); if (prePlaneMin == null) LogTools.print(" none"); else { for (int subC=0; subC<prePlaneMin.length; subC++) { LogTools.print(" " + prePlaneMin[subC]); } } LogTools.println(")"); LogTools.print("\tFirst plane maximum(s) ="); if (planeMax == null) LogTools.print(" none"); else { for (int subC=0; subC<planeMax.length; subC++) { LogTools.print(" " + planeMax[subC]); } } LogTools.print(" (initially"); if (prePlaneMax == null) LogTools.print(" none"); else { for (int subC=0; subC<prePlaneMax.length; subC++) { LogTools.print(" " + prePlaneMax[subC]); } } LogTools.println(")"); LogTools.println("\tMin/max populated = " + isMinMaxPop + " (initially " + preIsMinMaxPop + ")"); } // display pixels in image viewer // NB: avoid dependencies on optional loci.formats.gui package ReflectedUniverse r = new ReflectedUniverse(); try { r.exec("import loci.formats.gui.ImageViewer"); r.exec("viewer = new ImageViewer()"); r.setVar("reader", reader); r.setVar("images", images); r.setVar("true", true); r.exec("viewer.setImages(reader, images)"); r.exec("viewer.setVisible(true)"); } catch (ReflectException exc) { throw new FormatException(exc); } } // read format-specific metadata table if (doMeta) { LogTools.println(); LogTools.println("Reading" + s + " metadata"); Hashtable meta = reader.getMetadata(); String[] keys = (String[]) meta.keySet().toArray(new String[0]); Arrays.sort(keys); for (int i=0; i<keys.length; i++) { LogTools.print(keys[i] + ": "); LogTools.println(reader.getMetadataValue(keys[i])); } } // output and validate OME-XML if (omexml) { LogTools.println(); String version = MetadataTools.getOMEXMLVersion(ms); if (version == null) LogTools.println("Generating OME-XML"); else { LogTools.println("Generating OME-XML (schema version " + version + ")"); } if (MetadataTools.isOMEXMLMetadata(ms)) { String xml = MetadataTools.getOMEXML((MetadataRetrieve) ms); LogTools.println(XMLTools.indentXML(xml)); MetadataTools.validateOMEXML(xml); } else { LogTools.println("OME-Java library not found; no OME-XML available"); } } return true; }
public static boolean testRead(IFormatReader reader, String[] args) throws FormatException, IOException { String id = null; boolean pixels = true; boolean doMeta = true; boolean thumbs = false; boolean minmax = false; boolean merge = false; boolean stitch = false; boolean separate = false; boolean expand = false; boolean omexml = false; boolean normalize = false; boolean fastBlit = false; boolean preload = false; String omexmlVersion = null; int start = 0; int end = Integer.MAX_VALUE; int series = 0; int xCoordinate = 0, yCoordinate = 0, width = 0, height = 0; String swapOrder = null; String map = null; if (args != null) { for (int i=0; i<args.length; i++) { if (args[i].startsWith("-") && args.length > 1) { if (args[i].equals("-nopix")) pixels = false; else if (args[i].equals("-nometa")) doMeta = false; else if (args[i].equals("-thumbs")) thumbs = true; else if (args[i].equals("-minmax")) minmax = true; else if (args[i].equals("-merge")) merge = true; else if (args[i].equals("-stitch")) stitch = true; else if (args[i].equals("-separate")) separate = true; else if (args[i].equals("-expand")) expand = true; else if (args[i].equals("-omexml")) omexml = true; else if (args[i].equals("-normalize")) normalize = true; else if (args[i].equals("-fast")) fastBlit = true; else if (args[i].equals("-debug")) FormatHandler.setDebug(true); else if (args[i].equals("-preload")) preload = true; else if (args[i].equals("-version")) omexmlVersion = args[++i]; else if (args[i].equals("-crop")) { StringTokenizer st = new StringTokenizer(args[++i], ","); xCoordinate = Integer.parseInt(st.nextToken()); yCoordinate = Integer.parseInt(st.nextToken()); width = Integer.parseInt(st.nextToken()); height = Integer.parseInt(st.nextToken()); } else if (args[i].equals("-level")) { try { FormatHandler.setDebugLevel(Integer.parseInt(args[++i])); } catch (NumberFormatException exc) { } } else if (args[i].equals("-range")) { try { start = Integer.parseInt(args[++i]); end = Integer.parseInt(args[++i]); } catch (NumberFormatException exc) { } } else if (args[i].equals("-series")) { try { series = Integer.parseInt(args[++i]); } catch (NumberFormatException exc) { } } else if (args[i].equals("-swap")) { swapOrder = args[++i].toUpperCase(); } else if (args[i].equals("-map")) map = args[++i]; else LogTools.println("Ignoring unknown command flag: " + args[i]); } else { if (id == null) id = args[i]; else LogTools.println("Ignoring unknown argument: " + args[i]); } } } if (FormatHandler.debug) { LogTools.println("Debugging at level " + FormatHandler.debugLevel); } if (id == null) { String className = reader.getClass().getName(); String fmt = reader instanceof ImageReader ? "any" : reader.getFormat(); String[] s = { "To test read a file in " + fmt + " format, run:", " showinf [-nopix] [-nometa] [-thumbs] [-minmax] ", " [-merge] [-stitch] [-separate] [-expand] [-omexml]", " [-normalize] [-fast] [-debug] [-range start end] [-series num]", " [-swap order] [-map id] [-preload] [-version v] file", "", " file: the image file to read", " -nopix: read metadata only, not pixels", " -nometa: output only core metadata", " -thumbs: read thumbnails instead of normal pixels", " -minmax: compute min/max statistics", " -merge: combine separate channels into RGB image", " -stitch: stitch files with similar names", " -separate: split RGB image into separate channels", " -expand: expand indexed color to RGB", " -omexml: populate OME-XML metadata", "-normalize: normalize floating point images*", " -fast: paint RGB images as quickly as possible*", " -debug: turn on debugging output", " -range: specify range of planes to read (inclusive)", " -series: specify which image series to read", " -swap: override the default dimension order", " -map: specify file on disk to which name should be mapped", " -preload: pre-read entire file into a buffer; significantly", " reduces the time required to read the images, but", " requires more memory", " -version: specify which OME-XML version should be generated", " -crop: crop images before displaying; argument is 'x,y,w,h'", "", "* = may result in loss of precision", "" }; for (int i=0; i<s.length; i++) LogTools.println(s[i]); return false; } if (map != null) Location.mapId(id, map); else if (preload) { RandomAccessStream f = new RandomAccessStream(id); byte[] b = new byte[(int) f.length()]; f.read(b); f.close(); RABytes file = new RABytes(b); Location.mapFile(id, file); } if (omexml) { reader.setOriginalMetadataPopulated(true); MetadataStore store = MetadataTools.createOMEXMLMetadata(null, omexmlVersion); if (store != null) reader.setMetadataStore(store); } // check file format if (reader instanceof ImageReader) { // determine format ImageReader ir = (ImageReader) reader; LogTools.print("Checking file format "); LogTools.println("[" + ir.getFormat(id) + "]"); } else { // verify format LogTools.print("Checking " + reader.getFormat() + " format "); LogTools.println(reader.isThisType(id) ? "[yes]" : "[no]"); } LogTools.println("Initializing reader"); if (stitch) { reader = new FileStitcher(reader, true); String pat = FilePattern.findPattern(new Location(id)); if (pat != null) id = pat; } if (expand) reader = new ChannelFiller(reader); if (separate) reader = new ChannelSeparator(reader); if (merge) reader = new ChannelMerger(reader); MinMaxCalculator minMaxCalc = null; if (minmax) reader = minMaxCalc = new MinMaxCalculator(reader); DimensionSwapper dimSwapper = null; if (swapOrder != null) reader = dimSwapper = new DimensionSwapper(reader); StatusEchoer status = new StatusEchoer(); reader.addStatusListener(status); reader.close(); reader.setNormalized(normalize); reader.setMetadataFiltered(true); reader.setMetadataCollected(doMeta); long s1 = System.currentTimeMillis(); reader.setId(id); long e1 = System.currentTimeMillis(); float sec1 = (e1 - s1) / 1000f; LogTools.println("Initialization took " + sec1 + "s"); if (swapOrder != null) dimSwapper.swapDimensions(swapOrder); if (!normalize && reader.getPixelType() == FormatTools.FLOAT) { LogTools.println("Warning: Java does not support " + "display of unnormalized floating point data."); LogTools.println("Please use the '-normalize' option " + "to avoid receiving a cryptic exception."); } // read basic metadata LogTools.println(); LogTools.println("Reading core metadata"); LogTools.println(stitch ? "File pattern = " + id : "Filename = " + reader.getCurrentFile()); if (map != null) LogTools.println("Mapped filename = " + map); String[] used = reader.getUsedFiles(); boolean usedValid = used != null && used.length > 0; if (usedValid) { for (int u=0; u<used.length; u++) { if (used[u] == null) { usedValid = false; break; } } } if (!usedValid) { LogTools.println( "************ Warning: invalid used files list ************"); } if (used == null) { LogTools.println("Used files = null"); } else if (used.length == 0) { LogTools.println("Used files = []"); } else if (used.length > 1) { LogTools.println("Used files:"); for (int u=0; u<used.length; u++) LogTools.println("\t" + used[u]); } else if (!id.equals(used[0])) { LogTools.println("Used files = [" + used[0] + "]"); } int seriesCount = reader.getSeriesCount(); LogTools.println("Series count = " + seriesCount); MetadataStore ms = reader.getMetadataStore(); MetadataRetrieve mr = ms instanceof MetadataRetrieve ? (MetadataRetrieve) ms : null; for (int j=0; j<seriesCount; j++) { reader.setSeries(j); // read basic metadata for series #i int imageCount = reader.getImageCount(); boolean rgb = reader.isRGB(); int sizeX = reader.getSizeX(); int sizeY = reader.getSizeY(); int sizeZ = reader.getSizeZ(); int sizeC = reader.getSizeC(); int sizeT = reader.getSizeT(); int pixelType = reader.getPixelType(); int effSizeC = reader.getEffectiveSizeC(); int rgbChanCount = reader.getRGBChannelCount(); boolean indexed = reader.isIndexed(); byte[][] table8 = reader.get8BitLookupTable(); short[][] table16 = reader.get16BitLookupTable(); int[] cLengths = reader.getChannelDimLengths(); String[] cTypes = reader.getChannelDimTypes(); int thumbSizeX = reader.getThumbSizeX(); int thumbSizeY = reader.getThumbSizeY(); boolean little = reader.isLittleEndian(); String dimOrder = reader.getDimensionOrder(); boolean orderCertain = reader.isOrderCertain(); boolean interleaved = reader.isInterleaved(); boolean metadataComplete = reader.isMetadataComplete(); // output basic metadata for series #i String seriesName = mr == null ? null : mr.getImageName(j); LogTools.println("Series #" + j + (seriesName == null ? "" : " -- " + seriesName) + ":"); LogTools.println("\tImage count = " + imageCount); LogTools.print("\tRGB = " + rgb + " (" + rgbChanCount + ")"); if (merge) LogTools.print(" (merged)"); else if (separate) LogTools.print(" (separated)"); LogTools.println(); if (rgb != (rgbChanCount != 1)) { LogTools.println("\t************ Warning: RGB mismatch ************"); } LogTools.println("\tInterleaved = " + interleaved); LogTools.print("\tIndexed = " + indexed); if (table8 != null) { int len0 = table8.length; int len1 = table8[0].length; LogTools.print(" (8-bit LUT: " + table8.length + " x "); LogTools.print(table8[0] == null ? "null" : "" + table8[0].length); LogTools.print(")"); } if (table16 != null) { int len0 = table16.length; int len1 = table16[0].length; LogTools.print(" (16-bit LUT: " + table16.length + " x "); LogTools.print(table16[0] == null ? "null" : "" + table16[0].length); LogTools.print(")"); } LogTools.println(); if (indexed && table8 == null && table16 == null) { LogTools.println("\t************ Warning: no LUT ************"); } if (table8 != null && table16 != null) { LogTools.println( "\t************ Warning: multiple LUTs ************"); } LogTools.println("\tWidth = " + sizeX); LogTools.println("\tHeight = " + sizeY); LogTools.println("\tSizeZ = " + sizeZ); LogTools.println("\tSizeT = " + sizeT); LogTools.print("\tSizeC = " + sizeC); if (sizeC != effSizeC) { LogTools.print(" (effectively " + effSizeC + ")"); } int cProduct = 1; if (cLengths.length == 1 && FormatTools.CHANNEL.equals(cTypes[0])) { cProduct = cLengths[0]; } else { LogTools.print(" ("); for (int i=0; i<cLengths.length; i++) { if (i > 0) LogTools.print(" x "); LogTools.print(cLengths[i] + " " + cTypes[i]); cProduct *= cLengths[i]; } LogTools.print(")"); } LogTools.println(); if (cLengths.length == 0 || cProduct != sizeC) { LogTools.println( "\t************ Warning: C dimension mismatch ************"); } if (imageCount != sizeZ * effSizeC * sizeT) { LogTools.println("\t************ Warning: ZCT mismatch ************"); } LogTools.println("\tThumbnail size = " + thumbSizeX + " x " + thumbSizeY); LogTools.println("\tEndianness = " + (little ? "intel (little)" : "motorola (big)")); LogTools.println("\tDimension order = " + dimOrder + (orderCertain ? " (certain)" : " (uncertain)")); LogTools.println("\tPixel type = " + FormatTools.getPixelTypeString(pixelType)); LogTools.println("\tMetadata complete = " + metadataComplete); if (doMeta) { LogTools.println("\t-----"); int[] indices; if (imageCount > 6) { int q = imageCount / 2; indices = new int[] { 0, q - 2, q - 1, q, q + 1, q + 2, imageCount - 1 }; } else if (imageCount > 2) { indices = new int[] {0, imageCount / 2, imageCount - 1}; } else if (imageCount > 1) indices = new int[] {0, 1}; else indices = new int[] {0}; int[][] zct = new int[indices.length][]; int[] indices2 = new int[indices.length]; for (int i=0; i<indices.length; i++) { zct[i] = reader.getZCTCoords(indices[i]); indices2[i] = reader.getIndex(zct[i][0], zct[i][1], zct[i][2]); LogTools.print("\tPlane #" + indices[i] + " <=> Z " + zct[i][0] + ", C " + zct[i][1] + ", T " + zct[i][2]); if (indices[i] != indices2[i]) { LogTools.println(" [mismatch: " + indices2[i] + "]"); } else LogTools.println(); } } } reader.setSeries(series); String s = seriesCount > 1 ? (" series #" + series) : ""; int pixelType = reader.getPixelType(); int sizeC = reader.getSizeC(); // get a priori min/max values Double[] preGlobalMin = null, preGlobalMax = null; Double[] preKnownMin = null, preKnownMax = null; Double[] prePlaneMin = null, prePlaneMax = null; boolean preIsMinMaxPop = false; if (minmax) { preGlobalMin = new Double[sizeC]; preGlobalMax = new Double[sizeC]; preKnownMin = new Double[sizeC]; preKnownMax = new Double[sizeC]; for (int c=0; c<sizeC; c++) { preGlobalMin[c] = minMaxCalc.getChannelGlobalMinimum(c); preGlobalMax[c] = minMaxCalc.getChannelGlobalMaximum(c); preKnownMin[c] = minMaxCalc.getChannelKnownMinimum(c); preKnownMax[c] = minMaxCalc.getChannelKnownMaximum(c); } prePlaneMin = minMaxCalc.getPlaneMinimum(0); prePlaneMax = minMaxCalc.getPlaneMaximum(0); preIsMinMaxPop = minMaxCalc.isMinMaxPopulated(); } // read pixels if (pixels) { LogTools.println(); LogTools.print("Reading" + s + " pixel data "); status.setVerbose(false); int num = reader.getImageCount(); if (start < 0) start = 0; if (start >= num) start = num - 1; if (end < 0) end = 0; if (end >= num) end = num - 1; if (end < start) end = start; if (width == 0) width = reader.getSizeX(); if (height == 0) height = reader.getSizeY(); LogTools.print("(" + start + "-" + end + ") "); BufferedImage[] images = new BufferedImage[end - start + 1]; long s2 = System.currentTimeMillis(); boolean mismatch = false; for (int i=start; i<=end; i++) { status.setEchoNext(true); if (!fastBlit) { images[i - start] = thumbs ? reader.openThumbImage(i) : reader.openImage(i, xCoordinate, yCoordinate, width, height); } else { int x = reader.getSizeX(); int y = reader.getSizeY(); byte[] b = thumbs ? reader.openThumbBytes(i) : reader.openBytes(i, xCoordinate, yCoordinate, width, height); Object pix = DataTools.makeDataArray(b, FormatTools.getBytesPerPixel(reader.getPixelType()), reader.getPixelType() == FormatTools.FLOAT, reader.isLittleEndian()); images[i - start] = ImageTools.makeImage(ImageTools.make24Bits(pix, x, y, false, false), x, y); } // check for pixel type mismatch int pixType = ImageTools.getPixelType(images[i - start]); if (pixType != pixelType && pixType != pixelType + 1 && !fastBlit) { if (!mismatch) { LogTools.println(); mismatch = true; } LogTools.println("\tPlane #" + i + ": pixel type mismatch: " + FormatTools.getPixelTypeString(pixType) + "/" + FormatTools.getPixelTypeString(pixelType)); } else { mismatch = false; LogTools.print("."); } } long e2 = System.currentTimeMillis(); if (!mismatch) LogTools.print(" "); LogTools.println("[done]"); // output timing results float sec2 = (e2 - s2) / 1000f; float avg = (float) (e2 - s2) / images.length; LogTools.println(sec2 + "s elapsed (" + avg + "ms per image)"); if (minmax) { // get computed min/max values Double[] globalMin = new Double[sizeC]; Double[] globalMax = new Double[sizeC]; Double[] knownMin = new Double[sizeC]; Double[] knownMax = new Double[sizeC]; for (int c=0; c<sizeC; c++) { globalMin[c] = minMaxCalc.getChannelGlobalMinimum(c); globalMax[c] = minMaxCalc.getChannelGlobalMaximum(c); knownMin[c] = minMaxCalc.getChannelKnownMinimum(c); knownMax[c] = minMaxCalc.getChannelKnownMaximum(c); } Double[] planeMin = minMaxCalc.getPlaneMinimum(0); Double[] planeMax = minMaxCalc.getPlaneMaximum(0); boolean isMinMaxPop = minMaxCalc.isMinMaxPopulated(); // output min/max results LogTools.println(); LogTools.println("Min/max values:"); for (int c=0; c<sizeC; c++) { LogTools.println("\tChannel " + c + ":"); LogTools.println("\t\tGlobal minimum = " + globalMin[c] + " (initially " + preGlobalMin[c] + ")"); LogTools.println("\t\tGlobal maximum = " + globalMax[c] + " (initially " + preGlobalMax[c] + ")"); LogTools.println("\t\tKnown minimum = " + knownMin[c] + " (initially " + preKnownMin[c] + ")"); LogTools.println("\t\tKnown maximum = " + knownMax[c] + " (initially " + preKnownMax[c] + ")"); } LogTools.print("\tFirst plane minimum(s) ="); if (planeMin == null) LogTools.print(" none"); else { for (int subC=0; subC<planeMin.length; subC++) { LogTools.print(" " + planeMin[subC]); } } LogTools.print(" (initially"); if (prePlaneMin == null) LogTools.print(" none"); else { for (int subC=0; subC<prePlaneMin.length; subC++) { LogTools.print(" " + prePlaneMin[subC]); } } LogTools.println(")"); LogTools.print("\tFirst plane maximum(s) ="); if (planeMax == null) LogTools.print(" none"); else { for (int subC=0; subC<planeMax.length; subC++) { LogTools.print(" " + planeMax[subC]); } } LogTools.print(" (initially"); if (prePlaneMax == null) LogTools.print(" none"); else { for (int subC=0; subC<prePlaneMax.length; subC++) { LogTools.print(" " + prePlaneMax[subC]); } } LogTools.println(")"); LogTools.println("\tMin/max populated = " + isMinMaxPop + " (initially " + preIsMinMaxPop + ")"); } // display pixels in image viewer // NB: avoid dependencies on optional loci.formats.gui package ReflectedUniverse r = new ReflectedUniverse(); try { r.exec("import loci.formats.gui.ImageViewer"); r.exec("viewer = new ImageViewer()"); r.setVar("reader", reader); r.setVar("images", images); r.setVar("true", true); r.exec("viewer.setImages(reader, images)"); r.exec("viewer.setVisible(true)"); } catch (ReflectException exc) { throw new FormatException(exc); } } // read format-specific metadata table if (doMeta) { LogTools.println(); LogTools.println("Reading" + s + " metadata"); Hashtable meta = reader.getMetadata(); String[] keys = (String[]) meta.keySet().toArray(new String[0]); Arrays.sort(keys); for (int i=0; i<keys.length; i++) { LogTools.print(keys[i] + ": "); LogTools.println(reader.getMetadataValue(keys[i])); } } // output and validate OME-XML if (omexml) { LogTools.println(); String version = MetadataTools.getOMEXMLVersion(ms); if (version == null) LogTools.println("Generating OME-XML"); else { LogTools.println("Generating OME-XML (schema version " + version + ")"); } if (MetadataTools.isOMEXMLMetadata(ms)) { String xml = MetadataTools.getOMEXML((MetadataRetrieve) ms); LogTools.println(XMLTools.indentXML(xml)); MetadataTools.validateOMEXML(xml); } else { LogTools.println("The metadata could not be converted to OME-XML."); if (omexmlVersion == null) { LogTools.println("The OME-Java library is probably not available."); } else { LogTools.println(omexmlVersion + " is probably not a legal schema version."); } } } return true; }
diff --git a/src/com/github/Shot.java b/src/com/github/Shot.java index ce18498..56f0afc 100644 --- a/src/com/github/Shot.java +++ b/src/com/github/Shot.java @@ -1,74 +1,74 @@ package com.github; import java.util.ArrayList; import java.util.List; import org.bukkit.Location; public class Shot { private final Location from; public Shot(Location from) { this.from = from; } // TODO - Checking for obstacles public List<Hit> shoot(ShotData data, List<HitBox> hitBoxes) { List<Hit> hits = new ArrayList<Hit>(); for (HitBox hitBox : hitBoxes) { hitBox.update(); - float fromYaw = 360 % from.getYaw(); - float fromPitch = 360 % from.getPitch(); + float fromYaw = from.getYaw() % 360; + float fromPitch = from.getPitch() % 360; // making sure the center location is within range if (hitBox.getCenter().distanceSquared(from) > Math.pow(data.getDistanceToTravel(), 2)) { continue; } /* TODO Only allow hits on parts of the rectangle that are within range, * not just the whole thing if the center is within range. */ // accounting for wind speed/direction float windCompassDirection = data.getWindCompassDirection(from.getWorld()); float windSpeed = data.getWindSpeedMPH(from.getWorld()); fromYaw += (windCompassDirection > fromYaw ? 1 : windCompassDirection < fromYaw ? -1 : 0) * windCompassDirection / 60 * windSpeed; fromYaw %= 360; Location boxOrigin = hitBox.getOrigin(); int[] orderClockwise = new int[] {0, 1, 4, 3}; Location thisSideCorner = hitBox.getCorner(0); Location oppositeSideCorner = hitBox.getCorner(0); for (int i = 0; i < orderClockwise.length; i++) { int num = orderClockwise[i]; Location corner = hitBox.getCorner(num); Location clockwise = hitBox.getCorner(orderClockwise[(i + 1) % 3]); if ((Math.atan2(from.getZ() - corner.getZ(), from.getX() - corner.getX()) * 180 / Math.PI) > 0 && corner.distanceSquared(from) < clockwise.distanceSquared(from)) { thisSideCorner = corner; int exitCornerClockwiseAmount = (Math.atan2(from.getZ() - clockwise.getZ(), from.getX() - clockwise.getX()) * 180 / Math.PI) < 0 ? 2 : 3; oppositeSideCorner = hitBox.getCorner((i + exitCornerClockwiseAmount) % 3); } } Location entrance = getHit(thisSideCorner, data, hitBox, fromYaw, fromPitch, true); Location exit = getHit(oppositeSideCorner, data, hitBox, fromYaw, fromPitch, false); // hit detection and reaction if (entrance.getX() - boxOrigin.getX() <= hitBox.getX() && entrance.getY() - boxOrigin.getY() <= hitBox.getY() && entrance.getZ() - boxOrigin.getZ() <= hitBox.getZ()) { hits.add(new Hit(from, entrance, exit, hitBox, data)); } } return hits; } private Location getHit(Location thisSideCorner, ShotData data, HitBox hitBox, float fromYaw, float fromPitch, boolean variance) { double deltaFromToSideCornerX = from.getX() - thisSideCorner.getX(); double deltaFromToSideCornerZ = from.getZ() - thisSideCorner.getZ(); double xzDistFromSideCorner = Math.sqrt(Math.pow(deltaFromToSideCornerX, 2) + Math.pow(deltaFromToSideCornerZ, 2)); double yawSubtractionToSideCorner = Math.atan2(deltaFromToSideCornerZ, deltaFromToSideCornerX) * 180 / Math.PI; float deltaYaw = Math.abs(hitBox.getYawRotation() - fromYaw); double originDeltaYaw = 180 - (yawSubtractionToSideCorner + deltaYaw); double xzHitDistance = (xzDistFromSideCorner * (Math.sin(Math.toRadians(originDeltaYaw))) / Math.sin(Math.toRadians(deltaYaw))); double deltaX = (xzHitDistance * (Math.sin(Math.toRadians(180 - (fromYaw + 90)))) / Math.sin(Math.toRadians(90))); double deltaY = (xzDistFromSideCorner * (Math.sin(Math.toRadians(-fromPitch))) / Math.sin(Math.toRadians(90 - fromPitch))); double deltaZ = (xzHitDistance * (Math.sin(Math.toRadians(fromYaw))) / Math.sin(Math.toRadians(90))); double hitDistance = (xzHitDistance * (Math.sin(Math.toRadians(90))) / Math.sin(Math.toRadians(fromYaw))); Location hit = from.clone().add(deltaX + (variance ? data.getDeltaX(hitDistance, fromYaw) : 0), deltaY + (variance ? data.getDeltaY(hitDistance, fromPitch) : 0), deltaZ + (variance ? data.getDeltaZ(hitDistance, fromYaw) : 0)); hit.setYaw(fromYaw); hit.setPitch(fromPitch); return hit; } }
true
true
public List<Hit> shoot(ShotData data, List<HitBox> hitBoxes) { List<Hit> hits = new ArrayList<Hit>(); for (HitBox hitBox : hitBoxes) { hitBox.update(); float fromYaw = 360 % from.getYaw(); float fromPitch = 360 % from.getPitch(); // making sure the center location is within range if (hitBox.getCenter().distanceSquared(from) > Math.pow(data.getDistanceToTravel(), 2)) { continue; } /* TODO Only allow hits on parts of the rectangle that are within range, * not just the whole thing if the center is within range. */ // accounting for wind speed/direction float windCompassDirection = data.getWindCompassDirection(from.getWorld()); float windSpeed = data.getWindSpeedMPH(from.getWorld()); fromYaw += (windCompassDirection > fromYaw ? 1 : windCompassDirection < fromYaw ? -1 : 0) * windCompassDirection / 60 * windSpeed; fromYaw %= 360; Location boxOrigin = hitBox.getOrigin(); int[] orderClockwise = new int[] {0, 1, 4, 3}; Location thisSideCorner = hitBox.getCorner(0); Location oppositeSideCorner = hitBox.getCorner(0); for (int i = 0; i < orderClockwise.length; i++) { int num = orderClockwise[i]; Location corner = hitBox.getCorner(num); Location clockwise = hitBox.getCorner(orderClockwise[(i + 1) % 3]); if ((Math.atan2(from.getZ() - corner.getZ(), from.getX() - corner.getX()) * 180 / Math.PI) > 0 && corner.distanceSquared(from) < clockwise.distanceSquared(from)) { thisSideCorner = corner; int exitCornerClockwiseAmount = (Math.atan2(from.getZ() - clockwise.getZ(), from.getX() - clockwise.getX()) * 180 / Math.PI) < 0 ? 2 : 3; oppositeSideCorner = hitBox.getCorner((i + exitCornerClockwiseAmount) % 3); } } Location entrance = getHit(thisSideCorner, data, hitBox, fromYaw, fromPitch, true); Location exit = getHit(oppositeSideCorner, data, hitBox, fromYaw, fromPitch, false); // hit detection and reaction if (entrance.getX() - boxOrigin.getX() <= hitBox.getX() && entrance.getY() - boxOrigin.getY() <= hitBox.getY() && entrance.getZ() - boxOrigin.getZ() <= hitBox.getZ()) { hits.add(new Hit(from, entrance, exit, hitBox, data)); } } return hits; }
public List<Hit> shoot(ShotData data, List<HitBox> hitBoxes) { List<Hit> hits = new ArrayList<Hit>(); for (HitBox hitBox : hitBoxes) { hitBox.update(); float fromYaw = from.getYaw() % 360; float fromPitch = from.getPitch() % 360; // making sure the center location is within range if (hitBox.getCenter().distanceSquared(from) > Math.pow(data.getDistanceToTravel(), 2)) { continue; } /* TODO Only allow hits on parts of the rectangle that are within range, * not just the whole thing if the center is within range. */ // accounting for wind speed/direction float windCompassDirection = data.getWindCompassDirection(from.getWorld()); float windSpeed = data.getWindSpeedMPH(from.getWorld()); fromYaw += (windCompassDirection > fromYaw ? 1 : windCompassDirection < fromYaw ? -1 : 0) * windCompassDirection / 60 * windSpeed; fromYaw %= 360; Location boxOrigin = hitBox.getOrigin(); int[] orderClockwise = new int[] {0, 1, 4, 3}; Location thisSideCorner = hitBox.getCorner(0); Location oppositeSideCorner = hitBox.getCorner(0); for (int i = 0; i < orderClockwise.length; i++) { int num = orderClockwise[i]; Location corner = hitBox.getCorner(num); Location clockwise = hitBox.getCorner(orderClockwise[(i + 1) % 3]); if ((Math.atan2(from.getZ() - corner.getZ(), from.getX() - corner.getX()) * 180 / Math.PI) > 0 && corner.distanceSquared(from) < clockwise.distanceSquared(from)) { thisSideCorner = corner; int exitCornerClockwiseAmount = (Math.atan2(from.getZ() - clockwise.getZ(), from.getX() - clockwise.getX()) * 180 / Math.PI) < 0 ? 2 : 3; oppositeSideCorner = hitBox.getCorner((i + exitCornerClockwiseAmount) % 3); } } Location entrance = getHit(thisSideCorner, data, hitBox, fromYaw, fromPitch, true); Location exit = getHit(oppositeSideCorner, data, hitBox, fromYaw, fromPitch, false); // hit detection and reaction if (entrance.getX() - boxOrigin.getX() <= hitBox.getX() && entrance.getY() - boxOrigin.getY() <= hitBox.getY() && entrance.getZ() - boxOrigin.getZ() <= hitBox.getZ()) { hits.add(new Hit(from, entrance, exit, hitBox, data)); } } return hits; }
diff --git a/illaclient/src/illarion/client/graphics/AbstractEntity.java b/illaclient/src/illarion/client/graphics/AbstractEntity.java index 5cd2921d..897c7450 100644 --- a/illaclient/src/illarion/client/graphics/AbstractEntity.java +++ b/illaclient/src/illarion/client/graphics/AbstractEntity.java @@ -1,835 +1,843 @@ /* * This file is part of the Illarion Client. * * Copyright © 2012 - Illarion e.V. * * The Illarion Client 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 Client 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 Client. If not, see <http://www.gnu.org/licenses/>. */ package illarion.client.graphics; import illarion.client.graphics.shader.HighlightShader; import illarion.client.graphics.shader.Shader; import illarion.client.graphics.shader.ShaderManager; import illarion.client.resources.data.AbstractEntityTemplate; import illarion.client.world.World; import illarion.common.types.Location; import illarion.common.types.Rectangle; import illarion.common.util.FastMath; import org.apache.log4j.Logger; import org.newdawn.slick.Color; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Input; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.concurrent.NotThreadSafe; /** * The entity is a object that is shown in the game. It contains a sprite and possibly a frame animation. Also it * performs fade in and out effects. * <p> * It handles static objects on the screen as well as animated ones or objects with variations. * </p> * * @author Nop * @author Martin Karing &lt;[email protected]&gt; */ @SuppressWarnings("nls") @NotThreadSafe public abstract class AbstractEntity<T extends AbstractEntityTemplate> implements DisplayItem, AlphaHandler, AnimatedFrame { /** * This class is used in case more then one alpha change listener is added. It forwards a alpha change message to * two other handlers. This way its possible to create a infinite amount of listeners on one entity. */ private static final class AlphaChangeListenerMulticast implements AlphaChangeListener { /** * The first listener to get the event. */ private final AlphaChangeListener listener1; /** * The second listener to get the event. */ private final AlphaChangeListener listener2; /** * Constructor for a multicast object. * * @param l1 the first listener to get the message * @param l2 the second listener to get the message */ private AlphaChangeListenerMulticast(final AlphaChangeListener l1, final AlphaChangeListener l2) { listener1 = l1; listener2 = l2; } /** * This method receives the alpha changed event and forwards its data to both added listeners. * * @param from the old alpha value * @param to the new alpha value */ @Override public void alphaChanged(final int from, final int to) { listener1.alphaChanged(from, to); listener2.alphaChanged(from, to); } } /** * The default light that is used in the client. */ @Nonnull protected static final Color DEFAULT_LIGHT = new Color(1.f, 1.f, 1.f, 1.f); /** * The speed value for fading the alpha values by default. */ private static final int FADING_SPEED = 25; /** * The color value of the alpha when the object is faded out fully. */ private static final int FADE_OUT_ALPHA = (int) (0.4f * 255); /** * The alpha listener that is supposed to receive a message in case the alpha value of this entity changed. */ @Nullable private AlphaChangeListener alphaListener; /** * The target of the alpha approaching. The current alpha value will move by default closer to the alpha target * value at every render run. */ private int alphaTarget; /** * The base color is the color the image of the sprite is always colored with, * this color is applied no matter what the localLight is set to. */ @Nullable private Color baseColor; /** * The frame that is currently shown by this entity. */ private int currentFrame; /** * The current x location of this item on the screen relative to the origin of the game map. */ private int displayX; /** * The current y location of this item on the screen relative to the origin of the game map. */ private int displayY; /** * The z order of the item, so the layer of the item that determines the position of the object in the display * list. */ private int layerZ; /** * The light that effects this entity directly. That could be the {@link #DEFAULT_LIGHT} that ensures that the * object is displayed with its real colors or the ambient light of the weather that ensures that the object is * colored for the display on the map. */ @Nonnull private Color localLight; /** * The light value that is used to render this entity during the next render loop. */ @Nonnull private Color renderLight = new Color(Color.white); /** * This color is the color that was used last time to render the entity. Its used to check if the color changed * and the entity needs to be rendered again. */ @Nonnull private final Color lastRenderLight = new Color(Color.white); /** * The color that is used to overwrite the real color of this entity. */ @Nullable private Color overWriteBaseColor; /** * The scaling value that is applied to this entity. */ private float scale = 1.f; /** * A flag if this object is currently shown on the screen. */ private boolean shown; /** * This flag is used to determine if the scaling value is used at the rendering or not. Not using the scaling * value has a positive impact on the performance. */ private boolean useScale; /** * The template of this instance. */ private final T template; protected AbstractEntity(final T template) { this.template = template; baseColor = template.getDefaultColor(); if (baseColor == null) { alphaTarget = 255; localLight = new Color(Color.white); } else { localLight = new Color(baseColor); alphaTarget = baseColor.getAlpha(); } } @Nonnull public T getTemplate() { return template; } @Override public void addAlphaChangeListener(@Nonnull final AlphaChangeListener listener) { if (removedEntity) { LOGGER.warn("Adding a alpha listener to a removed entity is not allowed."); return; } if (alphaListener == null) { alphaListener = listener; return; } alphaListener = new AlphaChangeListenerMulticast(alphaListener, listener); } /** * This function is triggered when a frame animation is done. Overwrite this function in order to archive some * special event handling after the animation. By default it does nothing. * * @param finished true in case the animation is really done */ @Override public void animationFinished(final boolean finished) { // nothing needs to be done by default } /** * Set a new base color of the entity. * * @param newBaseColor the new base color of the entity, {@code null} to get the default color */ public void changeBaseColor(@Nullable final Color newBaseColor) { if (removedEntity) { LOGGER.warn("Changing the baseColor of a entity is not allowed after the entity was removed."); return; } if (newBaseColor == null) { overWriteBaseColor = null; return; } if (overWriteBaseColor == null) { overWriteBaseColor = new Color(newBaseColor); } else { copyLightValues(newBaseColor, overWriteBaseColor); } } /** * Get the frame that is currently displayed. * * @return the currently displayed frame */ public int getCurrentFrame() { return currentFrame; } /** * Get the highlighting level of the item * * @return the highlight level of the object */ public int getHighlight() { return 0; } /** * Draw this entity to the screen. This also performs a few basic animations such as fading in and out, * based on the delta time that is supplied to this function. * * @return true in case the rendering operation was done successfully */ @Override public boolean draw(@Nonnull final Graphics g) { if (removedEntity) { LOGGER.warn("Drawing a removed entity is not allowed."); return true; } if (getAlpha() == 0) { return true; } final int renderLocX = displayX; final int renderLocY = displayY; if (!Camera.getInstance().requiresUpdate(displayRect)) { return true; } final Rectangle parentDirtyArea = Camera.getInstance().getDirtyArea(displayRect); if ((parentDirtyArea != null) && !parentDirtyArea.equals(Camera.getInstance().getViewport())) { g.setClip(parentDirtyArea.getX() - Camera.getInstance().getViewportOffsetX(), (parentDirtyArea.getY() - Camera.getInstance().getViewportOffsetY()) + World.getMapDisplay().getHeightOffset(), parentDirtyArea.getWidth(), parentDirtyArea.getHeight()); } HighlightShader shader = null; final int highlight = getHighlight(); if (highlight > 0) { shader = ShaderManager.getShader(Shader.Highlight, HighlightShader.class); shader.bind(); shader.setTexture(0); if (highlight == 1) { shader.setHighlightShare(0.05f); } else { shader.setHighlightShare(0.25f); } } final Sprite sprite = template.getSprite(); if (useScale) { sprite.draw(g, renderLocX, renderLocY, renderLight, currentFrame, scale); } else { sprite.draw(g, renderLocX, renderLocY, renderLight, currentFrame); } if (shader != null) { shader.unbind(); } if ((parentDirtyArea != null) && !parentDirtyArea.equals(Camera.getInstance().getViewport())) { g.clearClip(); } Camera.getInstance().markAreaRendered(displayRect); return true; } /** * Get the current alpha value. * * @return the alpha value */ @Override public int getAlpha() { return getLight().getAlpha(); } /** * Get the current x location of this object on the screen relative to the * origin of the game map. That value is set with the screen position. * * @return the x coordinate of the display location */ public final int getDisplayX() { return displayX; } /** * Get the current y location of this object on the screen relative to the * origin of the game map. That value is set with the screen position. * * @return the y coordinate of the display location */ public final int getDisplayY() { return displayY; } /** * Get the current light instance that is used by this entity. * * @return the light this entity uses at the rendering functions */ @Nonnull public final Color getLight() { return localLight; } /** * Get the scaling value that is applied to the entity. * * @return the scaling value applied to the entity */ public float getScale() { return scale; } /** * Get the current target of the alpha approaching. * * @return the current alpha target value */ public final int getTargetAlpha() { return alphaTarget; } /** * Get the Z Order of this entity that marks the position in the display * list and selects this way, how other images overlay this entity. * * @return the layer of this entity */ @Override public final int getZOrder() { return layerZ; } /** * Hide the entity from the screen by removing it from the display list. */ @Override public void hide() { if (shown) { World.getMapDisplay().remove(this); shown = false; } } /** * Once this value is set {@code true} the entity can be assumed to be removed. It must not be added to the * display again once this was done. */ private boolean removedEntity; /** * Calling this function marks the entity to be removed from the client for good. Once this function was called * its not allowed to do anything anymore with this entity. */ public void markAsRemoved() { removedEntity = true; hide(); } /** * Check if the entity is visible. * * @return true in case the entity is visible */ public final boolean isVisible() { return (alphaTarget > 0) || (getLight().getAlpha() > 0); } /** * Set the current alpha value of the entity. This causes that the alpha value is changed right away without any * fading effect. To get a fading effect use {@link #setAlphaTarget(int)}. * * @param newAlpha the new alpha value of this entity */ @Override public void setAlpha(final int newAlpha) { if (removedEntity) { LOGGER.warn("Changing the alpha value of a removed entity is not allowed."); return; } if (getLight().getAlpha() != newAlpha) { final int oldAlpha = getLight().getAlpha(); getLight().a = newAlpha / 255.f; if (alphaListener != null) { alphaListener.alphaChanged(oldAlpha, getLight().getAlpha()); } wentDirty = true; } } /** * Set the target of a alpha fading effect. At every rendering run of this entity the real alpha value of this * entity will move closer to the alpha target. To set the alpha value without a fading animation use * {@link #setAlpha(int)}. * * @param newAlphaTarget the target of the alpha fading */ @Override public final void setAlphaTarget(final int newAlphaTarget) { if (removedEntity) { LOGGER.warn("Changing the alpha animation target of a entity is not allowed."); return; } alphaTarget = newAlphaTarget; } /** * Set the base color of this entity. This operation does not create a copy of this reference. * * @param newBaseColor the new base color of the entity */ public void setBaseColor(@Nullable final Color newBaseColor) { if (removedEntity) { LOGGER.warn("Changing the base color of a entity is not allowed once the entity was removed."); return; } baseColor = newBaseColor; } /** * Set the frame that is currently displayed at the render functions of this entity. * * @param frame the index of the frame that is displayed */ @Override public void setFrame(final int frame) { if (removedEntity) { LOGGER.warn("Changing the frame of a removed entity is not allowed."); return; } if (currentFrame != frame) { currentFrame = frame; wentDirty = true; } } /** * Set the current light of this entity. This sets the instance that is set as parameter directly as local light * color. So any changes applied to the instance that was transferred will effect the light of this entity. * * @param light the new light that shall be used by this entity */ public void setLight(@Nonnull final Color light) { if (removedEntity) { LOGGER.warn("Changing the light of a removed entity is not allowed."); return; } final float oldAlpha = localLight.a; localLight = new Color(light); localLight.a = oldAlpha; } /** * Set the scaling that shall be applied to this entity. * * @param newScale the new scaling value applied to this entity */ public void setScale(final float newScale) { if (removedEntity) { LOGGER.warn("Changing the scale of a removed entity is not allowed."); return; } if (scale != newScale) { scale = newScale; useScale = FastMath.abs(1.f - newScale) > FastMath.FLT_EPSILON; wentDirty = true; } } /** * Set the position of the entity on the display. The display origin is at the origin of the game map. * * @param dispX the x coordinate of the location of the display * @param dispY the y coordinate of the location of the display * @param zLayer the z layer of the coordinate * @param typeLayer the global layer of this type of entity. */ public void setScreenPos(final int dispX, final int dispY, final int zLayer, final int typeLayer) { if (removedEntity) { LOGGER.warn("Changing the screen position of a removed entity is not allowed."); return; } if ((dispX != displayX) || (dispY != displayY)) { wentDirty = true; } displayX = dispX; displayY = dispY; if (shown) { final int newLayerZ = zLayer - typeLayer; if (newLayerZ != layerZ) { updateDisplayPosition(); layerZ = newLayerZ; } } else { layerZ = zLayer - typeLayer; } } /** * Set the position of the entity on the display. The display origin is at * the origin of the game map. * * @param loc the location of the entity on the map * @param typeLayer the global layer of this type of entity. */ public final void setScreenPos(@Nonnull final Location loc, final int typeLayer) { setScreenPos(loc.getDcX(), loc.getDcY(), loc.getDcZ(), typeLayer); } @Override public boolean processEvent(@Nonnull final GameContainer container, final int delta, @Nonnull final MapInteractionEvent event) { return false; } protected boolean isMouseInInteractionRect(final int mouseX, final int mouseY) { final int mouseXonDisplay = mouseX + Camera.getInstance().getViewportOffsetX(); final int mouseYonDisplay = mouseY + Camera.getInstance().getViewportOffsetY(); return getInteractionRect().isInside(mouseXonDisplay, mouseYonDisplay); } protected boolean isMouseInInteractionRect(@Nonnull final Input input) { return isMouseInInteractionRect(input.getMouseX(), input.getMouseY()); } /** * The logging instance of this class. */ private static final Logger LOGGER = Logger.getLogger(AbstractEntity.class); @Override public void show() { if (removedEntity) { LOGGER.warn("Adding a entity to the display list is not allowed after the entity was removed."); return; } if (shown) { LOGGER.error("Added entity twice."); } else { World.getMapDisplay().add(this); shown = true; wentDirty = true; } } /** * Update the position of this entity in the display list. */ public void updateDisplayPosition() { if (removedEntity) { LOGGER.warn("Updating the display position is not allowed once the entity was removed."); return; } if (shown) { World.getMapDisplay().readd(this); wentDirty = true; } else { LOGGER.error("Updated display location for hidden item."); } } @Override public void update(@Nonnull final GameContainer container, final int delta) { if (removedEntity) { LOGGER.warn("Updating a removed entity is not allowed."); + shown = true; + hide(); + return; + } + if (!shown) { + LOGGER.warn("Entity that is not shown received update."); + shown = true; + hide(); return; } final Sprite sprite = template.getSprite(); final int offS = template.getShadowOffset(); int xOffset = sprite.getOffsetX() + sprite.getAlignOffsetX(); int yOffset = sprite.getOffsetY() - sprite.getAlignOffsetY(); int width = sprite.getWidth(); int widthNoShadow = width - offS; int height = sprite.getHeight(); if (useScale) { xOffset *= scale; yOffset *= scale; width *= scale; widthNoShadow *= scale; height *= scale; } final int scrX = displayX + xOffset; final int scrY = displayY - yOffset; displayRect.set(scrX, scrY, width, height); if (fadingCorridorEffect) { final boolean transparent = FadingCorridor.getInstance().isInCorridor(scrX, scrY, layerZ, widthNoShadow, height); if (transparent) { setAlphaTarget(FADE_OUT_ALPHA); } else { setAlphaTarget(255); } } updateAlpha(delta); renderLight = getLocalLight(); if ((baseColor != null) || (overWriteBaseColor != null)) { if (overWriteBaseColor != null) { renderLight = renderLight.multiply(overWriteBaseColor); } else { renderLight = renderLight.multiply(baseColor); } } if (!renderLight.equals(lastRenderLight)) { wentDirty = true; copyLightValues(renderLight, lastRenderLight); } setEntityAreaDirty(); } /** * Get the light local to this tile. * * @return the local light of this entity */ @Nonnull public Color getLocalLight() { final Color parentLight = getParentLight(); if (parentLight == null) { return new Color(getLight()); } return parentLight.multiply(getLight()); } private static void copyLightValues(@Nonnull final Color source, @Nonnull final Color target) { target.r = source.r; target.g = source.g; target.b = source.b; target.a = source.a; } @Nonnull private final Rectangle displayRect = new Rectangle(); @Nonnull private final Rectangle interactionRect = new Rectangle(); @Nonnull private final Rectangle lastDisplayRect = new Rectangle(); private boolean wentDirty; /** * Get the current interactive area of the object. * * @return the interactive area of the object */ @Nonnull public final Rectangle getInteractionRect() { final int offS = template.getShadowOffset(); if (offS == 0) { return displayRect; } interactionRect.set(displayRect); interactionRect.expand(0, 0, -offS, 0); return interactionRect; } /** * Get the current display rectangle. * * @return the current display rectangle */ @Nonnull public final Rectangle getDisplayRect() { return displayRect; } /** * The display rectangle that was active when rendering the last frame. * * @return the last display rectangle */ @Override @Nonnull public Rectangle getLastDisplayRect() { return lastDisplayRect; } public final void setEntityAreaDirty() { if (wentDirty || !lastDisplayRect.equals(displayRect)) { wentDirty = false; if (!lastDisplayRect.isEmpty()) { Camera.getInstance().markAreaDirty(lastDisplayRect); if (displayRect.equals(lastDisplayRect)) { return; } } lastDisplayRect.set(displayRect); Camera.getInstance().markAreaDirty(displayRect); } } private boolean fadingCorridorEffect; public void setFadingCorridorEffectEnabled(final boolean value) { fadingCorridorEffect = value; } /** * This function checks if the entity is made transparent due the color its * drawn with. * * @return <code>true</code> in case the graphic is turned transparent due * its color */ public boolean isTransparent() { return getAlpha() < 255; } /** * Update the alpha value. This function causes the alpha value to approach * the target alpha value and notifies in case its needed all listeners. * * @param delta the time in milliseconds since the last update */ protected final void updateAlpha(final int delta) { if (getAlpha() != alphaTarget) { setAlpha(AnimationUtility.translate(getAlpha(), alphaTarget, FADING_SPEED, 0, 255, delta)); } } /** * This function returns if this entity is using the scale value. This value * can be used for optimization. * * @return <code>true</code> in case the scaling value is used */ protected boolean usingScale() { return useScale; } /** * Get the parent light of this entity. This is the light value that is supplied by some other object. The value of * this color is never altered by this class. The value can be {@code null} to assume the default light. * * @return the parent light */ @Nullable protected Color getParentLight() { return null; } }
true
true
public void update(@Nonnull final GameContainer container, final int delta) { if (removedEntity) { LOGGER.warn("Updating a removed entity is not allowed."); return; } final Sprite sprite = template.getSprite(); final int offS = template.getShadowOffset(); int xOffset = sprite.getOffsetX() + sprite.getAlignOffsetX(); int yOffset = sprite.getOffsetY() - sprite.getAlignOffsetY(); int width = sprite.getWidth(); int widthNoShadow = width - offS; int height = sprite.getHeight(); if (useScale) { xOffset *= scale; yOffset *= scale; width *= scale; widthNoShadow *= scale; height *= scale; } final int scrX = displayX + xOffset; final int scrY = displayY - yOffset; displayRect.set(scrX, scrY, width, height); if (fadingCorridorEffect) { final boolean transparent = FadingCorridor.getInstance().isInCorridor(scrX, scrY, layerZ, widthNoShadow, height); if (transparent) { setAlphaTarget(FADE_OUT_ALPHA); } else { setAlphaTarget(255); } } updateAlpha(delta); renderLight = getLocalLight(); if ((baseColor != null) || (overWriteBaseColor != null)) { if (overWriteBaseColor != null) { renderLight = renderLight.multiply(overWriteBaseColor); } else { renderLight = renderLight.multiply(baseColor); } } if (!renderLight.equals(lastRenderLight)) { wentDirty = true; copyLightValues(renderLight, lastRenderLight); } setEntityAreaDirty(); }
public void update(@Nonnull final GameContainer container, final int delta) { if (removedEntity) { LOGGER.warn("Updating a removed entity is not allowed."); shown = true; hide(); return; } if (!shown) { LOGGER.warn("Entity that is not shown received update."); shown = true; hide(); return; } final Sprite sprite = template.getSprite(); final int offS = template.getShadowOffset(); int xOffset = sprite.getOffsetX() + sprite.getAlignOffsetX(); int yOffset = sprite.getOffsetY() - sprite.getAlignOffsetY(); int width = sprite.getWidth(); int widthNoShadow = width - offS; int height = sprite.getHeight(); if (useScale) { xOffset *= scale; yOffset *= scale; width *= scale; widthNoShadow *= scale; height *= scale; } final int scrX = displayX + xOffset; final int scrY = displayY - yOffset; displayRect.set(scrX, scrY, width, height); if (fadingCorridorEffect) { final boolean transparent = FadingCorridor.getInstance().isInCorridor(scrX, scrY, layerZ, widthNoShadow, height); if (transparent) { setAlphaTarget(FADE_OUT_ALPHA); } else { setAlphaTarget(255); } } updateAlpha(delta); renderLight = getLocalLight(); if ((baseColor != null) || (overWriteBaseColor != null)) { if (overWriteBaseColor != null) { renderLight = renderLight.multiply(overWriteBaseColor); } else { renderLight = renderLight.multiply(baseColor); } } if (!renderLight.equals(lastRenderLight)) { wentDirty = true; copyLightValues(renderLight, lastRenderLight); } setEntityAreaDirty(); }
diff --git a/org.eclipse.mylyn.bugzilla.core/src/org/eclipse/mylyn/internal/bugzilla/core/SaxMultiBugReportContentHandler.java b/org.eclipse.mylyn.bugzilla.core/src/org/eclipse/mylyn/internal/bugzilla/core/SaxMultiBugReportContentHandler.java index ac57f7291..cbaf6c9c4 100644 --- a/org.eclipse.mylyn.bugzilla.core/src/org/eclipse/mylyn/internal/bugzilla/core/SaxMultiBugReportContentHandler.java +++ b/org.eclipse.mylyn.bugzilla.core/src/org/eclipse/mylyn/internal/bugzilla/core/SaxMultiBugReportContentHandler.java @@ -1,421 +1,423 @@ /******************************************************************************* * Copyright (c) 2004, 2007 Mylyn project committers 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 *******************************************************************************/ package org.eclipse.mylyn.internal.bugzilla.core; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import org.eclipse.mylyn.tasks.core.AbstractAttributeFactory; import org.eclipse.mylyn.tasks.core.RepositoryAttachment; import org.eclipse.mylyn.tasks.core.RepositoryTaskAttribute; import org.eclipse.mylyn.tasks.core.RepositoryTaskData; import org.eclipse.mylyn.tasks.core.TaskComment; import org.eclipse.mylyn.tasks.core.data.AbstractTaskDataCollector; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * Parser for xml bugzilla reports. * * @author Rob Elves */ public class SaxMultiBugReportContentHandler extends DefaultHandler { private static final String ATTRIBUTE_NAME = "name"; private static final String COMMENT_ATTACHMENT_STRING = "Created an attachment (id="; private StringBuffer characters; private TaskComment taskComment; private Map<String, TaskComment> attachIdToComment = new HashMap<String, TaskComment>(); private int commentNum = 0; private RepositoryAttachment attachment; private Map<String, RepositoryTaskData> taskDataMap; private RepositoryTaskData repositoryTaskData; private List<TaskComment> longDescs; private String errorMessage = null; private AbstractAttributeFactory attributeFactory; private List<BugzillaCustomField> customFields; private AbstractTaskDataCollector collector; //private int retrieved = 1; public SaxMultiBugReportContentHandler(AbstractAttributeFactory factory, AbstractTaskDataCollector collector, Map<String, RepositoryTaskData> taskDataMap, List<BugzillaCustomField> customFields) { this.attributeFactory = factory; this.taskDataMap = taskDataMap; this.customFields = customFields; this.collector = collector; } public boolean errorOccurred() { return errorMessage != null; } public String getErrorMessage() { return errorMessage; } // public RepositoryTaskData getReport() { // return repositoryTaskData; // } @Override public void characters(char[] ch, int start, int length) throws SAXException { characters.append(ch, start, length); //System.err.println(String.copyValueOf(ch, start, length)); // if (monitor.isCanceled()) { // throw new OperationCanceledException("Search cancelled"); // } } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { characters = new StringBuffer(); BugzillaReportElement tag = BugzillaReportElement.UNKNOWN; if (localName.startsWith(BugzillaCustomField.CUSTOM_FIELD_PREFIX)) return; try { tag = BugzillaReportElement.valueOf(localName.trim().toUpperCase(Locale.ENGLISH)); } catch (RuntimeException e) { if (e instanceof IllegalArgumentException) { // ignore unrecognized tags return; } throw e; } switch (tag) { case BUGZILLA: // Note: here we can get the bugzilla version if necessary break; case BUG: if (attributes != null && (attributes.getValue("error") != null)) { errorMessage = attributes.getValue("error"); } attachIdToComment = new HashMap<String, TaskComment>(); commentNum = 0; taskComment = null; longDescs = new ArrayList<TaskComment>(); break; case LONG_DESC: taskComment = new TaskComment(attributeFactory, commentNum++); break; case WHO: if (taskComment != null) { if (attributes != null && attributes.getLength() > 0) { String name = attributes.getValue(ATTRIBUTE_NAME); if (name != null) { taskComment.setAttributeValue(BugzillaReportElement.WHO_NAME.getKeyString(), name); } } } break; case REPORTER: if (attributes != null && attributes.getLength() > 0) { String name = attributes.getValue(ATTRIBUTE_NAME); if (name != null) { RepositoryTaskAttribute attr = attributeFactory.createAttribute(BugzillaReportElement.REPORTER_NAME.getKeyString()); attr.setValue(name); repositoryTaskData.addAttribute(BugzillaReportElement.REPORTER_NAME.getKeyString(), attr); } } break; case ASSIGNED_TO: if (attributes != null && attributes.getLength() > 0) { String name = attributes.getValue(ATTRIBUTE_NAME); if (name != null) { RepositoryTaskAttribute attr = attributeFactory.createAttribute(BugzillaReportElement.ASSIGNED_TO_NAME.getKeyString()); attr.setValue(name); repositoryTaskData.addAttribute(BugzillaReportElement.ASSIGNED_TO_NAME.getKeyString(), attr); } } break; case ATTACHMENT: attachment = new RepositoryAttachment(attributeFactory); if (attributes != null) { if ("1".equals(attributes.getValue(BugzillaReportElement.IS_OBSOLETE.getKeyString()))) { attachment.addAttribute(BugzillaReportElement.IS_OBSOLETE.getKeyString(), attributeFactory.createAttribute(BugzillaReportElement.IS_OBSOLETE.getKeyString())); attachment.setObsolete(true); } if ("1".equals(attributes.getValue(BugzillaReportElement.IS_PATCH.getKeyString()))) { attachment.setPatch(true); } } break; } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { String parsedText = characters.toString(); if (localName.startsWith(BugzillaCustomField.CUSTOM_FIELD_PREFIX)) { RepositoryTaskAttribute attribute = repositoryTaskData.getAttribute(localName); if (attribute == null) { String desc = "???"; for (BugzillaCustomField bugzillaCustomField : customFields) { if (localName.equals(bugzillaCustomField.getName())) { desc = bugzillaCustomField.getDescription(); } } RepositoryTaskAttribute newattribute = new RepositoryTaskAttribute(localName, desc, true); newattribute.setReadOnly(false); newattribute.setValue(parsedText); repositoryTaskData.addAttribute(localName, newattribute); } else { attribute.addValue(parsedText); } } BugzillaReportElement tag = BugzillaReportElement.UNKNOWN; try { tag = BugzillaReportElement.valueOf(localName.trim().toUpperCase(Locale.ENGLISH)); } catch (RuntimeException e) { if (e instanceof IllegalArgumentException) { // ignore unrecognized tags return; } throw e; } switch (tag) { case BUG_ID: { try { repositoryTaskData = taskDataMap.get(parsedText.trim()); if (repositoryTaskData == null) { errorMessage = parsedText + " id not found."; } } catch (Exception e) { errorMessage = "Bug id from server did not match requested id."; } RepositoryTaskAttribute attr = repositoryTaskData.getAttribute(tag.getKeyString()); if (attr == null) { attr = attributeFactory.createAttribute(tag.getKeyString()); repositoryTaskData.addAttribute(tag.getKeyString(), attr); } attr.setValue(parsedText); break; } // Comment attributes case WHO: if (taskComment != null) { RepositoryTaskAttribute attr = attributeFactory.createAttribute(tag.getKeyString()); attr.setValue(parsedText); taskComment.addAttribute(tag.getKeyString(), attr); } break; case BUG_WHEN: if (taskComment != null) { RepositoryTaskAttribute attr = attributeFactory.createAttribute(tag.getKeyString()); attr.setValue(parsedText); taskComment.addAttribute(tag.getKeyString(), attr); } break; case THETEXT: if (taskComment != null) { RepositoryTaskAttribute attr = attributeFactory.createAttribute(tag.getKeyString()); attr.setValue(parsedText); taskComment.addAttribute(tag.getKeyString(), attr); // Check for attachment parseAttachment(taskComment, parsedText); } break; case LONG_DESC: if (taskComment != null) { longDescs.add(taskComment); } break; // Attachment attributes case ATTACHID: case DATE: case DESC: case FILENAME: case CTYPE: case TYPE: case SIZE: if (attachment != null) { RepositoryTaskAttribute attr = attributeFactory.createAttribute(tag.getKeyString()); attr.setValue(parsedText); attachment.addAttribute(tag.getKeyString(), attr); } break; case DATA: break; case ATTACHMENT: if (attachment != null) { repositoryTaskData.addAttachment(attachment); } break; // IGNORED ELEMENTS // case REPORTER_ACCESSIBLE: // case CLASSIFICATION_ID: // case CLASSIFICATION: // case CCLIST_ACCESSIBLE: // case EVERCONFIRMED: case BUGZILLA: break; // Considering solution for bug#198714 // case DELTA_TS: // RepositoryTaskAttribute delta_ts_attribute = repositoryTaskData.getAttribute(tag.getKeyString()); // if (delta_ts_attribute == null) { // delta_ts_attribute = attributeFactory.createAttribute(tag.getKeyString()); // repositoryTaskData.addAttribute(tag.getKeyString(), delta_ts_attribute); // } // delta_ts_attribute.setValue(BugzillaClient.stripTimeZone(parsedText)); // break; case BUG: // Reached end of bug. Need to set LONGDESCLENGTH to number of // comments int longDescsSize = longDescs.size() - 1; if (longDescsSize == 0) { repositoryTaskData.setAttributeValue(RepositoryTaskAttribute.DESCRIPTION, longDescs.get(0).getText()); } else if (longDescsSize == 1) { - if (longDescs.get(0).getCreated().compareTo(longDescs.get(1).getCreated()) < 0) { + if (longDescs.get(0).getCreated().compareTo(longDescs.get(1).getCreated()) <= 0) { + // if created_0 is equal to created_1 we assume that longDescs at index 0 is the description. repositoryTaskData.setAttributeValue(RepositoryTaskAttribute.DESCRIPTION, longDescs.get(0) .getText()); repositoryTaskData.addComment(longDescs.get(1)); } else { repositoryTaskData.setAttributeValue(RepositoryTaskAttribute.DESCRIPTION, longDescs.get(1) .getText()); commentNum = 1; longDescs.get(0).setNumber(commentNum); repositoryTaskData.addComment(longDescs.get(0)); } } else if (longDescsSize > 1) { String created_0 = longDescs.get(0).getCreated(); String created_1 = longDescs.get(1).getCreated(); String created_n = longDescs.get(longDescsSize).getCreated(); commentNum = 1; - if (created_0.compareTo(created_1) < 0 && created_0.compareTo(created_n) < 0) { + if (created_0.compareTo(created_1) <= 0 && created_0.compareTo(created_n) < 0) { + // if created_0 is equal to created_1 we assume that longDescs at index 0 is the description. repositoryTaskData.setAttributeValue(RepositoryTaskAttribute.DESCRIPTION, longDescs.get(0) .getText()); if (created_1.compareTo(created_n) < 0) { for (int i = 1; i <= longDescsSize; i++) { longDescs.get(i).setNumber(commentNum++); repositoryTaskData.addComment(longDescs.get(i)); } } else { for (int i = longDescsSize; i > 0; i--) { longDescs.get(i).setNumber(commentNum++); repositoryTaskData.addComment(longDescs.get(i)); } } } else { repositoryTaskData.setAttributeValue(RepositoryTaskAttribute.DESCRIPTION, longDescs.get( longDescsSize).getText()); if (created_0.compareTo(created_1) < 0) { for (int i = 0; i < longDescsSize; i++) { longDescs.get(i).setNumber(commentNum++); repositoryTaskData.addComment(longDescs.get(i)); } } else { for (int i = longDescsSize - 1; i >= 0; i--) { longDescs.get(i).setNumber(commentNum++); repositoryTaskData.addComment(longDescs.get(i)); } } } } RepositoryTaskAttribute numCommentsAttribute = repositoryTaskData.getAttribute(BugzillaReportElement.LONGDESCLENGTH.getKeyString()); if (numCommentsAttribute == null) { numCommentsAttribute = attributeFactory.createAttribute(BugzillaReportElement.LONGDESCLENGTH.getKeyString()); numCommentsAttribute.setValue("" + repositoryTaskData.getComments().size()); repositoryTaskData.addAttribute(BugzillaReportElement.LONGDESCLENGTH.getKeyString(), numCommentsAttribute); } else { numCommentsAttribute.setValue("" + repositoryTaskData.getComments().size()); } // Set the creator name on all attachments for (RepositoryAttachment attachment : repositoryTaskData.getAttachments()) { TaskComment taskComment = attachIdToComment.get(attachment.getId()); if (taskComment != null) { attachment.setCreator(taskComment.getAuthor()); } attachment.setAttributeValue(RepositoryTaskAttribute.ATTACHMENT_URL, repositoryTaskData.getRepositoryUrl() + IBugzillaConstants.URL_GET_ATTACHMENT_SUFFIX + attachment.getId()); attachment.setRepositoryKind(repositoryTaskData.getConnectorKind()); attachment.setRepositoryUrl(repositoryTaskData.getRepositoryUrl()); attachment.setTaskId(repositoryTaskData.getTaskId()); } collector.accept(repositoryTaskData); break; case BLOCKED: case DEPENDSON: RepositoryTaskAttribute dependancyAttribute = repositoryTaskData.getAttribute(tag.getKeyString()); if (dependancyAttribute == null) { dependancyAttribute = attributeFactory.createAttribute(tag.getKeyString()); dependancyAttribute.setValue(parsedText); repositoryTaskData.addAttribute(tag.getKeyString(), dependancyAttribute); } else { if (dependancyAttribute.getValue().equals("")) { dependancyAttribute.setValue(parsedText); } else { dependancyAttribute.setValue(dependancyAttribute.getValue() + ", " + parsedText); } } break; // All others added as report attribute default: RepositoryTaskAttribute attribute = repositoryTaskData.getAttribute(tag.getKeyString()); if (attribute == null) { attribute = attributeFactory.createAttribute(tag.getKeyString()); attribute.setValue(parsedText); repositoryTaskData.addAttribute(tag.getKeyString(), attribute); } else { attribute.addValue(parsedText); } break; } } /** determines attachment id from comment */ private void parseAttachment(TaskComment taskComment, String commentText) { String attachmentID = ""; if (commentText.startsWith(COMMENT_ATTACHMENT_STRING)) { int endIndex = commentText.indexOf(")"); if (endIndex > 0 && endIndex < commentText.length()) { attachmentID = commentText.substring(COMMENT_ATTACHMENT_STRING.length(), endIndex); if (!attachmentID.equals("")) { taskComment.setHasAttachment(true); taskComment.setAttachmentId(attachmentID); attachIdToComment.put(attachmentID, taskComment); } } } } }
false
true
public void endElement(String uri, String localName, String qName) throws SAXException { String parsedText = characters.toString(); if (localName.startsWith(BugzillaCustomField.CUSTOM_FIELD_PREFIX)) { RepositoryTaskAttribute attribute = repositoryTaskData.getAttribute(localName); if (attribute == null) { String desc = "???"; for (BugzillaCustomField bugzillaCustomField : customFields) { if (localName.equals(bugzillaCustomField.getName())) { desc = bugzillaCustomField.getDescription(); } } RepositoryTaskAttribute newattribute = new RepositoryTaskAttribute(localName, desc, true); newattribute.setReadOnly(false); newattribute.setValue(parsedText); repositoryTaskData.addAttribute(localName, newattribute); } else { attribute.addValue(parsedText); } } BugzillaReportElement tag = BugzillaReportElement.UNKNOWN; try { tag = BugzillaReportElement.valueOf(localName.trim().toUpperCase(Locale.ENGLISH)); } catch (RuntimeException e) { if (e instanceof IllegalArgumentException) { // ignore unrecognized tags return; } throw e; } switch (tag) { case BUG_ID: { try { repositoryTaskData = taskDataMap.get(parsedText.trim()); if (repositoryTaskData == null) { errorMessage = parsedText + " id not found."; } } catch (Exception e) { errorMessage = "Bug id from server did not match requested id."; } RepositoryTaskAttribute attr = repositoryTaskData.getAttribute(tag.getKeyString()); if (attr == null) { attr = attributeFactory.createAttribute(tag.getKeyString()); repositoryTaskData.addAttribute(tag.getKeyString(), attr); } attr.setValue(parsedText); break; } // Comment attributes case WHO: if (taskComment != null) { RepositoryTaskAttribute attr = attributeFactory.createAttribute(tag.getKeyString()); attr.setValue(parsedText); taskComment.addAttribute(tag.getKeyString(), attr); } break; case BUG_WHEN: if (taskComment != null) { RepositoryTaskAttribute attr = attributeFactory.createAttribute(tag.getKeyString()); attr.setValue(parsedText); taskComment.addAttribute(tag.getKeyString(), attr); } break; case THETEXT: if (taskComment != null) { RepositoryTaskAttribute attr = attributeFactory.createAttribute(tag.getKeyString()); attr.setValue(parsedText); taskComment.addAttribute(tag.getKeyString(), attr); // Check for attachment parseAttachment(taskComment, parsedText); } break; case LONG_DESC: if (taskComment != null) { longDescs.add(taskComment); } break; // Attachment attributes case ATTACHID: case DATE: case DESC: case FILENAME: case CTYPE: case TYPE: case SIZE: if (attachment != null) { RepositoryTaskAttribute attr = attributeFactory.createAttribute(tag.getKeyString()); attr.setValue(parsedText); attachment.addAttribute(tag.getKeyString(), attr); } break; case DATA: break; case ATTACHMENT: if (attachment != null) { repositoryTaskData.addAttachment(attachment); } break; // IGNORED ELEMENTS // case REPORTER_ACCESSIBLE: // case CLASSIFICATION_ID: // case CLASSIFICATION: // case CCLIST_ACCESSIBLE: // case EVERCONFIRMED: case BUGZILLA: break; // Considering solution for bug#198714 // case DELTA_TS: // RepositoryTaskAttribute delta_ts_attribute = repositoryTaskData.getAttribute(tag.getKeyString()); // if (delta_ts_attribute == null) { // delta_ts_attribute = attributeFactory.createAttribute(tag.getKeyString()); // repositoryTaskData.addAttribute(tag.getKeyString(), delta_ts_attribute); // } // delta_ts_attribute.setValue(BugzillaClient.stripTimeZone(parsedText)); // break; case BUG: // Reached end of bug. Need to set LONGDESCLENGTH to number of // comments int longDescsSize = longDescs.size() - 1; if (longDescsSize == 0) { repositoryTaskData.setAttributeValue(RepositoryTaskAttribute.DESCRIPTION, longDescs.get(0).getText()); } else if (longDescsSize == 1) { if (longDescs.get(0).getCreated().compareTo(longDescs.get(1).getCreated()) < 0) { repositoryTaskData.setAttributeValue(RepositoryTaskAttribute.DESCRIPTION, longDescs.get(0) .getText()); repositoryTaskData.addComment(longDescs.get(1)); } else { repositoryTaskData.setAttributeValue(RepositoryTaskAttribute.DESCRIPTION, longDescs.get(1) .getText()); commentNum = 1; longDescs.get(0).setNumber(commentNum); repositoryTaskData.addComment(longDescs.get(0)); } } else if (longDescsSize > 1) { String created_0 = longDescs.get(0).getCreated(); String created_1 = longDescs.get(1).getCreated(); String created_n = longDescs.get(longDescsSize).getCreated(); commentNum = 1; if (created_0.compareTo(created_1) < 0 && created_0.compareTo(created_n) < 0) { repositoryTaskData.setAttributeValue(RepositoryTaskAttribute.DESCRIPTION, longDescs.get(0) .getText()); if (created_1.compareTo(created_n) < 0) { for (int i = 1; i <= longDescsSize; i++) { longDescs.get(i).setNumber(commentNum++); repositoryTaskData.addComment(longDescs.get(i)); } } else { for (int i = longDescsSize; i > 0; i--) { longDescs.get(i).setNumber(commentNum++); repositoryTaskData.addComment(longDescs.get(i)); } } } else { repositoryTaskData.setAttributeValue(RepositoryTaskAttribute.DESCRIPTION, longDescs.get( longDescsSize).getText()); if (created_0.compareTo(created_1) < 0) { for (int i = 0; i < longDescsSize; i++) { longDescs.get(i).setNumber(commentNum++); repositoryTaskData.addComment(longDescs.get(i)); } } else { for (int i = longDescsSize - 1; i >= 0; i--) { longDescs.get(i).setNumber(commentNum++); repositoryTaskData.addComment(longDescs.get(i)); } } } } RepositoryTaskAttribute numCommentsAttribute = repositoryTaskData.getAttribute(BugzillaReportElement.LONGDESCLENGTH.getKeyString()); if (numCommentsAttribute == null) { numCommentsAttribute = attributeFactory.createAttribute(BugzillaReportElement.LONGDESCLENGTH.getKeyString()); numCommentsAttribute.setValue("" + repositoryTaskData.getComments().size()); repositoryTaskData.addAttribute(BugzillaReportElement.LONGDESCLENGTH.getKeyString(), numCommentsAttribute); } else { numCommentsAttribute.setValue("" + repositoryTaskData.getComments().size()); } // Set the creator name on all attachments for (RepositoryAttachment attachment : repositoryTaskData.getAttachments()) { TaskComment taskComment = attachIdToComment.get(attachment.getId()); if (taskComment != null) { attachment.setCreator(taskComment.getAuthor()); } attachment.setAttributeValue(RepositoryTaskAttribute.ATTACHMENT_URL, repositoryTaskData.getRepositoryUrl() + IBugzillaConstants.URL_GET_ATTACHMENT_SUFFIX + attachment.getId()); attachment.setRepositoryKind(repositoryTaskData.getConnectorKind()); attachment.setRepositoryUrl(repositoryTaskData.getRepositoryUrl()); attachment.setTaskId(repositoryTaskData.getTaskId()); } collector.accept(repositoryTaskData); break; case BLOCKED: case DEPENDSON: RepositoryTaskAttribute dependancyAttribute = repositoryTaskData.getAttribute(tag.getKeyString()); if (dependancyAttribute == null) { dependancyAttribute = attributeFactory.createAttribute(tag.getKeyString()); dependancyAttribute.setValue(parsedText); repositoryTaskData.addAttribute(tag.getKeyString(), dependancyAttribute); } else { if (dependancyAttribute.getValue().equals("")) { dependancyAttribute.setValue(parsedText); } else { dependancyAttribute.setValue(dependancyAttribute.getValue() + ", " + parsedText); } } break; // All others added as report attribute default: RepositoryTaskAttribute attribute = repositoryTaskData.getAttribute(tag.getKeyString()); if (attribute == null) { attribute = attributeFactory.createAttribute(tag.getKeyString()); attribute.setValue(parsedText); repositoryTaskData.addAttribute(tag.getKeyString(), attribute); } else { attribute.addValue(parsedText); } break; } }
public void endElement(String uri, String localName, String qName) throws SAXException { String parsedText = characters.toString(); if (localName.startsWith(BugzillaCustomField.CUSTOM_FIELD_PREFIX)) { RepositoryTaskAttribute attribute = repositoryTaskData.getAttribute(localName); if (attribute == null) { String desc = "???"; for (BugzillaCustomField bugzillaCustomField : customFields) { if (localName.equals(bugzillaCustomField.getName())) { desc = bugzillaCustomField.getDescription(); } } RepositoryTaskAttribute newattribute = new RepositoryTaskAttribute(localName, desc, true); newattribute.setReadOnly(false); newattribute.setValue(parsedText); repositoryTaskData.addAttribute(localName, newattribute); } else { attribute.addValue(parsedText); } } BugzillaReportElement tag = BugzillaReportElement.UNKNOWN; try { tag = BugzillaReportElement.valueOf(localName.trim().toUpperCase(Locale.ENGLISH)); } catch (RuntimeException e) { if (e instanceof IllegalArgumentException) { // ignore unrecognized tags return; } throw e; } switch (tag) { case BUG_ID: { try { repositoryTaskData = taskDataMap.get(parsedText.trim()); if (repositoryTaskData == null) { errorMessage = parsedText + " id not found."; } } catch (Exception e) { errorMessage = "Bug id from server did not match requested id."; } RepositoryTaskAttribute attr = repositoryTaskData.getAttribute(tag.getKeyString()); if (attr == null) { attr = attributeFactory.createAttribute(tag.getKeyString()); repositoryTaskData.addAttribute(tag.getKeyString(), attr); } attr.setValue(parsedText); break; } // Comment attributes case WHO: if (taskComment != null) { RepositoryTaskAttribute attr = attributeFactory.createAttribute(tag.getKeyString()); attr.setValue(parsedText); taskComment.addAttribute(tag.getKeyString(), attr); } break; case BUG_WHEN: if (taskComment != null) { RepositoryTaskAttribute attr = attributeFactory.createAttribute(tag.getKeyString()); attr.setValue(parsedText); taskComment.addAttribute(tag.getKeyString(), attr); } break; case THETEXT: if (taskComment != null) { RepositoryTaskAttribute attr = attributeFactory.createAttribute(tag.getKeyString()); attr.setValue(parsedText); taskComment.addAttribute(tag.getKeyString(), attr); // Check for attachment parseAttachment(taskComment, parsedText); } break; case LONG_DESC: if (taskComment != null) { longDescs.add(taskComment); } break; // Attachment attributes case ATTACHID: case DATE: case DESC: case FILENAME: case CTYPE: case TYPE: case SIZE: if (attachment != null) { RepositoryTaskAttribute attr = attributeFactory.createAttribute(tag.getKeyString()); attr.setValue(parsedText); attachment.addAttribute(tag.getKeyString(), attr); } break; case DATA: break; case ATTACHMENT: if (attachment != null) { repositoryTaskData.addAttachment(attachment); } break; // IGNORED ELEMENTS // case REPORTER_ACCESSIBLE: // case CLASSIFICATION_ID: // case CLASSIFICATION: // case CCLIST_ACCESSIBLE: // case EVERCONFIRMED: case BUGZILLA: break; // Considering solution for bug#198714 // case DELTA_TS: // RepositoryTaskAttribute delta_ts_attribute = repositoryTaskData.getAttribute(tag.getKeyString()); // if (delta_ts_attribute == null) { // delta_ts_attribute = attributeFactory.createAttribute(tag.getKeyString()); // repositoryTaskData.addAttribute(tag.getKeyString(), delta_ts_attribute); // } // delta_ts_attribute.setValue(BugzillaClient.stripTimeZone(parsedText)); // break; case BUG: // Reached end of bug. Need to set LONGDESCLENGTH to number of // comments int longDescsSize = longDescs.size() - 1; if (longDescsSize == 0) { repositoryTaskData.setAttributeValue(RepositoryTaskAttribute.DESCRIPTION, longDescs.get(0).getText()); } else if (longDescsSize == 1) { if (longDescs.get(0).getCreated().compareTo(longDescs.get(1).getCreated()) <= 0) { // if created_0 is equal to created_1 we assume that longDescs at index 0 is the description. repositoryTaskData.setAttributeValue(RepositoryTaskAttribute.DESCRIPTION, longDescs.get(0) .getText()); repositoryTaskData.addComment(longDescs.get(1)); } else { repositoryTaskData.setAttributeValue(RepositoryTaskAttribute.DESCRIPTION, longDescs.get(1) .getText()); commentNum = 1; longDescs.get(0).setNumber(commentNum); repositoryTaskData.addComment(longDescs.get(0)); } } else if (longDescsSize > 1) { String created_0 = longDescs.get(0).getCreated(); String created_1 = longDescs.get(1).getCreated(); String created_n = longDescs.get(longDescsSize).getCreated(); commentNum = 1; if (created_0.compareTo(created_1) <= 0 && created_0.compareTo(created_n) < 0) { // if created_0 is equal to created_1 we assume that longDescs at index 0 is the description. repositoryTaskData.setAttributeValue(RepositoryTaskAttribute.DESCRIPTION, longDescs.get(0) .getText()); if (created_1.compareTo(created_n) < 0) { for (int i = 1; i <= longDescsSize; i++) { longDescs.get(i).setNumber(commentNum++); repositoryTaskData.addComment(longDescs.get(i)); } } else { for (int i = longDescsSize; i > 0; i--) { longDescs.get(i).setNumber(commentNum++); repositoryTaskData.addComment(longDescs.get(i)); } } } else { repositoryTaskData.setAttributeValue(RepositoryTaskAttribute.DESCRIPTION, longDescs.get( longDescsSize).getText()); if (created_0.compareTo(created_1) < 0) { for (int i = 0; i < longDescsSize; i++) { longDescs.get(i).setNumber(commentNum++); repositoryTaskData.addComment(longDescs.get(i)); } } else { for (int i = longDescsSize - 1; i >= 0; i--) { longDescs.get(i).setNumber(commentNum++); repositoryTaskData.addComment(longDescs.get(i)); } } } } RepositoryTaskAttribute numCommentsAttribute = repositoryTaskData.getAttribute(BugzillaReportElement.LONGDESCLENGTH.getKeyString()); if (numCommentsAttribute == null) { numCommentsAttribute = attributeFactory.createAttribute(BugzillaReportElement.LONGDESCLENGTH.getKeyString()); numCommentsAttribute.setValue("" + repositoryTaskData.getComments().size()); repositoryTaskData.addAttribute(BugzillaReportElement.LONGDESCLENGTH.getKeyString(), numCommentsAttribute); } else { numCommentsAttribute.setValue("" + repositoryTaskData.getComments().size()); } // Set the creator name on all attachments for (RepositoryAttachment attachment : repositoryTaskData.getAttachments()) { TaskComment taskComment = attachIdToComment.get(attachment.getId()); if (taskComment != null) { attachment.setCreator(taskComment.getAuthor()); } attachment.setAttributeValue(RepositoryTaskAttribute.ATTACHMENT_URL, repositoryTaskData.getRepositoryUrl() + IBugzillaConstants.URL_GET_ATTACHMENT_SUFFIX + attachment.getId()); attachment.setRepositoryKind(repositoryTaskData.getConnectorKind()); attachment.setRepositoryUrl(repositoryTaskData.getRepositoryUrl()); attachment.setTaskId(repositoryTaskData.getTaskId()); } collector.accept(repositoryTaskData); break; case BLOCKED: case DEPENDSON: RepositoryTaskAttribute dependancyAttribute = repositoryTaskData.getAttribute(tag.getKeyString()); if (dependancyAttribute == null) { dependancyAttribute = attributeFactory.createAttribute(tag.getKeyString()); dependancyAttribute.setValue(parsedText); repositoryTaskData.addAttribute(tag.getKeyString(), dependancyAttribute); } else { if (dependancyAttribute.getValue().equals("")) { dependancyAttribute.setValue(parsedText); } else { dependancyAttribute.setValue(dependancyAttribute.getValue() + ", " + parsedText); } } break; // All others added as report attribute default: RepositoryTaskAttribute attribute = repositoryTaskData.getAttribute(tag.getKeyString()); if (attribute == null) { attribute = attributeFactory.createAttribute(tag.getKeyString()); attribute.setValue(parsedText); repositoryTaskData.addAttribute(tag.getKeyString(), attribute); } else { attribute.addValue(parsedText); } break; } }
diff --git a/com.mountainminds.eclemma.ui/src/com/mountainminds/eclemma/internal/ui/UIPreferences.java b/com.mountainminds.eclemma.ui/src/com/mountainminds/eclemma/internal/ui/UIPreferences.java index 2d78fc0..dd6f9bc 100644 --- a/com.mountainminds.eclemma.ui/src/com/mountainminds/eclemma/internal/ui/UIPreferences.java +++ b/com.mountainminds.eclemma.ui/src/com/mountainminds/eclemma/internal/ui/UIPreferences.java @@ -1,116 +1,116 @@ /******************************************************************************* * Copyright (c) 2006, 2011 Mountainminds GmbH & Co. KG and Contributors * 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: * Marc R. Hoffmann - initial API and implementation * ******************************************************************************/ package com.mountainminds.eclemma.internal.ui; import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer; import org.eclipse.jface.preference.IPreferenceStore; import com.mountainminds.eclemma.core.ICorePreferences; /** * Constants and initializer for the preference store. */ public class UIPreferences extends AbstractPreferenceInitializer { public static final String PREF_SHOW_COVERAGE_VIEW = EclEmmaUIPlugin.ID + ".show_coverage_view"; //$NON-NLS-1$ public static final String PREF_RESET_ON_DUMP = EclEmmaUIPlugin.ID + ".reset_on_dump"; //$NON-NLS-1$ public static final String PREF_ACTICATE_NEW_SESSIONS = EclEmmaUIPlugin.ID + ".activate_new_sessions"; //$NON-NLS-1$ public static final String PREF_DEFAULT_SCOPE_SOURCE_FOLDERS_ONLY = EclEmmaUIPlugin.ID + ".default_scope_source_folders_only"; //$NON-NLS-1$ public static final String PREF_DEFAULT_SCOPE_SAME_PROJECT_ONLY = EclEmmaUIPlugin.ID + ".default_scope_same_project_only"; //$NON-NLS-1$ public static final String PREF_DEFAULT_SCOPE_FILTER = EclEmmaUIPlugin.ID + ".default_scope_filter"; //$NON-NLS-1$ public static final String PREF_AUTO_REMOVE_SESSIONS = EclEmmaUIPlugin.ID + ".auto_remove_sessions"; //$NON-NLS-1$ public static final String PREF_AGENT_INCLUDES = EclEmmaUIPlugin.ID + ".agent_includes"; //$NON-NLS-1$ public static final String PREF_AGENT_EXCLUDES = EclEmmaUIPlugin.ID + ".agent_excludes"; //$NON-NLS-1$ public static final String PREF_AGENT_EXCLCLASSLOADER = EclEmmaUIPlugin.ID + ".agent_exclclassloader"; //$NON-NLS-1$ public static final ICorePreferences CORE_PREFERENCES = new ICorePreferences() { public boolean getActivateNewSessions() { return getPreferenceStore().getBoolean(PREF_ACTICATE_NEW_SESSIONS); } public boolean getAutoRemoveSessions() { return getPreferenceStore().getBoolean(PREF_AUTO_REMOVE_SESSIONS); } public boolean getDefaultScopeSourceFoldersOnly() { return getPreferenceStore().getBoolean( PREF_DEFAULT_SCOPE_SOURCE_FOLDERS_ONLY); } public boolean getDefaultScopeSameProjectOnly() { return getPreferenceStore().getBoolean( PREF_DEFAULT_SCOPE_SAME_PROJECT_ONLY); } public String getDefaultScopeFilter() { return getPreferenceStore().getString(PREF_DEFAULT_SCOPE_FILTER); } public String getAgentIncludes() { return getPreferenceStore().getString(PREF_AGENT_INCLUDES); } public String getAgentExcludes() { return getPreferenceStore().getString(PREF_AGENT_EXCLUDES); } public String getAgentExclClassloader() { return getPreferenceStore().getString(PREF_AGENT_EXCLCLASSLOADER); } }; public void initializeDefaultPreferences() { IPreferenceStore pref = getPreferenceStore(); pref.setDefault(PREF_SHOW_COVERAGE_VIEW, true); - pref.setDefault(PREF_SHOW_COVERAGE_VIEW, false); + pref.setDefault(PREF_RESET_ON_DUMP, false); pref.setDefault(PREF_ACTICATE_NEW_SESSIONS, ICorePreferences.DEFAULT.getActivateNewSessions()); pref.setDefault(PREF_AUTO_REMOVE_SESSIONS, ICorePreferences.DEFAULT.getAutoRemoveSessions()); pref.setDefault(PREF_DEFAULT_SCOPE_SOURCE_FOLDERS_ONLY, ICorePreferences.DEFAULT.getDefaultScopeSourceFoldersOnly()); pref.setDefault(PREF_DEFAULT_SCOPE_SAME_PROJECT_ONLY, ICorePreferences.DEFAULT.getDefaultScopeSameProjectOnly()); pref.setDefault(PREF_DEFAULT_SCOPE_FILTER, ICorePreferences.DEFAULT.getDefaultScopeFilter()); pref.setDefault(PREF_AGENT_INCLUDES, ICorePreferences.DEFAULT.getAgentIncludes()); pref.setDefault(PREF_AGENT_EXCLUDES, ICorePreferences.DEFAULT.getAgentExcludes()); pref.setDefault(PREF_AGENT_EXCLCLASSLOADER, ICorePreferences.DEFAULT.getAgentExclClassloader()); } private static IPreferenceStore getPreferenceStore() { return EclEmmaUIPlugin.getInstance().getPreferenceStore(); } }
true
true
public void initializeDefaultPreferences() { IPreferenceStore pref = getPreferenceStore(); pref.setDefault(PREF_SHOW_COVERAGE_VIEW, true); pref.setDefault(PREF_SHOW_COVERAGE_VIEW, false); pref.setDefault(PREF_ACTICATE_NEW_SESSIONS, ICorePreferences.DEFAULT.getActivateNewSessions()); pref.setDefault(PREF_AUTO_REMOVE_SESSIONS, ICorePreferences.DEFAULT.getAutoRemoveSessions()); pref.setDefault(PREF_DEFAULT_SCOPE_SOURCE_FOLDERS_ONLY, ICorePreferences.DEFAULT.getDefaultScopeSourceFoldersOnly()); pref.setDefault(PREF_DEFAULT_SCOPE_SAME_PROJECT_ONLY, ICorePreferences.DEFAULT.getDefaultScopeSameProjectOnly()); pref.setDefault(PREF_DEFAULT_SCOPE_FILTER, ICorePreferences.DEFAULT.getDefaultScopeFilter()); pref.setDefault(PREF_AGENT_INCLUDES, ICorePreferences.DEFAULT.getAgentIncludes()); pref.setDefault(PREF_AGENT_EXCLUDES, ICorePreferences.DEFAULT.getAgentExcludes()); pref.setDefault(PREF_AGENT_EXCLCLASSLOADER, ICorePreferences.DEFAULT.getAgentExclClassloader()); }
public void initializeDefaultPreferences() { IPreferenceStore pref = getPreferenceStore(); pref.setDefault(PREF_SHOW_COVERAGE_VIEW, true); pref.setDefault(PREF_RESET_ON_DUMP, false); pref.setDefault(PREF_ACTICATE_NEW_SESSIONS, ICorePreferences.DEFAULT.getActivateNewSessions()); pref.setDefault(PREF_AUTO_REMOVE_SESSIONS, ICorePreferences.DEFAULT.getAutoRemoveSessions()); pref.setDefault(PREF_DEFAULT_SCOPE_SOURCE_FOLDERS_ONLY, ICorePreferences.DEFAULT.getDefaultScopeSourceFoldersOnly()); pref.setDefault(PREF_DEFAULT_SCOPE_SAME_PROJECT_ONLY, ICorePreferences.DEFAULT.getDefaultScopeSameProjectOnly()); pref.setDefault(PREF_DEFAULT_SCOPE_FILTER, ICorePreferences.DEFAULT.getDefaultScopeFilter()); pref.setDefault(PREF_AGENT_INCLUDES, ICorePreferences.DEFAULT.getAgentIncludes()); pref.setDefault(PREF_AGENT_EXCLUDES, ICorePreferences.DEFAULT.getAgentExcludes()); pref.setDefault(PREF_AGENT_EXCLCLASSLOADER, ICorePreferences.DEFAULT.getAgentExclClassloader()); }
diff --git a/EasyShopperTest/src/com/google/code/easyshopper/utility/CameraUtilsTest.java b/EasyShopperTest/src/com/google/code/easyshopper/utility/CameraUtilsTest.java index 73e124f..e7e6c70 100644 --- a/EasyShopperTest/src/com/google/code/easyshopper/utility/CameraUtilsTest.java +++ b/EasyShopperTest/src/com/google/code/easyshopper/utility/CameraUtilsTest.java @@ -1,14 +1,14 @@ package com.google.code.easyshopper.utility; import android.net.Uri; import android.test.AndroidTestCase; import com.google.code.easyshopper.utility.CameraUtils; public class CameraUtilsTest extends AndroidTestCase { public void testPathComposition() { Uri imagePath = CameraUtils.getImagePath("another_path"); Uri expUri = new Uri.Builder().scheme("file").appendEncodedPath("//sdcard/Android/data/com.gmail.gulino.marco.easyshopper/another_path").build(); - assertEquals(expUri, imagePath); +// assertEquals(expUri, imagePath); } }
true
true
public void testPathComposition() { Uri imagePath = CameraUtils.getImagePath("another_path"); Uri expUri = new Uri.Builder().scheme("file").appendEncodedPath("//sdcard/Android/data/com.gmail.gulino.marco.easyshopper/another_path").build(); assertEquals(expUri, imagePath); }
public void testPathComposition() { Uri imagePath = CameraUtils.getImagePath("another_path"); Uri expUri = new Uri.Builder().scheme("file").appendEncodedPath("//sdcard/Android/data/com.gmail.gulino.marco.easyshopper/another_path").build(); // assertEquals(expUri, imagePath); }
diff --git a/src/main/java/net/pterodactylus/sone/web/ajax/GetStatusAjaxPage.java b/src/main/java/net/pterodactylus/sone/web/ajax/GetStatusAjaxPage.java index b28b82e9..4e2049eb 100644 --- a/src/main/java/net/pterodactylus/sone/web/ajax/GetStatusAjaxPage.java +++ b/src/main/java/net/pterodactylus/sone/web/ajax/GetStatusAjaxPage.java @@ -1,195 +1,204 @@ /* * Sone - GetStatusAjaxPage.java - Copyright © 2010 David Roden * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.pterodactylus.sone.web.ajax; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import net.pterodactylus.sone.data.Post; import net.pterodactylus.sone.data.Reply; import net.pterodactylus.sone.data.Sone; import net.pterodactylus.sone.notify.ListNotificationFilters; import net.pterodactylus.sone.template.SoneAccessor; import net.pterodactylus.sone.web.WebInterface; import net.pterodactylus.util.filter.Filter; import net.pterodactylus.util.filter.Filters; import net.pterodactylus.util.json.JsonArray; import net.pterodactylus.util.json.JsonObject; import net.pterodactylus.util.notify.Notification; /** * The “get status” AJAX handler returns all information that is necessary to * update the web interface in real-time. * * @author <a href="mailto:[email protected]">David ‘Bombe’ Roden</a> */ public class GetStatusAjaxPage extends JsonPage { /** Date formatter. */ private static final DateFormat dateFormat = new SimpleDateFormat("MMM d, yyyy, HH:mm:ss"); /** * Creates a new “get status” AJAX handler. * * @param webInterface * The Sone web interface */ public GetStatusAjaxPage(WebInterface webInterface) { super("getStatus.ajax", webInterface); } /** * {@inheritDoc} */ @Override protected JsonObject createJsonObject(Request request) { final Sone currentSone = getCurrentSone(request.getToadletContext(), false); /* load Sones. */ - boolean loadAllSones = Boolean.parseBoolean(request.getHttpRequest().getParam("loadAllSones", "true")); + boolean loadAllSones = Boolean.parseBoolean(request.getHttpRequest().getParam("loadAllSones", "false")); Set<Sone> sones = new HashSet<Sone>(Collections.singleton(getCurrentSone(request.getToadletContext(), false))); if (loadAllSones) { sones.addAll(webInterface.getCore().getSones()); + } else { + String loadSoneIds = request.getHttpRequest().getParam("soneIds"); + if (loadSoneIds.length() > 0) { + String[] soneIds = loadSoneIds.split(","); + for (String soneId : soneIds) { + /* just add it, we skip null further down. */ + sones.add(webInterface.getCore().getSone(soneId, false)); + } + } } JsonArray jsonSones = new JsonArray(); for (Sone sone : sones) { if (sone == null) { continue; } JsonObject jsonSone = createJsonSone(sone); jsonSones.add(jsonSone); } /* load notifications. */ List<Notification> notifications = ListNotificationFilters.filterNotifications(new ArrayList<Notification>(webInterface.getNotifications().getNotifications()), currentSone); Collections.sort(notifications, Notification.LAST_UPDATED_TIME_SORTER); JsonArray jsonNotificationInformations = new JsonArray(); for (Notification notification : notifications) { jsonNotificationInformations.add(createJsonNotificationInformation(notification)); } /* load new posts. */ Set<Post> newPosts = webInterface.getNewPosts(); if (currentSone != null) { newPosts = Filters.filteredSet(newPosts, new Filter<Post>() { @Override public boolean filterObject(Post post) { return ListNotificationFilters.isPostVisible(currentSone, post); } }); } JsonArray jsonPosts = new JsonArray(); for (Post post : newPosts) { JsonObject jsonPost = new JsonObject(); jsonPost.put("id", post.getId()); jsonPost.put("sone", post.getSone().getId()); jsonPost.put("recipient", (post.getRecipient() != null) ? post.getRecipient().getId() : null); jsonPost.put("time", post.getTime()); jsonPosts.add(jsonPost); } /* load new replies. */ Set<Reply> newReplies = webInterface.getNewReplies(); if (currentSone != null) { newReplies = Filters.filteredSet(newReplies, new Filter<Reply>() { @Override public boolean filterObject(Reply reply) { return ListNotificationFilters.isReplyVisible(currentSone, reply); } }); } JsonArray jsonReplies = new JsonArray(); for (Reply reply : newReplies) { JsonObject jsonReply = new JsonObject(); jsonReply.put("id", reply.getId()); jsonReply.put("sone", reply.getSone().getId()); jsonReply.put("post", reply.getPost().getId()); jsonReply.put("postSone", reply.getPost().getSone().getId()); jsonReplies.add(jsonReply); } return createSuccessJsonObject().put("sones", jsonSones).put("notifications", jsonNotificationInformations).put("newPosts", jsonPosts).put("newReplies", jsonReplies); } /** * {@inheritDoc} */ @Override protected boolean needsFormPassword() { return false; } /** * {@inheritDoc} */ @Override protected boolean requiresLogin() { return false; } // // PRIVATE METHODS // /** * Creates a JSON object from the given Sone. * * @param sone * The Sone to convert to a JSON object * @return The JSON representation of the given Sone */ private JsonObject createJsonSone(Sone sone) { JsonObject jsonSone = new JsonObject(); jsonSone.put("id", sone.getId()); jsonSone.put("name", SoneAccessor.getNiceName(sone)); jsonSone.put("local", sone.getInsertUri() != null); jsonSone.put("status", webInterface.getCore().getSoneStatus(sone).name()); jsonSone.put("modified", webInterface.getCore().isModifiedSone(sone)); jsonSone.put("locked", webInterface.getCore().isLocked(sone)); jsonSone.put("lastUpdatedUnknown", sone.getTime() == 0); synchronized (dateFormat) { jsonSone.put("lastUpdated", dateFormat.format(new Date(sone.getTime()))); } jsonSone.put("lastUpdatedText", GetTimesAjaxPage.getTime(webInterface, System.currentTimeMillis() - sone.getTime()).getText()); return jsonSone; } /** * Creates a JSON object that only contains the ID and the last-updated time * of the given notification. * * @see Notification#getId() * @see Notification#getLastUpdatedTime() * @param notification * The notification * @return A JSON object containing the notification ID and last-updated * time */ private JsonObject createJsonNotificationInformation(Notification notification) { JsonObject jsonNotification = new JsonObject(); jsonNotification.put("id", notification.getId()); jsonNotification.put("lastUpdatedTime", notification.getLastUpdatedTime()); return jsonNotification; } }
false
true
protected JsonObject createJsonObject(Request request) { final Sone currentSone = getCurrentSone(request.getToadletContext(), false); /* load Sones. */ boolean loadAllSones = Boolean.parseBoolean(request.getHttpRequest().getParam("loadAllSones", "true")); Set<Sone> sones = new HashSet<Sone>(Collections.singleton(getCurrentSone(request.getToadletContext(), false))); if (loadAllSones) { sones.addAll(webInterface.getCore().getSones()); } JsonArray jsonSones = new JsonArray(); for (Sone sone : sones) { if (sone == null) { continue; } JsonObject jsonSone = createJsonSone(sone); jsonSones.add(jsonSone); } /* load notifications. */ List<Notification> notifications = ListNotificationFilters.filterNotifications(new ArrayList<Notification>(webInterface.getNotifications().getNotifications()), currentSone); Collections.sort(notifications, Notification.LAST_UPDATED_TIME_SORTER); JsonArray jsonNotificationInformations = new JsonArray(); for (Notification notification : notifications) { jsonNotificationInformations.add(createJsonNotificationInformation(notification)); } /* load new posts. */ Set<Post> newPosts = webInterface.getNewPosts(); if (currentSone != null) { newPosts = Filters.filteredSet(newPosts, new Filter<Post>() { @Override public boolean filterObject(Post post) { return ListNotificationFilters.isPostVisible(currentSone, post); } }); } JsonArray jsonPosts = new JsonArray(); for (Post post : newPosts) { JsonObject jsonPost = new JsonObject(); jsonPost.put("id", post.getId()); jsonPost.put("sone", post.getSone().getId()); jsonPost.put("recipient", (post.getRecipient() != null) ? post.getRecipient().getId() : null); jsonPost.put("time", post.getTime()); jsonPosts.add(jsonPost); } /* load new replies. */ Set<Reply> newReplies = webInterface.getNewReplies(); if (currentSone != null) { newReplies = Filters.filteredSet(newReplies, new Filter<Reply>() { @Override public boolean filterObject(Reply reply) { return ListNotificationFilters.isReplyVisible(currentSone, reply); } }); } JsonArray jsonReplies = new JsonArray(); for (Reply reply : newReplies) { JsonObject jsonReply = new JsonObject(); jsonReply.put("id", reply.getId()); jsonReply.put("sone", reply.getSone().getId()); jsonReply.put("post", reply.getPost().getId()); jsonReply.put("postSone", reply.getPost().getSone().getId()); jsonReplies.add(jsonReply); } return createSuccessJsonObject().put("sones", jsonSones).put("notifications", jsonNotificationInformations).put("newPosts", jsonPosts).put("newReplies", jsonReplies); }
protected JsonObject createJsonObject(Request request) { final Sone currentSone = getCurrentSone(request.getToadletContext(), false); /* load Sones. */ boolean loadAllSones = Boolean.parseBoolean(request.getHttpRequest().getParam("loadAllSones", "false")); Set<Sone> sones = new HashSet<Sone>(Collections.singleton(getCurrentSone(request.getToadletContext(), false))); if (loadAllSones) { sones.addAll(webInterface.getCore().getSones()); } else { String loadSoneIds = request.getHttpRequest().getParam("soneIds"); if (loadSoneIds.length() > 0) { String[] soneIds = loadSoneIds.split(","); for (String soneId : soneIds) { /* just add it, we skip null further down. */ sones.add(webInterface.getCore().getSone(soneId, false)); } } } JsonArray jsonSones = new JsonArray(); for (Sone sone : sones) { if (sone == null) { continue; } JsonObject jsonSone = createJsonSone(sone); jsonSones.add(jsonSone); } /* load notifications. */ List<Notification> notifications = ListNotificationFilters.filterNotifications(new ArrayList<Notification>(webInterface.getNotifications().getNotifications()), currentSone); Collections.sort(notifications, Notification.LAST_UPDATED_TIME_SORTER); JsonArray jsonNotificationInformations = new JsonArray(); for (Notification notification : notifications) { jsonNotificationInformations.add(createJsonNotificationInformation(notification)); } /* load new posts. */ Set<Post> newPosts = webInterface.getNewPosts(); if (currentSone != null) { newPosts = Filters.filteredSet(newPosts, new Filter<Post>() { @Override public boolean filterObject(Post post) { return ListNotificationFilters.isPostVisible(currentSone, post); } }); } JsonArray jsonPosts = new JsonArray(); for (Post post : newPosts) { JsonObject jsonPost = new JsonObject(); jsonPost.put("id", post.getId()); jsonPost.put("sone", post.getSone().getId()); jsonPost.put("recipient", (post.getRecipient() != null) ? post.getRecipient().getId() : null); jsonPost.put("time", post.getTime()); jsonPosts.add(jsonPost); } /* load new replies. */ Set<Reply> newReplies = webInterface.getNewReplies(); if (currentSone != null) { newReplies = Filters.filteredSet(newReplies, new Filter<Reply>() { @Override public boolean filterObject(Reply reply) { return ListNotificationFilters.isReplyVisible(currentSone, reply); } }); } JsonArray jsonReplies = new JsonArray(); for (Reply reply : newReplies) { JsonObject jsonReply = new JsonObject(); jsonReply.put("id", reply.getId()); jsonReply.put("sone", reply.getSone().getId()); jsonReply.put("post", reply.getPost().getId()); jsonReply.put("postSone", reply.getPost().getSone().getId()); jsonReplies.add(jsonReply); } return createSuccessJsonObject().put("sones", jsonSones).put("notifications", jsonNotificationInformations).put("newPosts", jsonPosts).put("newReplies", jsonReplies); }
diff --git a/src/main/java/org/springframework/data/demo/repository/MongoBookShelf.java b/src/main/java/org/springframework/data/demo/repository/MongoBookShelf.java index 08e5a6b..9d4be8f 100644 --- a/src/main/java/org/springframework/data/demo/repository/MongoBookShelf.java +++ b/src/main/java/org/springframework/data/demo/repository/MongoBookShelf.java @@ -1,60 +1,62 @@ package org.springframework.data.demo.repository; import java.util.Collections; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.demo.domain.Author; import org.springframework.data.demo.domain.Book; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.stereotype.Repository; @Repository public class MongoBookShelf implements BookShelf { @Autowired MongoTemplate mongoTemplate; @Override public void add(Book book) { lookUpAuthor(book); mongoTemplate.insert(book); } @Override public void save(Book book) { lookUpAuthor(book); mongoTemplate.save(book); } @Override public Book find(String isbn) { Query query = new Query(Criteria.where("isbn").is(isbn)); return mongoTemplate.findOne(query, Book.class); } @Override public void remove(String isbn) { Query query = new Query(Criteria.where("isbn").is(isbn)); mongoTemplate.remove(query, Book.class); } @Override public List<Book> findAll() { List<Book> books = mongoTemplate.findAll(Book.class); return Collections.unmodifiableList(books); } private void lookUpAuthor(Book book) { if (book.getAuthor() != null) { Query query = new Query(Criteria.where("name").is(book.getAuthor().getName())); Author existing = mongoTemplate.findOne(query ,Author.class); if (existing != null) { book.setAuthor(existing); } - mongoTemplate.insert(book.getAuthor()); + else { + mongoTemplate.insert(book.getAuthor()); + } } } }
true
true
private void lookUpAuthor(Book book) { if (book.getAuthor() != null) { Query query = new Query(Criteria.where("name").is(book.getAuthor().getName())); Author existing = mongoTemplate.findOne(query ,Author.class); if (existing != null) { book.setAuthor(existing); } mongoTemplate.insert(book.getAuthor()); } }
private void lookUpAuthor(Book book) { if (book.getAuthor() != null) { Query query = new Query(Criteria.where("name").is(book.getAuthor().getName())); Author existing = mongoTemplate.findOne(query ,Author.class); if (existing != null) { book.setAuthor(existing); } else { mongoTemplate.insert(book.getAuthor()); } } }
diff --git a/jetty-security/src/main/java/org/eclipse/jetty/security/authentication/FormAuthenticator.java b/jetty-security/src/main/java/org/eclipse/jetty/security/authentication/FormAuthenticator.java index 194888c6..594b8222 100644 --- a/jetty-security/src/main/java/org/eclipse/jetty/security/authentication/FormAuthenticator.java +++ b/jetty-security/src/main/java/org/eclipse/jetty/security/authentication/FormAuthenticator.java @@ -1,369 +1,369 @@ // ======================================================================== // Copyright (c) 2008-2009 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // and Apache License v2.0 which accompanies this distribution. // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // You may elect to redistribute this code under either of these licenses. // ======================================================================== package org.eclipse.jetty.security.authentication; import java.io.IOException; import java.util.Collections; import java.util.Enumeration; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; import javax.servlet.http.HttpSession; import org.eclipse.jetty.http.HttpHeaders; import org.eclipse.jetty.http.security.Constraint; import org.eclipse.jetty.security.Authenticator; import org.eclipse.jetty.security.UserAuthentication; import org.eclipse.jetty.security.ServerAuthException; import org.eclipse.jetty.server.Authentication; import org.eclipse.jetty.server.UserIdentity; import org.eclipse.jetty.server.Authentication.User; import org.eclipse.jetty.util.StringUtil; import org.eclipse.jetty.util.URIUtil; import org.eclipse.jetty.util.log.Log; /** * FORM Authenticator. * * The form authenticator redirects unauthenticated requests to a log page * which should use a form to gather username/password from the user and send them * to the /j_security_check URI within the context. FormAuthentication is intended * to be used together with the {@link SessionCachingAuthenticator} so that the * auth results may be associated with the session. * * This authenticator implements form authentication using dispatchers unless * the {@link #__FORM_DISPATCH} init parameters is set to false. * */ public class FormAuthenticator extends LoginAuthenticator { public final static String __FORM_LOGIN_PAGE="org.eclipse.jetty.security.form_login_page"; public final static String __FORM_ERROR_PAGE="org.eclipse.jetty.security.form_error_page"; public final static String __FORM_DISPATCH="org.eclipse.jetty.security.dispatch"; public final static String __J_URI = "org.eclipse.jetty.util.URI"; public final static String __J_AUTHENTICATED = "org.eclipse.jetty.server.Auth"; public final static String __J_SECURITY_CHECK = "/j_security_check"; public final static String __J_USERNAME = "j_username"; public final static String __J_PASSWORD = "j_password"; private String _formErrorPage; private String _formErrorPath; private String _formLoginPage; private String _formLoginPath; private boolean _dispatch; public FormAuthenticator() { } /* ------------------------------------------------------------ */ public FormAuthenticator(String login,String error) { if (login!=null) setLoginPage(login); if (error!=null) setErrorPage(error); } /* ------------------------------------------------------------ */ /** * @see org.eclipse.jetty.security.authentication.LoginAuthenticator#setConfiguration(org.eclipse.jetty.security.Authenticator.Configuration) */ @Override public void setConfiguration(Configuration configuration) { super.setConfiguration(configuration); String login=configuration.getInitParameter(FormAuthenticator.__FORM_LOGIN_PAGE); if (login!=null) setLoginPage(login); String error=configuration.getInitParameter(FormAuthenticator.__FORM_ERROR_PAGE); if (error!=null) setErrorPage(error); String dispatch=configuration.getInitParameter(FormAuthenticator.__FORM_DISPATCH); _dispatch=dispatch==null || Boolean.getBoolean(dispatch); } /* ------------------------------------------------------------ */ public String getAuthMethod() { return Constraint.__FORM_AUTH; } /* ------------------------------------------------------------ */ private void setLoginPage(String path) { if (!path.startsWith("/")) { Log.warn("form-login-page must start with /"); path = "/" + path; } _formLoginPage = path; _formLoginPath = path; if (_formLoginPath.indexOf('?') > 0) _formLoginPath = _formLoginPath.substring(0, _formLoginPath.indexOf('?')); } /* ------------------------------------------------------------ */ private void setErrorPage(String path) { if (path == null || path.trim().length() == 0) { _formErrorPath = null; _formErrorPage = null; } else { if (!path.startsWith("/")) { Log.warn("form-error-page must start with /"); path = "/" + path; } _formErrorPage = path; _formErrorPath = path; if (_formErrorPath.indexOf('?') > 0) _formErrorPath = _formErrorPath.substring(0, _formErrorPath.indexOf('?')); } } /* ------------------------------------------------------------ */ public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException { HttpServletRequest request = (HttpServletRequest)req; HttpServletResponse response = (HttpServletResponse)res; HttpSession session = request.getSession(mandatory); - String uri = request.getRequestURL().toString();//getPathInfo(); + String uri = request.getRequestURI(); // not mandatory or not authenticated if (session == null || isLoginOrErrorPage(uri)) { return Authentication.NOT_CHECKED; } try { // Handle a request for authentication. if (uri==null) uri=URIUtil.SLASH; else if (uri.endsWith(__J_SECURITY_CHECK)) { final String username = request.getParameter(__J_USERNAME); final String password = request.getParameter(__J_PASSWORD); UserIdentity user = _loginService.login(username,password); if (user!=null) { // Redirect to original request String nuri; synchronized(session) { nuri = (String) session.getAttribute(__J_URI); session.removeAttribute(__J_URI); } if (nuri == null || nuri.length() == 0) { nuri = request.getContextPath(); if (nuri.length() == 0) nuri = URIUtil.SLASH; } response.setContentLength(0); response.sendRedirect(response.encodeRedirectURL(nuri)); return new FormAuthentication(this,user); } // not authenticated if (Log.isDebugEnabled()) Log.debug("Form authentication FAILED for " + StringUtil.printable(username)); if (_formErrorPage == null) { if (response != null) response.sendError(HttpServletResponse.SC_FORBIDDEN); } else if (_dispatch) { RequestDispatcher dispatcher = request.getRequestDispatcher(_formErrorPage); response.setHeader(HttpHeaders.CACHE_CONTROL,"No-cache"); response.setDateHeader(HttpHeaders.EXPIRES,1); dispatcher.forward(new FormRequest(request), new FormResponse(response)); } else { response.sendRedirect(URIUtil.addPaths(request.getContextPath(),_formErrorPage)); } return Authentication.SEND_FAILURE; } if (mandatory) { // redirect to login page synchronized (session) { if (session.getAttribute(__J_URI)==null) { StringBuffer buf = request.getRequestURL(); if (request.getQueryString() != null) buf.append("?").append(request.getQueryString()); session.setAttribute(__J_URI, buf.toString()); } } if (_dispatch) { RequestDispatcher dispatcher = request.getRequestDispatcher(_formLoginPage); response.setHeader(HttpHeaders.CACHE_CONTROL,"No-cache"); response.setDateHeader(HttpHeaders.EXPIRES,1); dispatcher.forward(new FormRequest(request), new FormResponse(response)); } else { response.sendRedirect(URIUtil.addPaths(request.getContextPath(),_formLoginPage)); } return Authentication.SEND_CONTINUE; } return Authentication.UNAUTHENTICATED; } catch (IOException e) { throw new ServerAuthException(e); } catch (ServletException e) { throw new ServerAuthException(e); } } /* ------------------------------------------------------------ */ public boolean isLoginOrErrorPage(String pathInContext) { return pathInContext != null && (pathInContext.equals(_formErrorPath) || pathInContext.equals(_formLoginPath)); } /* ------------------------------------------------------------ */ public boolean secureResponse(ServletRequest req, ServletResponse res, boolean mandatory, User validatedUser) throws ServerAuthException { return true; } /* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */ protected static class FormRequest extends HttpServletRequestWrapper { public FormRequest(HttpServletRequest request) { super(request); } @Override public long getDateHeader(String name) { if (name.toLowerCase().startsWith("if-")) return -1; return super.getDateHeader(name); } @Override public String getHeader(String name) { if (name.toLowerCase().startsWith("if-")) return null; return super.getHeader(name); } @Override public Enumeration getHeaderNames() { return Collections.enumeration(Collections.list(super.getHeaderNames())); } @Override public Enumeration getHeaders(String name) { if (name.toLowerCase().startsWith("if-")) return Collections.enumeration(Collections.EMPTY_LIST); return super.getHeaders(name); } } /* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */ protected static class FormResponse extends HttpServletResponseWrapper { public FormResponse(HttpServletResponse response) { super(response); } @Override public void addDateHeader(String name, long date) { if (notIgnored(name)) super.addDateHeader(name,date); } @Override public void addHeader(String name, String value) { if (notIgnored(name)) super.addHeader(name,value); } @Override public void setDateHeader(String name, long date) { if (notIgnored(name)) super.setDateHeader(name,date); } @Override public void setHeader(String name, String value) { if (notIgnored(name)) super.setHeader(name,value); } private boolean notIgnored(String name) { if (HttpHeaders.CACHE_CONTROL.equalsIgnoreCase(name) || HttpHeaders.PRAGMA.equalsIgnoreCase(name) || HttpHeaders.ETAG.equalsIgnoreCase(name) || HttpHeaders.EXPIRES.equalsIgnoreCase(name) || HttpHeaders.LAST_MODIFIED.equalsIgnoreCase(name) || HttpHeaders.AGE.equalsIgnoreCase(name)) return false; return true; } } public static class FormAuthentication extends UserAuthentication implements Authentication.ResponseSent { public FormAuthentication(Authenticator authenticator, UserIdentity userIdentity) { super(authenticator,userIdentity); } public String toString() { return "Form"+super.toString(); } } }
true
true
public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException { HttpServletRequest request = (HttpServletRequest)req; HttpServletResponse response = (HttpServletResponse)res; HttpSession session = request.getSession(mandatory); String uri = request.getRequestURL().toString();//getPathInfo(); // not mandatory or not authenticated if (session == null || isLoginOrErrorPage(uri)) { return Authentication.NOT_CHECKED; } try { // Handle a request for authentication. if (uri==null) uri=URIUtil.SLASH; else if (uri.endsWith(__J_SECURITY_CHECK)) { final String username = request.getParameter(__J_USERNAME); final String password = request.getParameter(__J_PASSWORD); UserIdentity user = _loginService.login(username,password); if (user!=null) { // Redirect to original request String nuri; synchronized(session) { nuri = (String) session.getAttribute(__J_URI); session.removeAttribute(__J_URI); } if (nuri == null || nuri.length() == 0) { nuri = request.getContextPath(); if (nuri.length() == 0) nuri = URIUtil.SLASH; } response.setContentLength(0); response.sendRedirect(response.encodeRedirectURL(nuri)); return new FormAuthentication(this,user); } // not authenticated if (Log.isDebugEnabled()) Log.debug("Form authentication FAILED for " + StringUtil.printable(username)); if (_formErrorPage == null) { if (response != null) response.sendError(HttpServletResponse.SC_FORBIDDEN); } else if (_dispatch) { RequestDispatcher dispatcher = request.getRequestDispatcher(_formErrorPage); response.setHeader(HttpHeaders.CACHE_CONTROL,"No-cache"); response.setDateHeader(HttpHeaders.EXPIRES,1); dispatcher.forward(new FormRequest(request), new FormResponse(response)); } else { response.sendRedirect(URIUtil.addPaths(request.getContextPath(),_formErrorPage)); } return Authentication.SEND_FAILURE; } if (mandatory) { // redirect to login page synchronized (session) { if (session.getAttribute(__J_URI)==null) { StringBuffer buf = request.getRequestURL(); if (request.getQueryString() != null) buf.append("?").append(request.getQueryString()); session.setAttribute(__J_URI, buf.toString()); } } if (_dispatch) { RequestDispatcher dispatcher = request.getRequestDispatcher(_formLoginPage); response.setHeader(HttpHeaders.CACHE_CONTROL,"No-cache"); response.setDateHeader(HttpHeaders.EXPIRES,1); dispatcher.forward(new FormRequest(request), new FormResponse(response)); } else { response.sendRedirect(URIUtil.addPaths(request.getContextPath(),_formLoginPage)); } return Authentication.SEND_CONTINUE; } return Authentication.UNAUTHENTICATED; } catch (IOException e) { throw new ServerAuthException(e); } catch (ServletException e) { throw new ServerAuthException(e); } }
public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException { HttpServletRequest request = (HttpServletRequest)req; HttpServletResponse response = (HttpServletResponse)res; HttpSession session = request.getSession(mandatory); String uri = request.getRequestURI(); // not mandatory or not authenticated if (session == null || isLoginOrErrorPage(uri)) { return Authentication.NOT_CHECKED; } try { // Handle a request for authentication. if (uri==null) uri=URIUtil.SLASH; else if (uri.endsWith(__J_SECURITY_CHECK)) { final String username = request.getParameter(__J_USERNAME); final String password = request.getParameter(__J_PASSWORD); UserIdentity user = _loginService.login(username,password); if (user!=null) { // Redirect to original request String nuri; synchronized(session) { nuri = (String) session.getAttribute(__J_URI); session.removeAttribute(__J_URI); } if (nuri == null || nuri.length() == 0) { nuri = request.getContextPath(); if (nuri.length() == 0) nuri = URIUtil.SLASH; } response.setContentLength(0); response.sendRedirect(response.encodeRedirectURL(nuri)); return new FormAuthentication(this,user); } // not authenticated if (Log.isDebugEnabled()) Log.debug("Form authentication FAILED for " + StringUtil.printable(username)); if (_formErrorPage == null) { if (response != null) response.sendError(HttpServletResponse.SC_FORBIDDEN); } else if (_dispatch) { RequestDispatcher dispatcher = request.getRequestDispatcher(_formErrorPage); response.setHeader(HttpHeaders.CACHE_CONTROL,"No-cache"); response.setDateHeader(HttpHeaders.EXPIRES,1); dispatcher.forward(new FormRequest(request), new FormResponse(response)); } else { response.sendRedirect(URIUtil.addPaths(request.getContextPath(),_formErrorPage)); } return Authentication.SEND_FAILURE; } if (mandatory) { // redirect to login page synchronized (session) { if (session.getAttribute(__J_URI)==null) { StringBuffer buf = request.getRequestURL(); if (request.getQueryString() != null) buf.append("?").append(request.getQueryString()); session.setAttribute(__J_URI, buf.toString()); } } if (_dispatch) { RequestDispatcher dispatcher = request.getRequestDispatcher(_formLoginPage); response.setHeader(HttpHeaders.CACHE_CONTROL,"No-cache"); response.setDateHeader(HttpHeaders.EXPIRES,1); dispatcher.forward(new FormRequest(request), new FormResponse(response)); } else { response.sendRedirect(URIUtil.addPaths(request.getContextPath(),_formLoginPage)); } return Authentication.SEND_CONTINUE; } return Authentication.UNAUTHENTICATED; } catch (IOException e) { throw new ServerAuthException(e); } catch (ServletException e) { throw new ServerAuthException(e); } }
diff --git a/src/com/dmdirc/plugins/PluginInfo.java b/src/com/dmdirc/plugins/PluginInfo.java index 8416a9949..524a4c120 100644 --- a/src/com/dmdirc/plugins/PluginInfo.java +++ b/src/com/dmdirc/plugins/PluginInfo.java @@ -1,980 +1,971 @@ /* * Copyright (c) 2006-2008 Chris Smith, Shane Mc Cormack, Gregory Holmes * * 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. * * SVN: $Id$ */ package com.dmdirc.plugins; import com.dmdirc.Main; import com.dmdirc.actions.ActionManager; import com.dmdirc.actions.CoreActionType; import com.dmdirc.config.prefs.validator.ValidationResponse; import com.dmdirc.util.resourcemanager.ResourceManager; import com.dmdirc.logger.Logger; import com.dmdirc.logger.ErrorLevel; import java.io.File; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.Properties; import java.util.List; import java.util.ArrayList; import java.util.Timer; import java.util.TimerTask; import java.net.URL; import java.net.URISyntaxException; public class PluginInfo implements Comparable<PluginInfo> { /** Plugin Meta Data */ private Properties metaData = null; /** URL that this plugin was loaded from */ private final URL url; /** Filename for this plugin (taken from URL) */ private final String filename; /** The actual Plugin from this jar */ private Plugin plugin = null; /** The classloader used for this Plugin */ private PluginClassLoader classloader = null; /** The resource manager used by this pluginInfo */ private ResourceManager myResourceManager = null; /** Is this plugin only loaded temporarily? */ private boolean tempLoaded = false; /** List of classes this plugin has */ private List<String> myClasses = new ArrayList<String>(); /** Requirements error message. */ private String requirementsError = ""; /** Last Error Message. */ private String lastError = "No Error"; /** Are we trying to load? */ private boolean isLoading = false; /** * Create a new PluginInfo. * * @param url URL to file that this plugin is stored in. * @throws PluginException if there is an error loading the Plugin * @since 0.6 */ public PluginInfo(final URL url) throws PluginException { this(url, true); } /** * Create a new PluginInfo. * * @param url URL to file that this plugin is stored in. * @param load Should this plugin be loaded, or is this just a placeholder? (true for load, false for placeholder) * @throws PluginException if there is an error loading the Plugin * @since 0.6 */ public PluginInfo(final URL url, final boolean load) throws PluginException { this.url = url; this.filename = (new File(url.getPath())).getName(); ResourceManager res; // Check for updates. if (new File(getFullFilename()+".update").exists() && new File(getFullFilename()).delete()) { new File(getFullFilename()+".update").renameTo(new File(getFullFilename())); } if (!load) { // Load the metaData if available. metaData = new Properties(); try { res = getResourceManager(); if (res.resourceExists("META-INF/plugin.info")) { metaData.load(res.getResourceInputStream("META-INF/plugin.info")); } } catch (IOException e) { } catch (IllegalArgumentException e) { } return; } try { res = getResourceManager(); } catch (IOException ioe) { lastError = "Error with resourcemanager: "+ioe.getMessage(); throw new PluginException("Plugin "+filename+" failed to load. "+lastError, ioe); } try { if (res.resourceExists("META-INF/plugin.info")) { metaData = new Properties(); metaData.load(res.getResourceInputStream("META-INF/plugin.info")); } else { lastError = "plugin.info doesn't exist in jar"; throw new PluginException("Plugin "+filename+" failed to load. "+lastError); } } catch (IOException e) { lastError = "plugin.info IOException: "+e.getMessage(); throw new PluginException("Plugin "+filename+" failed to load, plugin.info failed to open - "+e.getMessage(), e); } catch (IllegalArgumentException e) { lastError = "plugin.info IllegalArgumentException: "+e.getMessage(); throw new PluginException("Plugin "+filename+" failed to load, plugin.info failed to open - "+e.getMessage(), e); } if (getVersion() < 0) { lastError = "Incomplete plugin.info (Missing or invalid 'version')"; throw new PluginException("Plugin "+filename+" failed to load. "+lastError); } else if (getAuthor().isEmpty()) { lastError = "Incomplete plugin.info (Missing or invalid 'author')"; throw new PluginException("Plugin "+filename+" failed to load. "+lastError); } else if (getName().isEmpty()) { lastError = "Incomplete plugin.info (Missing or invalid 'name')"; throw new PluginException("Plugin "+filename+" failed to load. "+lastError); } else if (getMinVersion().isEmpty()) { lastError = "Incomplete plugin.info (Missing or invalid 'minversion')"; throw new PluginException("Plugin "+filename+" failed to load. "+lastError); } else if (getMainClass().isEmpty()) { lastError = "Incomplete plugin.info (Missing or invalid 'mainclass')"; throw new PluginException("Plugin "+filename+" failed to load. "+lastError); } if (checkRequirements()) { final String mainClass = getMainClass().replace('.', '/')+".class"; if (!res.resourceExists(mainClass)) { lastError = "main class file ("+mainClass+") not found in jar."; throw new PluginException("Plugin "+filename+" failed to load. "+lastError); } for (final String classfilename : res.getResourcesStartingWith("")) { String classname = classfilename.replace('/', '.'); if (classname.matches("^.*\\.class$")) { classname = classname.replaceAll("\\.class$", ""); myClasses.add(classname); } } if (isPersistent() && loadAll()) { loadEntirePlugin(); } } else { lastError = "One or more requirements not met ("+requirementsError+")"; throw new PluginException("Plugin "+filename+" was not loaded. "+lastError); } } /** * Called when the plugin is updated using the updater. * Reloads metaData and updates the list of files. */ public void pluginUpdated() { try { // Force a new resourcemanager just incase. final ResourceManager res = getResourceManager(true); myClasses.clear(); for (final String classfilename : res.getResourcesStartingWith("")) { String classname = classfilename.replace('/', '.'); if (classname.matches("^.*\\.class$")) { classname = classname.replaceAll("\\.class$", ""); myClasses.add(classname); } } updateMetaData(); } catch (IOException ioe) { } } /** * Try to reload the metaData from the plugin.info file. * If this fails, the old data will be used still. * * @return true if metaData was reloaded ok, else false. */ public boolean updateMetaData() { try { // Force a new resourcemanager just incase. final ResourceManager res = getResourceManager(true); if (res.resourceExists("META-INF/plugin.info")) { final Properties newMetaData = new Properties(); newMetaData.load(res.getResourceInputStream("META-INF/plugin.info")); metaData = newMetaData; return true; } } catch (IOException ioe) { } catch (IllegalArgumentException e) { } return false; } /** * Get the contents of requirementsError * * @return requirementsError */ public String getRequirementsError() { return requirementsError; } /** * Get the resource manager for this plugin * * @throws IOException if there is any problem getting a ResourceManager for this plugin */ public synchronized ResourceManager getResourceManager() throws IOException { return getResourceManager(false); } /** * Get the resource manager for this plugin * * @param forceNew Force a new resource manager rather than using the old one. * @throws IOException if there is any problem getting a ResourceManager for this plugin * @since 0.6 */ public synchronized ResourceManager getResourceManager(final boolean forceNew) throws IOException { if (myResourceManager == null || forceNew) { myResourceManager = ResourceManager.getResourceManager("jar://"+getFullFilename()); // Clear the resourcemanager in 10 seconds to stop us holding the file open final Timer timer = new Timer(filename+"-resourcemanagerTimer"); final TimerTask timerTask = new TimerTask(){ public void run() { myResourceManager = null; } }; timer.schedule(timerTask, 10000); } return myResourceManager; } /** * Checks to see if the minimum version requirement of the plugin is * satisfied. * If either version is non-positive, the test passes. * On failure, the requirementsError field will contain a user-friendly * error message. * * @param desired The desired minimum version of DMDirc. * @param actual The actual current version of DMDirc. * @return True if the test passed, false otherwise */ protected boolean checkMinimumVersion(final String desired, final int actual) { int idesired; try { idesired = Integer.parseInt(desired); } catch (NumberFormatException ex) { requirementsError = "'minversion' is a non-integer"; return false; } if (actual > 0 && idesired > 0 && actual < idesired) { requirementsError = "Plugin is for a newer version of DMDirc"; return false; } else { return true; } } /** * Checks to see if the maximum version requirement of the plugin is * satisfied. * If either version is non-positive, the test passes. * If the desired version is empty, the test passes. * On failure, the requirementsError field will contain a user-friendly * error message. * * @param desired The desired maximum version of DMDirc. * @param actual The actual current version of DMDirc. * @return True if the test passed, false otherwise */ protected boolean checkMaximumVersion(final String desired, final int actual) { int idesired; if (desired.isEmpty()) { return true; } try { idesired = Integer.parseInt(desired); } catch (NumberFormatException ex) { requirementsError = "'maxversion' is a non-integer"; return false; } if (actual > 0 && idesired > 0 && actual > idesired) { requirementsError = "Plugin is for an older version of DMDirc"; return false; } else { return true; } } /** * Checks to see if the OS requirements of the plugin are satisfied. * If the desired string is empty, the test passes. * Otherwise it is used as one to three colon-delimited regular expressions, * to test the name, version and architecture of the OS, respectively. * On failure, the requirementsError field will contain a user-friendly * error message. * * @param desired The desired OS requirements * @param actualName The actual name of the OS * @param actualVersion The actual version of the OS * @param actualArch The actual architecture of the OS * @return True if the test passes, false otherwise */ protected boolean checkOS(final String desired, final String actualName, final String actualVersion, final String actualArch) { if (desired.isEmpty()) { return true; } final String[] desiredParts = desired.split(":"); if (!actualName.toLowerCase().matches(desiredParts[0])) { requirementsError = "Invalid OS. (Wanted: '" + desiredParts[0] + "', actual: '" + actualName + "')"; return false; } else if (desiredParts.length > 1 && !actualVersion.toLowerCase().matches(desiredParts[1])) { requirementsError = "Invalid OS version. (Wanted: '" + desiredParts[1] + "', actual: '" + actualVersion + "')"; return false; } else if (desiredParts.length > 2 && !actualArch.toLowerCase().matches(desiredParts[2])) { requirementsError = "Invalid OS architecture. (Wanted: '" + desiredParts[2] + "', actual: '" + actualArch + "')"; return false; } return true; } /** * Checks to see if the UI requirements of the plugin are satisfied. * If the desired string is empty, the test passes. * Otherwise it is used as a regular expressions against the package of the * UIController to test what UI is currently in use. * On failure, the requirementsError field will contain a user-friendly * error message. * * @param desired The desired UI requirements * @param actual The package of the current UI in use. * @return True if the test passes, false otherwise */ protected boolean checkUI(final String desired, final String actual) { if (desired.isEmpty()) { return true; } if (!actual.toLowerCase().matches(desired)) { requirementsError = "Invalid UI. (Wanted: '" + desired + "', actual: '" + actual + "')"; return false; } return true; } /** * Checks to see if the file requirements of the plugin are satisfied. * If the desired string is empty, the test passes. * Otherwise it is passed to File.exists() to see if the file is valid. * Multiple files can be specified by using a "," to separate. And either/or * files can be specified using a "|" (eg /usr/bin/bash|/bin/bash) * If the test fails, the requirementsError field will contain a * user-friendly error message. * * @param desired The desired file requirements * @return True if the test passes, false otherwise */ protected boolean checkFiles(final String desired) { if (desired.isEmpty()) { return true; } for (String files : desired.split(",")) { final String[] filelist = files.split("\\|"); boolean foundFile = false; for (String file : filelist) { if ((new File(file)).exists()) { foundFile = true; break; } } if (!foundFile) { requirementsError = "Required file '"+files+"' not found"; return false; } } return true; } /** * Checks to see if the plugin requirements of the plugin are satisfied. * If the desired string is empty, the test passes. * Plugins should be specified as: * plugin1[:minversion[:maxversion]],plugin2[:minversion[:maxversion]] * Plugins will be attempted to be loaded if not loaded, else the test will * fail if the versions don't match, or the plugin isn't known. * If the test fails, the requirementsError field will contain a * user-friendly error message. * * @param desired The desired file requirements * @return True if the test passes, false otherwise */ protected boolean checkPlugins(final String desired) { if (desired.isEmpty()) { return true; } for (String plugin : desired.split(",")) { final String[] data = plugin.split(":"); final PluginInfo pi = PluginManager.getPluginManager().getPluginInfoByName(data[0], true); if (pi == null) { requirementsError = "Required plugin '"+data[0]+"' was not found"; return false; } else { if (data.length > 1) { // Check plugin minimum version matches. try { final int minversion = Integer.parseInt(data[1]); if (pi.getVersion() < minversion) { requirementsError = "Plugin '"+data[0]+"' is too old (Required Version: "+minversion+", Actual Version: "+pi.getVersion()+")"; return false; } else { if (data.length > 2) { // Check plugin maximum version matches. try { final int maxversion = Integer.parseInt(data[2]); if (pi.getVersion() > maxversion) { requirementsError = "Plugin '"+data[0]+"' is too new (Required Version: "+maxversion+", Actual Version: "+pi.getVersion()+")"; return false; } } catch (NumberFormatException nfe) { requirementsError = "Plugin max-version '"+data[2]+"' for plugin ('"+data[0]+"') is a non-integer"; return false; } } } } catch (NumberFormatException nfe) { requirementsError = "Plugin min-version '"+data[1]+"' for plugin ('"+data[0]+"') is a non-integer"; return false; } } } } return true; } /** * Are the requirements for this plugin met? * * @return true/false (Actual error if false is in the requirementsError field) */ public boolean checkRequirements() { if (metaData == null) { // No meta-data, so no requirements. return true; } final String uiPackage; if (Main.getUI().getClass().getPackage() != null) { uiPackage = Main.getUI().getClass().getPackage().getName(); } else { final String uiController = Main.getUI().getClass().getName(); if (uiController.lastIndexOf('.') >= 0) { uiPackage = uiController.substring(0,uiController.lastIndexOf('.')); } else { uiPackage = uiController; } } if (!checkMinimumVersion(getMinVersion(), Main.SVN_REVISION) || !checkMaximumVersion(getMaxVersion(), Main.SVN_REVISION) || !checkOS(getMetaInfo(new String[]{"required-os", "require-os"}), System.getProperty("os.name"), System.getProperty("os.version"), System.getProperty("os.arch")) || !checkFiles(getMetaInfo(new String[]{"required-files", "require-files", "required-file", "require-file"})) || !checkUI(getMetaInfo(new String[]{"required-ui", "require-ui"}), uiPackage) || !checkPlugins(getMetaInfo(new String[]{"required-plugins", "require-plugins", "required-plugin", "require-plugin"})) ) { return false; } // All requirements passed, woo \o return true; } /** * Is this plugin loaded? */ public boolean isLoaded() { return (plugin != null) && !tempLoaded; } /** * Is this plugin temporarily loaded? */ public boolean isTempLoaded() { return (plugin != null) && tempLoaded; } /** * Load entire plugin. * This loads all files in the jar immediately. * * @throws PluginException if there is an error with the resourcemanager */ private void loadEntirePlugin() throws PluginException { // Load the main "Plugin" from the jar loadPlugin(); // Now load all the rest. for (String classname : myClasses) { loadClass(classname); } } /** * Try to Load the plugin files temporarily. */ public void loadPluginTemp() { tempLoaded = true; loadPlugin(); } /** * Load any required plugins */ public void loadRequired() { final String required = getMetaInfo(new String[]{"required-plugins", "require-plugins", "required-plugin", "require-plugin"}); for (String plugin : required.split(",")) { final String[] data = plugin.split(":"); if (!data[0].trim().isEmpty()) { final PluginInfo pi = PluginManager.getPluginManager().getPluginInfoByName(data[0], true); if (pi == null) { return; } if (tempLoaded) { pi.loadPluginTemp(); } else { pi.loadPlugin(); } } } } /** * Load the plugin files. */ public void loadPlugin() { - System.out.println("["+getName()+"] loadPlugin called"); if (isTempLoaded()) { tempLoaded = false; - System.out.println("["+getName()+"] temp -> full"); - System.out.println("["+getName()+"] loadingRequirements"); loadRequired(); - System.out.println("["+getName()+"] calling onLoad"); plugin.onLoad(); - System.out.println("["+getName()+"] onLoad Result: "+lastError); } else { if (isLoaded() || metaData == null || isLoading) { lastError = "Not Loading: ("+isLoaded()+"||"+(metaData == null)+"||"+isLoading+")"; - System.out.println("["+getName()+"] loadPlugin failed: "+lastError); return; } isLoading = true; - System.out.println("["+getName()+"] loadingRequirements"); loadRequired(); - System.out.println("["+getName()+"] loading Main class"); loadClass(getMainClass()); - System.out.println("["+getName()+"] load Result: "+lastError); if (isLoaded()) { ActionManager.processEvent(CoreActionType.PLUGIN_LOADED, null, this); } isLoading = false; } } /** * Load the given classname. * * @param classname Class to load */ private void loadClass(final String classname) { try { if (classloader == null) { classloader = new PluginClassLoader(this); } // Don't reload a class if its already loaded. if (classloader.isClassLoaded(classname, true)) { lastError = "Classloader says we are already loaded."; return; } final Class<?> c = classloader.loadClass(classname); final Constructor<?> constructor = c.getConstructor(new Class[] {}); // Only try and construct the main class, anything else should be constructed // by the plugin itself. if (classname.equals(getMainClass())) { final Object temp = constructor.newInstance(new Object[] {}); if (temp instanceof Plugin) { final ValidationResponse prerequisites = ((Plugin) temp).checkPrerequisites(); if (!prerequisites.isFailure()) { plugin = (Plugin) temp; if (!tempLoaded) { try { plugin.onLoad(); } catch (Exception e) { lastError = "Error in onLoad for "+getName()+":"+e.getMessage(); Logger.userError(ErrorLevel.MEDIUM, lastError, e); unloadPlugin(); } } } else { if (!tempLoaded) { lastError = "Prerequisites for plugin not met. ('"+filename+":"+getMainClass()+"' -> '"+prerequisites.getFailureReason()+"') "; Logger.userError(ErrorLevel.LOW, lastError); } } } } } catch (ClassNotFoundException cnfe) { lastError = "Class not found ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+cnfe.getMessage(); Logger.userError(ErrorLevel.LOW, lastError, cnfe); } catch (NoSuchMethodException nsme) { // Don't moan about missing constructors for any class thats not the main Class lastError = "Constructor missing ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+nsme.getMessage(); if (classname.equals(getMainClass())) { Logger.userError(ErrorLevel.LOW, lastError, nsme); } } catch (IllegalAccessException iae) { lastError = "Unable to access constructor ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+iae.getMessage(); Logger.userError(ErrorLevel.LOW, lastError, iae); } catch (InvocationTargetException ite) { lastError = "Unable to invoke target ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+ite.getMessage(); Logger.userError(ErrorLevel.LOW, lastError, ite); } catch (InstantiationException ie) { lastError = "Unable to instantiate plugin ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+ie.getMessage(); Logger.userError(ErrorLevel.LOW, lastError, ie); } catch (NoClassDefFoundError ncdf) { lastError = "Unable to instantiate plugin ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - Unable to find class: " + ncdf.getMessage(); Logger.userError(ErrorLevel.LOW, lastError, ncdf); } catch (VerifyError ve) { lastError = "Unable to instantiate plugin ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - Incompatible: "+ve.getMessage(); Logger.userError(ErrorLevel.LOW, lastError, ve); } } /** * Unload the plugin if possible. */ public void unloadPlugin() { if (!isPersistent() && (isLoaded() || isTempLoaded())) { if (!isTempLoaded()) { try { plugin.onUnload(); } catch (Exception e) { lastError = "Error in onUnload for "+getName()+":"+e.getMessage(); Logger.userError(ErrorLevel.MEDIUM, lastError, e); } ActionManager.processEvent(CoreActionType.PLUGIN_UNLOADED, null, this); } tempLoaded = false; plugin = null; classloader = null; } } /** * Get the last Error * * @return last Error * @since 0.6 */ public String getLastError() { return lastError; } /** * Get the list of Classes * * @return Classes this plugin has */ public List<String> getClassList() { return myClasses; } /** * Get the main Class * * @return Main Class to begin loading. */ public String getMainClass() { return metaData.getProperty("mainclass",""); } /** * Get the Plugin for this plugin. * * @return Plugin */ public Plugin getPlugin() { return plugin; } /** * Get the PluginClassLoader for this plugin. * * @return PluginClassLoader */ protected PluginClassLoader getPluginClassLoader() { return classloader; } /** * Get the plugin friendly version * * @return Plugin friendly Version */ public String getFriendlyVersion() { return metaData.getProperty("friendlyversion", String.valueOf(getVersion())); } /** * Get the plugin version * * @return Plugin Version */ public int getVersion() { try { return Integer.parseInt(metaData.getProperty("version","0")); } catch (NumberFormatException nfe) { return -1; } } /** * Get the id for this plugin on the addons site. * If a plugin has been submitted to addons.dmdirc.com, and plugin.info * contains a property addonid then this will return it. * This is used along with the version property to allow the auto-updater to * update the addon if the author submits a new version to the addons site. * * @return Addon Site ID number * -1 If not present * -2 If non-integer */ public int getAddonID() { try { return Integer.parseInt(metaData.getProperty("addonid","-1")); } catch (NumberFormatException nfe) { return -2; } } /** * Is this a persistent plugin? * * @return true if persistent, else false */ public boolean isPersistent() { final String persistence = metaData.getProperty("persistent","no"); return persistence.equalsIgnoreCase("true") || persistence.equalsIgnoreCase("yes"); } /** * Does this plugin contain any persistent classes? * * @return true if this plugin contains any persistent classes, else false */ public boolean hasPersistent() { final String persistence = metaData.getProperty("persistent","no"); if (persistence.equalsIgnoreCase("true")) { return true; } else { for (Object keyObject : metaData.keySet()) { if (keyObject.toString().toLowerCase().startsWith("persistent-")) { return true; } } } return false; } /** * Get a list of all persistent classes in this plugin * * @return List of all persistent classes in this plugin */ public List<String> getPersistentClasses() { final List<String> result = new ArrayList<String>(); final String persistence = metaData.getProperty("persistent","no"); if (persistence.equalsIgnoreCase("true")) { try { ResourceManager res = getResourceManager(); for (final String filename : res.getResourcesStartingWith("")) { if (filename.matches("^.*\\.class$")) { result.add(filename.replaceAll("\\.class$", "").replace('/', '.')); } } } catch (IOException e) { // Jar no longer exists? } } else { for (Object keyObject : metaData.keySet()) { if (keyObject.toString().toLowerCase().startsWith("persistent-")) { result.add(keyObject.toString().substring(11)); } } } return result; } /** * Is this a persistent class? * * @param classname class to check persistence of * @return true if file (or whole plugin) is persistent, else false */ public boolean isPersistent(final String classname) { if (isPersistent()) { return true; } else { final String persistence = metaData.getProperty("persistent-"+classname,"no"); return persistence.equalsIgnoreCase("true") || persistence.equalsIgnoreCase("yes"); } } /** * Get the plugin Filename. * * @return Filename of plugin */ public String getFilename() { return filename; } /** * Get the full plugin Filename (inc dirname) * * @return Filename of plugin */ public String getFullFilename() { return url.getPath(); } /** * Get the plugin Author. * * @return Author of plugin */ public String getAuthor() { return getMetaInfo("author",""); } /** * Get the plugin Description. * * @return Description of plugin */ public String getDescription() { return getMetaInfo("description",""); } /** * Get the minimum dmdirc version required to run the plugin. * * @return minimum dmdirc version required to run the plugin. */ public String getMinVersion() { return getMetaInfo("minversion",""); } /** * Get the (optional) maximum dmdirc version on which this plugin can run * * @return optional maximum dmdirc version on which this plugin can run */ public String getMaxVersion() { return getMetaInfo("maxversion",""); } /** * Get the name of the plugin. (Used to identify the plugin) * * @return Name of plugin */ public String getName() { return getMetaInfo("name",""); } /** * Get the nice name of the plugin. (Displayed to users) * * @return Nice Name of plugin */ public String getNiceName() { return getMetaInfo("nicename",getName()); } /** * String Representation of this plugin * * @return String Representation of this plugin */ @Override public String toString() { return getNiceName()+" - "+filename; } /** * Does this plugin want all its classes loaded? * * @return true/false if loadall=true || loadall=yes */ public boolean loadAll() { final String loadAll = metaData.getProperty("loadall","no"); return loadAll.equalsIgnoreCase("true") || loadAll.equalsIgnoreCase("yes"); } /** * Get misc meta-information. * * @param metainfo The metainfo to return * @return Misc Meta Info (or "" if not found); */ public String getMetaInfo(final String metainfo) { return getMetaInfo(metainfo,""); } /** * Get misc meta-information. * * @param metainfo The metainfo to return * @param fallback Fallback value if requested value is not found * @return Misc Meta Info (or fallback if not found); */ public String getMetaInfo(final String metainfo, final String fallback) { return metaData.getProperty(metainfo,fallback); } /** * Get misc meta-information. * * @param metainfo The metainfos to look for in order. If the first item in * the array is not found, the next will be looked for, and * so on until either one is found, or none are found. * @return Misc Meta Info (or "" if none are found); */ public String getMetaInfo(final String[] metainfo) { return getMetaInfo(metainfo,""); } /** * Get misc meta-information. * * @param metainfo The metainfos to look for in order. If the first item in * the array is not found, the next will be looked for, and * so on until either one is found, or none are found. * @param fallback Fallback value if requested values are not found * @return Misc Meta Info (or "" if none are found); */ public String getMetaInfo(final String[] metainfo, final String fallback) { for (String meta : metainfo) { String result = metaData.getProperty(meta); if (result != null) { return result; } } return fallback; } /** * Compares this object with the specified object for order. * Returns a negative integer, zero, or a positive integer as per String.compareTo(); * * @param o Object to compare to * @return a negative integer, zero, or a positive integer. */ @Override public int compareTo(final PluginInfo o) { return toString().compareTo(o.toString()); } }
false
true
public boolean checkRequirements() { if (metaData == null) { // No meta-data, so no requirements. return true; } final String uiPackage; if (Main.getUI().getClass().getPackage() != null) { uiPackage = Main.getUI().getClass().getPackage().getName(); } else { final String uiController = Main.getUI().getClass().getName(); if (uiController.lastIndexOf('.') >= 0) { uiPackage = uiController.substring(0,uiController.lastIndexOf('.')); } else { uiPackage = uiController; } } if (!checkMinimumVersion(getMinVersion(), Main.SVN_REVISION) || !checkMaximumVersion(getMaxVersion(), Main.SVN_REVISION) || !checkOS(getMetaInfo(new String[]{"required-os", "require-os"}), System.getProperty("os.name"), System.getProperty("os.version"), System.getProperty("os.arch")) || !checkFiles(getMetaInfo(new String[]{"required-files", "require-files", "required-file", "require-file"})) || !checkUI(getMetaInfo(new String[]{"required-ui", "require-ui"}), uiPackage) || !checkPlugins(getMetaInfo(new String[]{"required-plugins", "require-plugins", "required-plugin", "require-plugin"})) ) { return false; } // All requirements passed, woo \o return true; } /** * Is this plugin loaded? */ public boolean isLoaded() { return (plugin != null) && !tempLoaded; } /** * Is this plugin temporarily loaded? */ public boolean isTempLoaded() { return (plugin != null) && tempLoaded; } /** * Load entire plugin. * This loads all files in the jar immediately. * * @throws PluginException if there is an error with the resourcemanager */ private void loadEntirePlugin() throws PluginException { // Load the main "Plugin" from the jar loadPlugin(); // Now load all the rest. for (String classname : myClasses) { loadClass(classname); } } /** * Try to Load the plugin files temporarily. */ public void loadPluginTemp() { tempLoaded = true; loadPlugin(); } /** * Load any required plugins */ public void loadRequired() { final String required = getMetaInfo(new String[]{"required-plugins", "require-plugins", "required-plugin", "require-plugin"}); for (String plugin : required.split(",")) { final String[] data = plugin.split(":"); if (!data[0].trim().isEmpty()) { final PluginInfo pi = PluginManager.getPluginManager().getPluginInfoByName(data[0], true); if (pi == null) { return; } if (tempLoaded) { pi.loadPluginTemp(); } else { pi.loadPlugin(); } } } } /** * Load the plugin files. */ public void loadPlugin() { System.out.println("["+getName()+"] loadPlugin called"); if (isTempLoaded()) { tempLoaded = false; System.out.println("["+getName()+"] temp -> full"); System.out.println("["+getName()+"] loadingRequirements"); loadRequired(); System.out.println("["+getName()+"] calling onLoad"); plugin.onLoad(); System.out.println("["+getName()+"] onLoad Result: "+lastError); } else { if (isLoaded() || metaData == null || isLoading) { lastError = "Not Loading: ("+isLoaded()+"||"+(metaData == null)+"||"+isLoading+")"; System.out.println("["+getName()+"] loadPlugin failed: "+lastError); return; } isLoading = true; System.out.println("["+getName()+"] loadingRequirements"); loadRequired(); System.out.println("["+getName()+"] loading Main class"); loadClass(getMainClass()); System.out.println("["+getName()+"] load Result: "+lastError); if (isLoaded()) { ActionManager.processEvent(CoreActionType.PLUGIN_LOADED, null, this); } isLoading = false; } } /** * Load the given classname. * * @param classname Class to load */ private void loadClass(final String classname) { try { if (classloader == null) { classloader = new PluginClassLoader(this); } // Don't reload a class if its already loaded. if (classloader.isClassLoaded(classname, true)) { lastError = "Classloader says we are already loaded."; return; } final Class<?> c = classloader.loadClass(classname); final Constructor<?> constructor = c.getConstructor(new Class[] {}); // Only try and construct the main class, anything else should be constructed // by the plugin itself. if (classname.equals(getMainClass())) { final Object temp = constructor.newInstance(new Object[] {}); if (temp instanceof Plugin) { final ValidationResponse prerequisites = ((Plugin) temp).checkPrerequisites(); if (!prerequisites.isFailure()) { plugin = (Plugin) temp; if (!tempLoaded) { try { plugin.onLoad(); } catch (Exception e) { lastError = "Error in onLoad for "+getName()+":"+e.getMessage(); Logger.userError(ErrorLevel.MEDIUM, lastError, e); unloadPlugin(); } } } else { if (!tempLoaded) { lastError = "Prerequisites for plugin not met. ('"+filename+":"+getMainClass()+"' -> '"+prerequisites.getFailureReason()+"') "; Logger.userError(ErrorLevel.LOW, lastError); } } } } } catch (ClassNotFoundException cnfe) { lastError = "Class not found ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+cnfe.getMessage(); Logger.userError(ErrorLevel.LOW, lastError, cnfe); } catch (NoSuchMethodException nsme) { // Don't moan about missing constructors for any class thats not the main Class lastError = "Constructor missing ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+nsme.getMessage(); if (classname.equals(getMainClass())) { Logger.userError(ErrorLevel.LOW, lastError, nsme); } } catch (IllegalAccessException iae) { lastError = "Unable to access constructor ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+iae.getMessage(); Logger.userError(ErrorLevel.LOW, lastError, iae); } catch (InvocationTargetException ite) { lastError = "Unable to invoke target ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+ite.getMessage(); Logger.userError(ErrorLevel.LOW, lastError, ite); } catch (InstantiationException ie) { lastError = "Unable to instantiate plugin ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+ie.getMessage(); Logger.userError(ErrorLevel.LOW, lastError, ie); } catch (NoClassDefFoundError ncdf) { lastError = "Unable to instantiate plugin ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - Unable to find class: " + ncdf.getMessage(); Logger.userError(ErrorLevel.LOW, lastError, ncdf); } catch (VerifyError ve) { lastError = "Unable to instantiate plugin ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - Incompatible: "+ve.getMessage(); Logger.userError(ErrorLevel.LOW, lastError, ve); } } /** * Unload the plugin if possible. */ public void unloadPlugin() { if (!isPersistent() && (isLoaded() || isTempLoaded())) { if (!isTempLoaded()) { try { plugin.onUnload(); } catch (Exception e) { lastError = "Error in onUnload for "+getName()+":"+e.getMessage(); Logger.userError(ErrorLevel.MEDIUM, lastError, e); } ActionManager.processEvent(CoreActionType.PLUGIN_UNLOADED, null, this); } tempLoaded = false; plugin = null; classloader = null; } } /** * Get the last Error * * @return last Error * @since 0.6 */ public String getLastError() { return lastError; } /** * Get the list of Classes * * @return Classes this plugin has */ public List<String> getClassList() { return myClasses; } /** * Get the main Class * * @return Main Class to begin loading. */ public String getMainClass() { return metaData.getProperty("mainclass",""); } /** * Get the Plugin for this plugin. * * @return Plugin */ public Plugin getPlugin() { return plugin; } /** * Get the PluginClassLoader for this plugin. * * @return PluginClassLoader */ protected PluginClassLoader getPluginClassLoader() { return classloader; } /** * Get the plugin friendly version * * @return Plugin friendly Version */ public String getFriendlyVersion() { return metaData.getProperty("friendlyversion", String.valueOf(getVersion())); } /** * Get the plugin version * * @return Plugin Version */ public int getVersion() { try { return Integer.parseInt(metaData.getProperty("version","0")); } catch (NumberFormatException nfe) { return -1; } } /** * Get the id for this plugin on the addons site. * If a plugin has been submitted to addons.dmdirc.com, and plugin.info * contains a property addonid then this will return it. * This is used along with the version property to allow the auto-updater to * update the addon if the author submits a new version to the addons site. * * @return Addon Site ID number * -1 If not present * -2 If non-integer */ public int getAddonID() { try { return Integer.parseInt(metaData.getProperty("addonid","-1")); } catch (NumberFormatException nfe) { return -2; } } /** * Is this a persistent plugin? * * @return true if persistent, else false */ public boolean isPersistent() { final String persistence = metaData.getProperty("persistent","no"); return persistence.equalsIgnoreCase("true") || persistence.equalsIgnoreCase("yes"); } /** * Does this plugin contain any persistent classes? * * @return true if this plugin contains any persistent classes, else false */ public boolean hasPersistent() { final String persistence = metaData.getProperty("persistent","no"); if (persistence.equalsIgnoreCase("true")) { return true; } else { for (Object keyObject : metaData.keySet()) { if (keyObject.toString().toLowerCase().startsWith("persistent-")) { return true; } } } return false; } /** * Get a list of all persistent classes in this plugin * * @return List of all persistent classes in this plugin */ public List<String> getPersistentClasses() { final List<String> result = new ArrayList<String>(); final String persistence = metaData.getProperty("persistent","no"); if (persistence.equalsIgnoreCase("true")) { try { ResourceManager res = getResourceManager(); for (final String filename : res.getResourcesStartingWith("")) { if (filename.matches("^.*\\.class$")) { result.add(filename.replaceAll("\\.class$", "").replace('/', '.')); } } } catch (IOException e) { // Jar no longer exists? } } else { for (Object keyObject : metaData.keySet()) { if (keyObject.toString().toLowerCase().startsWith("persistent-")) { result.add(keyObject.toString().substring(11)); } } } return result; } /** * Is this a persistent class? * * @param classname class to check persistence of * @return true if file (or whole plugin) is persistent, else false */ public boolean isPersistent(final String classname) { if (isPersistent()) { return true; } else { final String persistence = metaData.getProperty("persistent-"+classname,"no"); return persistence.equalsIgnoreCase("true") || persistence.equalsIgnoreCase("yes"); } } /** * Get the plugin Filename. * * @return Filename of plugin */ public String getFilename() { return filename; } /** * Get the full plugin Filename (inc dirname) * * @return Filename of plugin */ public String getFullFilename() { return url.getPath(); } /** * Get the plugin Author. * * @return Author of plugin */ public String getAuthor() { return getMetaInfo("author",""); } /** * Get the plugin Description. * * @return Description of plugin */ public String getDescription() { return getMetaInfo("description",""); } /** * Get the minimum dmdirc version required to run the plugin. * * @return minimum dmdirc version required to run the plugin. */ public String getMinVersion() { return getMetaInfo("minversion",""); } /** * Get the (optional) maximum dmdirc version on which this plugin can run * * @return optional maximum dmdirc version on which this plugin can run */ public String getMaxVersion() { return getMetaInfo("maxversion",""); } /** * Get the name of the plugin. (Used to identify the plugin) * * @return Name of plugin */ public String getName() { return getMetaInfo("name",""); } /** * Get the nice name of the plugin. (Displayed to users) * * @return Nice Name of plugin */ public String getNiceName() { return getMetaInfo("nicename",getName()); } /** * String Representation of this plugin * * @return String Representation of this plugin */ @Override public String toString() { return getNiceName()+" - "+filename; } /** * Does this plugin want all its classes loaded? * * @return true/false if loadall=true || loadall=yes */ public boolean loadAll() { final String loadAll = metaData.getProperty("loadall","no"); return loadAll.equalsIgnoreCase("true") || loadAll.equalsIgnoreCase("yes"); } /** * Get misc meta-information. * * @param metainfo The metainfo to return * @return Misc Meta Info (or "" if not found); */ public String getMetaInfo(final String metainfo) { return getMetaInfo(metainfo,""); } /** * Get misc meta-information. * * @param metainfo The metainfo to return * @param fallback Fallback value if requested value is not found * @return Misc Meta Info (or fallback if not found); */ public String getMetaInfo(final String metainfo, final String fallback) { return metaData.getProperty(metainfo,fallback); } /** * Get misc meta-information. * * @param metainfo The metainfos to look for in order. If the first item in * the array is not found, the next will be looked for, and * so on until either one is found, or none are found. * @return Misc Meta Info (or "" if none are found); */ public String getMetaInfo(final String[] metainfo) { return getMetaInfo(metainfo,""); } /** * Get misc meta-information. * * @param metainfo The metainfos to look for in order. If the first item in * the array is not found, the next will be looked for, and * so on until either one is found, or none are found. * @param fallback Fallback value if requested values are not found * @return Misc Meta Info (or "" if none are found); */ public String getMetaInfo(final String[] metainfo, final String fallback) { for (String meta : metainfo) { String result = metaData.getProperty(meta); if (result != null) { return result; } } return fallback; } /** * Compares this object with the specified object for order. * Returns a negative integer, zero, or a positive integer as per String.compareTo(); * * @param o Object to compare to * @return a negative integer, zero, or a positive integer. */ @Override public int compareTo(final PluginInfo o) { return toString().compareTo(o.toString()); } }
public boolean checkRequirements() { if (metaData == null) { // No meta-data, so no requirements. return true; } final String uiPackage; if (Main.getUI().getClass().getPackage() != null) { uiPackage = Main.getUI().getClass().getPackage().getName(); } else { final String uiController = Main.getUI().getClass().getName(); if (uiController.lastIndexOf('.') >= 0) { uiPackage = uiController.substring(0,uiController.lastIndexOf('.')); } else { uiPackage = uiController; } } if (!checkMinimumVersion(getMinVersion(), Main.SVN_REVISION) || !checkMaximumVersion(getMaxVersion(), Main.SVN_REVISION) || !checkOS(getMetaInfo(new String[]{"required-os", "require-os"}), System.getProperty("os.name"), System.getProperty("os.version"), System.getProperty("os.arch")) || !checkFiles(getMetaInfo(new String[]{"required-files", "require-files", "required-file", "require-file"})) || !checkUI(getMetaInfo(new String[]{"required-ui", "require-ui"}), uiPackage) || !checkPlugins(getMetaInfo(new String[]{"required-plugins", "require-plugins", "required-plugin", "require-plugin"})) ) { return false; } // All requirements passed, woo \o return true; } /** * Is this plugin loaded? */ public boolean isLoaded() { return (plugin != null) && !tempLoaded; } /** * Is this plugin temporarily loaded? */ public boolean isTempLoaded() { return (plugin != null) && tempLoaded; } /** * Load entire plugin. * This loads all files in the jar immediately. * * @throws PluginException if there is an error with the resourcemanager */ private void loadEntirePlugin() throws PluginException { // Load the main "Plugin" from the jar loadPlugin(); // Now load all the rest. for (String classname : myClasses) { loadClass(classname); } } /** * Try to Load the plugin files temporarily. */ public void loadPluginTemp() { tempLoaded = true; loadPlugin(); } /** * Load any required plugins */ public void loadRequired() { final String required = getMetaInfo(new String[]{"required-plugins", "require-plugins", "required-plugin", "require-plugin"}); for (String plugin : required.split(",")) { final String[] data = plugin.split(":"); if (!data[0].trim().isEmpty()) { final PluginInfo pi = PluginManager.getPluginManager().getPluginInfoByName(data[0], true); if (pi == null) { return; } if (tempLoaded) { pi.loadPluginTemp(); } else { pi.loadPlugin(); } } } } /** * Load the plugin files. */ public void loadPlugin() { if (isTempLoaded()) { tempLoaded = false; loadRequired(); plugin.onLoad(); } else { if (isLoaded() || metaData == null || isLoading) { lastError = "Not Loading: ("+isLoaded()+"||"+(metaData == null)+"||"+isLoading+")"; return; } isLoading = true; loadRequired(); loadClass(getMainClass()); if (isLoaded()) { ActionManager.processEvent(CoreActionType.PLUGIN_LOADED, null, this); } isLoading = false; } } /** * Load the given classname. * * @param classname Class to load */ private void loadClass(final String classname) { try { if (classloader == null) { classloader = new PluginClassLoader(this); } // Don't reload a class if its already loaded. if (classloader.isClassLoaded(classname, true)) { lastError = "Classloader says we are already loaded."; return; } final Class<?> c = classloader.loadClass(classname); final Constructor<?> constructor = c.getConstructor(new Class[] {}); // Only try and construct the main class, anything else should be constructed // by the plugin itself. if (classname.equals(getMainClass())) { final Object temp = constructor.newInstance(new Object[] {}); if (temp instanceof Plugin) { final ValidationResponse prerequisites = ((Plugin) temp).checkPrerequisites(); if (!prerequisites.isFailure()) { plugin = (Plugin) temp; if (!tempLoaded) { try { plugin.onLoad(); } catch (Exception e) { lastError = "Error in onLoad for "+getName()+":"+e.getMessage(); Logger.userError(ErrorLevel.MEDIUM, lastError, e); unloadPlugin(); } } } else { if (!tempLoaded) { lastError = "Prerequisites for plugin not met. ('"+filename+":"+getMainClass()+"' -> '"+prerequisites.getFailureReason()+"') "; Logger.userError(ErrorLevel.LOW, lastError); } } } } } catch (ClassNotFoundException cnfe) { lastError = "Class not found ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+cnfe.getMessage(); Logger.userError(ErrorLevel.LOW, lastError, cnfe); } catch (NoSuchMethodException nsme) { // Don't moan about missing constructors for any class thats not the main Class lastError = "Constructor missing ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+nsme.getMessage(); if (classname.equals(getMainClass())) { Logger.userError(ErrorLevel.LOW, lastError, nsme); } } catch (IllegalAccessException iae) { lastError = "Unable to access constructor ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+iae.getMessage(); Logger.userError(ErrorLevel.LOW, lastError, iae); } catch (InvocationTargetException ite) { lastError = "Unable to invoke target ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+ite.getMessage(); Logger.userError(ErrorLevel.LOW, lastError, ite); } catch (InstantiationException ie) { lastError = "Unable to instantiate plugin ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+ie.getMessage(); Logger.userError(ErrorLevel.LOW, lastError, ie); } catch (NoClassDefFoundError ncdf) { lastError = "Unable to instantiate plugin ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - Unable to find class: " + ncdf.getMessage(); Logger.userError(ErrorLevel.LOW, lastError, ncdf); } catch (VerifyError ve) { lastError = "Unable to instantiate plugin ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - Incompatible: "+ve.getMessage(); Logger.userError(ErrorLevel.LOW, lastError, ve); } } /** * Unload the plugin if possible. */ public void unloadPlugin() { if (!isPersistent() && (isLoaded() || isTempLoaded())) { if (!isTempLoaded()) { try { plugin.onUnload(); } catch (Exception e) { lastError = "Error in onUnload for "+getName()+":"+e.getMessage(); Logger.userError(ErrorLevel.MEDIUM, lastError, e); } ActionManager.processEvent(CoreActionType.PLUGIN_UNLOADED, null, this); } tempLoaded = false; plugin = null; classloader = null; } } /** * Get the last Error * * @return last Error * @since 0.6 */ public String getLastError() { return lastError; } /** * Get the list of Classes * * @return Classes this plugin has */ public List<String> getClassList() { return myClasses; } /** * Get the main Class * * @return Main Class to begin loading. */ public String getMainClass() { return metaData.getProperty("mainclass",""); } /** * Get the Plugin for this plugin. * * @return Plugin */ public Plugin getPlugin() { return plugin; } /** * Get the PluginClassLoader for this plugin. * * @return PluginClassLoader */ protected PluginClassLoader getPluginClassLoader() { return classloader; } /** * Get the plugin friendly version * * @return Plugin friendly Version */ public String getFriendlyVersion() { return metaData.getProperty("friendlyversion", String.valueOf(getVersion())); } /** * Get the plugin version * * @return Plugin Version */ public int getVersion() { try { return Integer.parseInt(metaData.getProperty("version","0")); } catch (NumberFormatException nfe) { return -1; } } /** * Get the id for this plugin on the addons site. * If a plugin has been submitted to addons.dmdirc.com, and plugin.info * contains a property addonid then this will return it. * This is used along with the version property to allow the auto-updater to * update the addon if the author submits a new version to the addons site. * * @return Addon Site ID number * -1 If not present * -2 If non-integer */ public int getAddonID() { try { return Integer.parseInt(metaData.getProperty("addonid","-1")); } catch (NumberFormatException nfe) { return -2; } } /** * Is this a persistent plugin? * * @return true if persistent, else false */ public boolean isPersistent() { final String persistence = metaData.getProperty("persistent","no"); return persistence.equalsIgnoreCase("true") || persistence.equalsIgnoreCase("yes"); } /** * Does this plugin contain any persistent classes? * * @return true if this plugin contains any persistent classes, else false */ public boolean hasPersistent() { final String persistence = metaData.getProperty("persistent","no"); if (persistence.equalsIgnoreCase("true")) { return true; } else { for (Object keyObject : metaData.keySet()) { if (keyObject.toString().toLowerCase().startsWith("persistent-")) { return true; } } } return false; } /** * Get a list of all persistent classes in this plugin * * @return List of all persistent classes in this plugin */ public List<String> getPersistentClasses() { final List<String> result = new ArrayList<String>(); final String persistence = metaData.getProperty("persistent","no"); if (persistence.equalsIgnoreCase("true")) { try { ResourceManager res = getResourceManager(); for (final String filename : res.getResourcesStartingWith("")) { if (filename.matches("^.*\\.class$")) { result.add(filename.replaceAll("\\.class$", "").replace('/', '.')); } } } catch (IOException e) { // Jar no longer exists? } } else { for (Object keyObject : metaData.keySet()) { if (keyObject.toString().toLowerCase().startsWith("persistent-")) { result.add(keyObject.toString().substring(11)); } } } return result; } /** * Is this a persistent class? * * @param classname class to check persistence of * @return true if file (or whole plugin) is persistent, else false */ public boolean isPersistent(final String classname) { if (isPersistent()) { return true; } else { final String persistence = metaData.getProperty("persistent-"+classname,"no"); return persistence.equalsIgnoreCase("true") || persistence.equalsIgnoreCase("yes"); } } /** * Get the plugin Filename. * * @return Filename of plugin */ public String getFilename() { return filename; } /** * Get the full plugin Filename (inc dirname) * * @return Filename of plugin */ public String getFullFilename() { return url.getPath(); } /** * Get the plugin Author. * * @return Author of plugin */ public String getAuthor() { return getMetaInfo("author",""); } /** * Get the plugin Description. * * @return Description of plugin */ public String getDescription() { return getMetaInfo("description",""); } /** * Get the minimum dmdirc version required to run the plugin. * * @return minimum dmdirc version required to run the plugin. */ public String getMinVersion() { return getMetaInfo("minversion",""); } /** * Get the (optional) maximum dmdirc version on which this plugin can run * * @return optional maximum dmdirc version on which this plugin can run */ public String getMaxVersion() { return getMetaInfo("maxversion",""); } /** * Get the name of the plugin. (Used to identify the plugin) * * @return Name of plugin */ public String getName() { return getMetaInfo("name",""); } /** * Get the nice name of the plugin. (Displayed to users) * * @return Nice Name of plugin */ public String getNiceName() { return getMetaInfo("nicename",getName()); } /** * String Representation of this plugin * * @return String Representation of this plugin */ @Override public String toString() { return getNiceName()+" - "+filename; } /** * Does this plugin want all its classes loaded? * * @return true/false if loadall=true || loadall=yes */ public boolean loadAll() { final String loadAll = metaData.getProperty("loadall","no"); return loadAll.equalsIgnoreCase("true") || loadAll.equalsIgnoreCase("yes"); } /** * Get misc meta-information. * * @param metainfo The metainfo to return * @return Misc Meta Info (or "" if not found); */ public String getMetaInfo(final String metainfo) { return getMetaInfo(metainfo,""); } /** * Get misc meta-information. * * @param metainfo The metainfo to return * @param fallback Fallback value if requested value is not found * @return Misc Meta Info (or fallback if not found); */ public String getMetaInfo(final String metainfo, final String fallback) { return metaData.getProperty(metainfo,fallback); } /** * Get misc meta-information. * * @param metainfo The metainfos to look for in order. If the first item in * the array is not found, the next will be looked for, and * so on until either one is found, or none are found. * @return Misc Meta Info (or "" if none are found); */ public String getMetaInfo(final String[] metainfo) { return getMetaInfo(metainfo,""); } /** * Get misc meta-information. * * @param metainfo The metainfos to look for in order. If the first item in * the array is not found, the next will be looked for, and * so on until either one is found, or none are found. * @param fallback Fallback value if requested values are not found * @return Misc Meta Info (or "" if none are found); */ public String getMetaInfo(final String[] metainfo, final String fallback) { for (String meta : metainfo) { String result = metaData.getProperty(meta); if (result != null) { return result; } } return fallback; } /** * Compares this object with the specified object for order. * Returns a negative integer, zero, or a positive integer as per String.compareTo(); * * @param o Object to compare to * @return a negative integer, zero, or a positive integer. */ @Override public int compareTo(final PluginInfo o) { return toString().compareTo(o.toString()); } }
diff --git a/Writable.java b/Writable.java index 45f5a66..2e81c15 100644 --- a/Writable.java +++ b/Writable.java @@ -1,764 +1,764 @@ package me.exphc.Writable; import java.util.Collections; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.UUID; import java.util.Iterator; import java.util.logging.Logger; import java.util.concurrent.ConcurrentHashMap; import java.util.Formatter; import java.lang.Byte; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.io.*; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.*; import org.bukkit.event.*; import org.bukkit.event.block.*; import org.bukkit.event.player.*; import org.bukkit.Material.*; import org.bukkit.material.*; import org.bukkit.block.*; import org.bukkit.entity.*; import org.bukkit.command.*; import org.bukkit.inventory.*; import org.bukkit.configuration.*; import org.bukkit.configuration.file.*; import org.bukkit.scheduler.*; import org.bukkit.*; enum WritingState { NOT_WRITING, // initial state, timed out, or finished writing CLICKED_PAPER, // onPlayerInteract(), when right-click paper PLACED_SIGN, // onBlockPlace(), when placed temporary sign // onSignChange(), after wrote sign } class WritableSignPlaceTimeoutTask implements Runnable { static public ConcurrentHashMap<Player, Integer> taskIDs = new ConcurrentHashMap<Player, Integer>(); static Logger log = Logger.getLogger("Minecraft"); Player player; public WritableSignPlaceTimeoutTask(Player p) { player = p; } public void run() { if (Writable.getWritingState(player) != WritingState.PLACED_SIGN) { log.info("did not place sign in time"); WritablePlayerListener.restoreSavedItem(player); Writable.setWritingState(player, WritingState.NOT_WRITING); } WritableSignPlaceTimeoutTask.taskIDs.remove(player); } } class WritablePlayerListener extends PlayerListener { Logger log = Logger.getLogger("Minecraft"); Writable plugin; static private ConcurrentHashMap<Player, ItemStack> savedItemStack = new ConcurrentHashMap<Player, ItemStack>(); static private ConcurrentHashMap<Player, Integer> savedItemSlot = new ConcurrentHashMap<Player, Integer>(); static public ConcurrentHashMap<Player, ChatColor> currentColor = new ConcurrentHashMap<Player, ChatColor>(); public WritablePlayerListener(Writable pl) { plugin = pl; } public void onPlayerInteract(PlayerInteractEvent event) { Block block = event.getClickedBlock(); ItemStack item = event.getItem(); Player player = event.getPlayer(); Action action = event.getAction(); if (item != null && item.getType() == Material.PAPER && action == Action.RIGHT_CLICK_BLOCK) { if (Writable.getWritingState(player) != WritingState.NOT_WRITING) { player.sendMessage("You are already writing"); // TODO: stop other writing, restore (like timeout), cancel task? return; } // TODO: prevent writing on >1 stacks? or try to shuffle around? // Check block to ensure is realistically hard surface to write on (stone, not gravel or sand, etc.) if (!plugin.isWritingSurface(block)) { player.sendMessage("You need a hard surface to write on, not "+block.getType().toString().toLowerCase()); return; } // Check if have writing implement and ink int implementSlot = Writable.findImplementSlot(player); if (implementSlot == -1) { player.sendMessage("To write, you must have a writing implement in your hotbar"); return; } int inkSlot = Writable.findInkSlot(player, implementSlot); if (inkSlot == -1) { ItemStack implementItem = player.getInventory().getItem(implementSlot); log.info("slot"+implementSlot); player.sendMessage("To write, place ink next to the " + implementItem.getType().toString().toLowerCase() + " in your inventory"); return; } ItemStack inkItem = player.getInventory().getItem(inkSlot); ChatColor color = Writable.getChatColor(inkItem); - // TODO: optionally use up ink + // Optionally use up ink if (plugin.isInkConsumable()) { int amount = inkItem.getAmount(); if (amount > 1) { - log.info("dec"); inkItem.setAmount(amount - 1); } else { - log.info("set0"); - player.getInventory().setItem(inkSlot, null); + player.getInventory().clear(inkSlot); } + // Docs say deprecated and should not be relied on, but, client won't update without it + player.updateInventory(); } // If blank, assign new ID short id = item.getDurability(); if (id == 0) { id = plugin.getNewPaperID(); item.setDurability(id); } else { if (Writable.isPaperFull(id)) { player.sendMessage("Sorry, this paper is full"); return; } } player.sendMessage(color+"Right-click to write on paper #"+id); // Save off old item in hand to restore, and ink color to use savedItemStack.put(player, item); savedItemSlot.put(player, player.getInventory().getHeldItemSlot()); currentColor.put(player, color); // Quickly change to sign, so double right-click paper = place sign to write on player.setItemInHand(new ItemStack(Material.SIGN, 1)); // TODO: if have >1, save off old paper? Writable.setWritingState(player, WritingState.CLICKED_PAPER); // Timeout to NOT_WRITING if our sign isn't used in a sufficient time WritableSignPlaceTimeoutTask task = new WritableSignPlaceTimeoutTask(player); int taskID = Bukkit.getScheduler().scheduleAsyncDelayedTask(plugin, task, plugin.getConfig().getLong("signTimeout", 2*20)); // Save task to cancel if did in fact make it to PLACED_SIGN in time WritableSignPlaceTimeoutTask.taskIDs.put(player, taskID); } } // Restore previous item held by player, before started writing (do not use setItemInHand()) // Returns items restored static public ItemStack restoreSavedItem(Player player) { ItemStack items = savedItemStack.get(player); int slot = savedItemSlot.get(player); player.getInventory().setItem(slot, items); savedItemStack.remove(player); savedItemSlot.remove(player); currentColor.remove(player); return items; } static public void readPaperToPlayer(Player player, int id) { if (id == 0) { player.sendMessage("Double right-click to write on this blank paper"); return; } ArrayList<String> lines = Writable.readPaper(id); if (lines.size() == 0) { player.sendMessage("Paper #"+id+" is blank"); return; } player.sendMessage("Reading paper #"+id+":"); for (String line: lines) { player.sendMessage(" "+line); } // Chat shows 10 recent lines normally // can press 't' to show 20 recent lines if (lines.size() > 10) { player.sendMessage("Press 't' to show the full text of paper #"+id); } // Text on paper is meant to only fit in one chat screen, so no pagination needed } // When change to in inventory slot, read back public void onItemHeldChange(PlayerItemHeldEvent event) { Player player = event.getPlayer(); ItemStack item = player.getInventory().getItem(event.getNewSlot()); if (item != null && item.getType() == Material.PAPER) { int id = item.getDurability(); // TODO: only if not zero readPaperToPlayer(player, id); } } // If pickup a paper with writing on it, let know public void onPlayerPickupItem(PlayerPickupItemEvent event) { ItemStack item = event.getItem().getItemStack(); if (item != null && item.getType() == Material.PAPER) { if (item.getDurability() != 0) { event.getPlayer().sendMessage("You picked up paper, mysteriously scribbled"); } } } } class WritableBlockListener extends BlockListener { Logger log = Logger.getLogger("Minecraft"); Writable plugin; public WritableBlockListener(Writable pl) { plugin = pl; } public void onBlockPlace(BlockPlaceEvent event) { Block block = event.getBlock(); Player player = event.getPlayer(); if (block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN_POST) { WritingState state = Writable.getWritingState(player); // Did they get this sign from right-clicking paper? if (state == WritingState.CLICKED_PAPER) { // We made it, stop timeout task (so won't revert to NOT_WRITING and take back sign) int taskID = WritableSignPlaceTimeoutTask.taskIDs.get(player); WritableSignPlaceTimeoutTask.taskIDs.remove(player); Bukkit.getScheduler().cancelTask(taskID); Writable.setWritingState(player, WritingState.PLACED_SIGN); // TODO: store paper ID } else { log.info("Place non-paper sign"); } } } public void onSignChange(SignChangeEvent event) { Block block = event.getBlock(); Player player = event.getPlayer(); String[] lines = event.getLines(); WritingState state = Writable.getWritingState(player); if (state != WritingState.PLACED_SIGN) { log.info("Changing sign not from paper"); return; } // This sign text came from a sign from clicking paper // Destroy sign block.setType(Material.AIR); ChatColor color = WritablePlayerListener.currentColor.get(player); // Restore previous item ItemStack paperItem = WritablePlayerListener.restoreSavedItem(player); // Write int id = paperItem.getDurability(); plugin.writePaper(id, lines, color); // Finish up Writable.setWritingState(player, WritingState.NOT_WRITING); WritablePlayerListener.readPaperToPlayer(player, id); } } // Like Material, but also has MaterialData // Like ItemStack, but different data is different! class MaterialWithData implements Comparable { int material; byte data; public MaterialWithData(Material m, MaterialData d) { material = m.getId(); data = d.getData(); } public MaterialWithData(Material m) { material = m.getId(); data = 0; } public int hashCode() { return material * data; } public boolean equals(Object rhs) { return compareTo(rhs) == 0; } public int compareTo(Object obj) { int ret; if (!(obj instanceof MaterialWithData)) { return -1; } MaterialWithData rhs = (MaterialWithData)obj; ret = material - rhs.material; if (ret != 0) { return ret; } return data - rhs.data; } public String toString() { return "MaterialWithData("+material+","+data+")"; } } public class Writable extends JavaPlugin { static Logger log = Logger.getLogger("Minecraft"); WritablePlayerListener playerListener; WritableBlockListener blockListener; static private ConcurrentHashMap<Player, WritingState> writingState; static private ConcurrentHashMap<Integer, ArrayList<String>> paperTexts; // TODO: paper class? static private List<Material> writingImplementMaterials; static private List<Material> writingSurfaceMaterials; static private HashMap<MaterialWithData,ChatColor> inkColors; static private short nextPaperID; static private int paperLengthLineCap; static private boolean consumeInk; public void onEnable() { writingState = new ConcurrentHashMap<Player, WritingState>(); loadConfig(); playerListener = new WritablePlayerListener(this); blockListener = new WritableBlockListener(this); Bukkit.getPluginManager().registerEvent(Event.Type.PLAYER_INTERACT, playerListener, org.bukkit.event.Event.Priority.Normal, this); Bukkit.getPluginManager().registerEvent(Event.Type.PLAYER_ITEM_HELD, playerListener, org.bukkit.event.Event.Priority.Normal, this); Bukkit.getPluginManager().registerEvent(Event.Type.PLAYER_PICKUP_ITEM, playerListener, org.bukkit.event.Event.Priority.Normal, this); Bukkit.getPluginManager().registerEvent(Event.Type.SIGN_CHANGE, blockListener, org.bukkit.event.Event.Priority.Normal, this); Bukkit.getPluginManager().registerEvent(Event.Type.BLOCK_PLACE, blockListener, org.bukkit.event.Event.Priority.Normal, this); configurePaperStacking(); log.info("Writable enabled"); } private void loadConfig() { getConfig().options().copyDefaults(true); saveConfig(); List<String> implementsStrings = getConfig().getStringList("writingImplements"); writingImplementMaterials = new ArrayList<Material>(); for (String implementString: implementsStrings) { Material implementMaterial = Material.matchMaterial(implementString); if (implementMaterial == null) { log.info("Invalid implement material: " + implementString); // TODO: error continue; } writingImplementMaterials.add(implementMaterial); } List<String> surfacesStrings = getConfig().getStringList("writingSurfaces"); writingSurfaceMaterials = new ArrayList<Material>(); for (String surfaceString: surfacesStrings) { Material surfaceMaterial = Material.matchMaterial(surfaceString); if (surfaceMaterial == null) { log.info("Invalid surface material: " + surfaceString); // TODO: error; continue; } writingSurfaceMaterials.add(surfaceMaterial); } MemorySection inksSection = (MemorySection)getConfig().get("inks"); Map<String,Object> inksMap = inksSection.getValues(true); inkColors = new HashMap<MaterialWithData,ChatColor>(); Iterator it = inksMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry)it.next(); String inkString = (String)pair.getKey(); String colorString = (String)pair.getValue(); MaterialWithData ink = lookupInk(inkString); if (ink == null) { log.info("Invalid ink item: " + inkString); // TODO: error continue; } ChatColor inkColor = ChatColor.valueOf(colorString.toUpperCase()); if (inkColor == null) { log.info("Invalid ink color: " + colorString); // TODO: error continue; } inkColors.put(ink, inkColor); } nextPaperID = (short)getConfig().getInt("nextPaperID", 1); paperLengthLineCap = getConfig().getInt("paperLengthLineCap", 7); consumeInk = getConfig().getBoolean("consumeInk", false); loadPapers(); } private MaterialWithData lookupInk(String s) { Material material = Material.matchMaterial(s); if (material != null) { return new MaterialWithData(material); } DyeColor dyeColor = getDyeColor(s); if (dyeColor == null) { dyeColor = getDyeColor(s.replace("_dye", "")); } if (dyeColor != null) { Dye data = new Dye(); data.setColor(dyeColor); ItemStack item = data.toItemStack(); return new MaterialWithData(item.getType(), item.getData()); } return null; } private DyeColor getDyeColor(String s) { // Unfortunately Bukkit doesn't have these names anywhere I can find // http://www.minecraftwiki.net/wiki/Data_values#Dyes if (s.equals("ink_sac")) { return DyeColor.BLACK; } else if (s.equals("rose_red")) { return DyeColor.RED; } else if (s.equals("cactus_green")) { return DyeColor.GREEN; } else if (s.equals("cocoa_beans")) { return DyeColor.BROWN; } else if (s.equals("lapis_lazuli")) { return DyeColor.BLUE; } else if (s.equals("purple")) { return DyeColor.PURPLE; } else if (s.equals("cyan")) { return DyeColor.CYAN; } else if (s.equals("light_gray")) { return DyeColor.SILVER; } else if (s.equals("gray")) { return DyeColor.GRAY; } else if (s.equals("pink")) { return DyeColor.PINK; } else if (s.equals("lime")) { return DyeColor.LIME; } else if (s.equals("dandelion_yellow")) { return DyeColor.YELLOW; } else if (s.equals("light_blue")) { return DyeColor.LIGHT_BLUE; } else if (s.equals("magenta")) { return DyeColor.MAGENTA; } else if (s.equals("orange")) { return DyeColor.ORANGE; } else if (s.equals("bone_meal")) { return DyeColor.WHITE; } try { return DyeColor.valueOf(s); } catch (Exception e) { return null; } } // Find writing implement in player's inventory and matching ink color public static int findImplementSlot(Player player) { PlayerInventory inventory = player.getInventory(); for (int i = 0; i < 9; i += 1) { ItemStack implementItem = inventory.getItem(i); if (isWritingImplement(implementItem)) { return i; } } return -1; } // Get nearby ink next to writing implement in inventory, if any public static int findInkSlot(Player player, int implementSlot) { PlayerInventory inventory = player.getInventory(); ItemStack inkItem; int inkSlot; inkSlot = implementSlot - 1; if (inkSlot > 0) { inkItem = inventory.getItem(inkSlot); log.info("findInkSlot-1="+inkItem+"s"+inkSlot); if (getChatColor(inkItem) != null) { return inkSlot; } } inkSlot = implementSlot + 1; inkItem = inventory.getItem(inkSlot); log.info("findInkSlot+1="+inkItem+"s"+inkSlot); if (getChatColor(inkItem) != null) { return inkSlot; } return -1; } private static boolean isWritingImplement(ItemStack item) { return writingImplementMaterials.contains(item.getType()); } public static boolean isWritingSurface(Block block) { return writingSurfaceMaterials.contains(block.getType()); } // Get chat color used for given writing ink public static ChatColor getChatColor(ItemStack item) { ChatColor color = inkColors.get(new MaterialWithData(item.getType(), item.getData())); return color; } // Try to make paper stack by damage ID, or otherwise stack by one // Based on http://code.google.com/p/nisovin-minecraft-bukkit-plugins/source/browse/trunk/BookWorm/src/com/nisovin/bookworm/BookWorm.java // http://dev.bukkit.org/server-mods/bookworm/ private void configurePaperStacking() { try { boolean ok = false; // attempt to make papers with different data values stack separately try { // obfuscated method name, check BookWorm for updates String methodName = getConfig().getString("stack-by-data-fn", "a");//"bQ"); Method method = net.minecraft.server.Item.class.getDeclaredMethod(methodName, boolean.class); if (method.getReturnType() == net.minecraft.server.Item.class) { method.setAccessible(true); method.invoke(net.minecraft.server.Item.PAPER, true); ok = true; } } catch (Exception e) { log.info("Not stacking papers together"); } if (!ok) { // otherwise limit stack size to 1 Field field = net.minecraft.server.Item.class.getDeclaredField("maxStackSize"); field.setAccessible(true); field.setInt(net.minecraft.server.Item.PAPER, 1); } else { log.info("Successfully changed paper stacking"); } } catch (Exception e) { e.printStackTrace(); } } public void onDisable() { saveConfig(); log.info("Writable disabled"); } // Manipulate state machine static public void setWritingState(Player player, WritingState newState) { WritingState oldState = getWritingState(player); //log.info("State change "+player.getName()+": "+oldState+" -> "+newState); if (newState == WritingState.NOT_WRITING) { writingState.remove(player); } else { writingState.put(player, newState); } } static public WritingState getWritingState(Player player) { WritingState state = writingState.get(player); return state == null ? WritingState.NOT_WRITING : state; } // Manipulate paper text public void writePaper(int id, String[] newLines, ChatColor color) { ArrayList<String> lines = readPaper(id); lines.addAll(formatLines(newLines, color)); paperTexts.put(new Integer(id), lines); savePaper(id); } // Format 4x15 sign text reasonably into paragraphs public ArrayList<String> formatLines(String[] inLines, ChatColor color) { ArrayList<String> outLines = new ArrayList<String>(); final int MAX_SIGN_LINE_LENGTH = 15; StringBuffer lineBuffer = new StringBuffer(); // Add lines intelligently for (int i = 0; i < inLines.length; i += 1) { String line = inLines[i]; // Blank line = new paragraph if (line == null || line.equals("")) { // unless blank themselves if (lineBuffer.toString().length() != 0) { outLines.add(color + lineBuffer.toString()); lineBuffer = new StringBuffer(); } } else { // Text lines = concatenate lineBuffer.append(line); if (line.length() < MAX_SIGN_LINE_LENGTH) { // Not at limit, add spacing // (if hit limit, probably not a word break) lineBuffer.append(" "); } } } if (lineBuffer.toString().length() != 0) { outLines.add(color + lineBuffer.toString()); } return outLines; } // Write paper contents to disk public void savePaper(int id) { String path = pathForPaper(id); log.info("saving to "+path); try { BufferedWriter out = new BufferedWriter(new FileWriter(path)); ArrayList<String> lines = readPaper(id); for (String line: lines) { out.write(line); out.newLine(); } out.close(); } catch (IOException e) { log.info("Error saving #"+id+": "+e.getMessage()); } } private String pathForPaper(int id) { String filename = String.format("%4x", id).replace(" ","0"); // TODO: %.4x String path = getDataFolder() + System.getProperty("file.separator") + filename + ".txt"; return path; } private ArrayList<String> loadPaper(int id) { String path = pathForPaper(id); ArrayList<String> lines = new ArrayList<String>(); try { BufferedReader in = new BufferedReader(new FileReader(path)); String line; do { line = in.readLine(); if (line != null) { lines.add(line); } } while(line != null); } catch (IOException e) { log.info("Error loading paper #"+id+": "+e.getMessage()); // may have been deleted return new ArrayList<String>(); } return lines; } // Load all papers from disk private void loadPapers() { paperTexts = new ConcurrentHashMap<Integer, ArrayList<String>>(); for (int i = 1; i < nextPaperID; i += 1) { ArrayList<String> lines = loadPaper(i); paperTexts.put(i, lines); } } static public ArrayList<String> readPaper(int id) { ArrayList<String> lines = paperTexts.get(id); if (lines == null) { return new ArrayList<String>(); // empty array } else { return lines; } } short getNewPaperID() { short id = nextPaperID; nextPaperID += 1; getConfig().set("nextPaperID", nextPaperID); saveConfig(); return id; } // Return whether more text can be written on the paper static boolean isPaperFull(int id) { ArrayList<String> lines = paperTexts.get(id); // formatLines() adds up to 2 lines of text return lines != null && lines.size() > paperLengthLineCap; } static boolean isInkConsumable() { return consumeInk; } }
false
true
public void onPlayerInteract(PlayerInteractEvent event) { Block block = event.getClickedBlock(); ItemStack item = event.getItem(); Player player = event.getPlayer(); Action action = event.getAction(); if (item != null && item.getType() == Material.PAPER && action == Action.RIGHT_CLICK_BLOCK) { if (Writable.getWritingState(player) != WritingState.NOT_WRITING) { player.sendMessage("You are already writing"); // TODO: stop other writing, restore (like timeout), cancel task? return; } // TODO: prevent writing on >1 stacks? or try to shuffle around? // Check block to ensure is realistically hard surface to write on (stone, not gravel or sand, etc.) if (!plugin.isWritingSurface(block)) { player.sendMessage("You need a hard surface to write on, not "+block.getType().toString().toLowerCase()); return; } // Check if have writing implement and ink int implementSlot = Writable.findImplementSlot(player); if (implementSlot == -1) { player.sendMessage("To write, you must have a writing implement in your hotbar"); return; } int inkSlot = Writable.findInkSlot(player, implementSlot); if (inkSlot == -1) { ItemStack implementItem = player.getInventory().getItem(implementSlot); log.info("slot"+implementSlot); player.sendMessage("To write, place ink next to the " + implementItem.getType().toString().toLowerCase() + " in your inventory"); return; } ItemStack inkItem = player.getInventory().getItem(inkSlot); ChatColor color = Writable.getChatColor(inkItem); // TODO: optionally use up ink if (plugin.isInkConsumable()) { int amount = inkItem.getAmount(); if (amount > 1) { log.info("dec"); inkItem.setAmount(amount - 1); } else { log.info("set0"); player.getInventory().setItem(inkSlot, null); } } // If blank, assign new ID short id = item.getDurability(); if (id == 0) { id = plugin.getNewPaperID(); item.setDurability(id); } else { if (Writable.isPaperFull(id)) { player.sendMessage("Sorry, this paper is full"); return; } } player.sendMessage(color+"Right-click to write on paper #"+id); // Save off old item in hand to restore, and ink color to use savedItemStack.put(player, item); savedItemSlot.put(player, player.getInventory().getHeldItemSlot()); currentColor.put(player, color); // Quickly change to sign, so double right-click paper = place sign to write on player.setItemInHand(new ItemStack(Material.SIGN, 1)); // TODO: if have >1, save off old paper? Writable.setWritingState(player, WritingState.CLICKED_PAPER); // Timeout to NOT_WRITING if our sign isn't used in a sufficient time WritableSignPlaceTimeoutTask task = new WritableSignPlaceTimeoutTask(player); int taskID = Bukkit.getScheduler().scheduleAsyncDelayedTask(plugin, task, plugin.getConfig().getLong("signTimeout", 2*20)); // Save task to cancel if did in fact make it to PLACED_SIGN in time WritableSignPlaceTimeoutTask.taskIDs.put(player, taskID); } }
public void onPlayerInteract(PlayerInteractEvent event) { Block block = event.getClickedBlock(); ItemStack item = event.getItem(); Player player = event.getPlayer(); Action action = event.getAction(); if (item != null && item.getType() == Material.PAPER && action == Action.RIGHT_CLICK_BLOCK) { if (Writable.getWritingState(player) != WritingState.NOT_WRITING) { player.sendMessage("You are already writing"); // TODO: stop other writing, restore (like timeout), cancel task? return; } // TODO: prevent writing on >1 stacks? or try to shuffle around? // Check block to ensure is realistically hard surface to write on (stone, not gravel or sand, etc.) if (!plugin.isWritingSurface(block)) { player.sendMessage("You need a hard surface to write on, not "+block.getType().toString().toLowerCase()); return; } // Check if have writing implement and ink int implementSlot = Writable.findImplementSlot(player); if (implementSlot == -1) { player.sendMessage("To write, you must have a writing implement in your hotbar"); return; } int inkSlot = Writable.findInkSlot(player, implementSlot); if (inkSlot == -1) { ItemStack implementItem = player.getInventory().getItem(implementSlot); log.info("slot"+implementSlot); player.sendMessage("To write, place ink next to the " + implementItem.getType().toString().toLowerCase() + " in your inventory"); return; } ItemStack inkItem = player.getInventory().getItem(inkSlot); ChatColor color = Writable.getChatColor(inkItem); // Optionally use up ink if (plugin.isInkConsumable()) { int amount = inkItem.getAmount(); if (amount > 1) { inkItem.setAmount(amount - 1); } else { player.getInventory().clear(inkSlot); } // Docs say deprecated and should not be relied on, but, client won't update without it player.updateInventory(); } // If blank, assign new ID short id = item.getDurability(); if (id == 0) { id = plugin.getNewPaperID(); item.setDurability(id); } else { if (Writable.isPaperFull(id)) { player.sendMessage("Sorry, this paper is full"); return; } } player.sendMessage(color+"Right-click to write on paper #"+id); // Save off old item in hand to restore, and ink color to use savedItemStack.put(player, item); savedItemSlot.put(player, player.getInventory().getHeldItemSlot()); currentColor.put(player, color); // Quickly change to sign, so double right-click paper = place sign to write on player.setItemInHand(new ItemStack(Material.SIGN, 1)); // TODO: if have >1, save off old paper? Writable.setWritingState(player, WritingState.CLICKED_PAPER); // Timeout to NOT_WRITING if our sign isn't used in a sufficient time WritableSignPlaceTimeoutTask task = new WritableSignPlaceTimeoutTask(player); int taskID = Bukkit.getScheduler().scheduleAsyncDelayedTask(plugin, task, plugin.getConfig().getLong("signTimeout", 2*20)); // Save task to cancel if did in fact make it to PLACED_SIGN in time WritableSignPlaceTimeoutTask.taskIDs.put(player, taskID); } }
diff --git a/contentconnector-portlet/src/main/java/com/gentics/cr/taglib/portlet/RenderContentTag.java b/contentconnector-portlet/src/main/java/com/gentics/cr/taglib/portlet/RenderContentTag.java index 1303835d..9f7d5000 100644 --- a/contentconnector-portlet/src/main/java/com/gentics/cr/taglib/portlet/RenderContentTag.java +++ b/contentconnector-portlet/src/main/java/com/gentics/cr/taglib/portlet/RenderContentTag.java @@ -1,197 +1,197 @@ package com.gentics.cr.taglib.portlet; import java.io.IOException; import java.net.URLEncoder; import java.util.Hashtable; import javax.portlet.PortletSession; import javax.portlet.RenderRequest; import javax.servlet.jsp.JspException; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.tagext.TagSupport; import org.apache.log4j.Logger; import com.gentics.api.portalnode.connector.PLinkReplacer; import com.gentics.cr.CRConfigUtil; import com.gentics.cr.CRResolvableBean; import com.gentics.cr.configuration.GenericConfiguration; import com.gentics.cr.exceptions.CRException; import com.gentics.cr.rendering.ContentRenderer; import com.gentics.cr.rendering.contentprocessor.ContentPostProcesser; /** * Implementation of a tag that renders content with plink replacing and velocity * Last changed: $Date: 2010-04-01 15:25:54 +0200 (Do, 01 Apr 2010) $ * @version $Revision: 545 $ * @author $Author: [email protected] $ * */ public class RenderContentTag extends TagSupport { /** * */ private static final long serialVersionUID = -5724484220477278975L; private Logger logger = Logger.getLogger("com.gentics.cr.rendering"); /** * Name of the render request attribute for the instance of {@link ContentRenderer} */ public final static String RENDERER_PARAM = "rendercontenttag.renderer"; /** * Name of the config attribute for the instance of {@link GenericConfiguration} */ public final static String CRCONF_PARAM = "rendercontenttag.crconf"; /** * Name of the request attribute for the instance of {@link RenderRequest} */ public final static String REQUEST_PARAM = "rendercontenttag.request"; /** * Name of the render request attribute for the instance of {@link PLinkReplacer} */ public final static String PLINK_PARAM = "rendercontenttag.plinkreplacer"; /** * Rendered object */ protected CRResolvableBean object; /** * */ public static final String SESSION_KEY_CONTENTPOSTPROCESSOR_CONF = RenderContentTag.class.getName() + "|ContentPostProcessor|confs"; /** * name of the rendered attribute */ protected String contentAttribute = "content"; protected String var = null; /** * flag if the output should be urlencoded */ protected boolean urlencode = false; /** * Set the object to be rendered. Must be an instance of {@link CRResolvableBean}. * @param object rendered object */ public void setObject(Object object) { if (object instanceof CRResolvableBean) { this.object = (CRResolvableBean) object; } } /** * Set the content attribute to be rendered * @param contentAttribute name of the rendered content attribute */ public void setContentAttribute(String contentAttribute) { this.contentAttribute = contentAttribute; } /** * Set the flag if the returned content should be url-encoded * @param urlencode * */ public void setUrlencode(String urlencode) { this.urlencode = "true".equals(urlencode); } /** * * @param var */ public void setVar(String var) { this.var = var; } /** * @return * @throws JspException * @see javax.servlet.jsp.tagext.SimpleTagSupport#doTag() */ public int doEndTag() throws JspException { // get the ContentRenderer RenderRequest renderRequest = getRenderRequest(); PortletSession session = renderRequest.getPortletSession(); ContentRenderer renderer = (ContentRenderer)renderRequest.getAttribute(RENDERER_PARAM); PLinkReplacer pLinkReplacer = (PLinkReplacer)renderRequest.getAttribute(PLINK_PARAM); CRConfigUtil crConf = (CRConfigUtil)renderRequest.getAttribute(CRCONF_PARAM); try { if (object != null) { try { String content = renderer.renderContent(object, contentAttribute, true, pLinkReplacer, false, null); /* Get the ContentPostProcessor-Config from the PortletSession or instance it from the Config*/ @SuppressWarnings("unchecked") Hashtable<String,ContentPostProcesser> confs = (Hashtable<String, ContentPostProcesser>) session.getAttribute(SESSION_KEY_CONTENTPOSTPROCESSOR_CONF, PortletSession.APPLICATION_SCOPE); if (confs == null){ confs = ContentPostProcesser.getProcessorTable(crConf); if (confs != null){ session.setAttribute(SESSION_KEY_CONTENTPOSTPROCESSOR_CONF, confs, PortletSession.APPLICATION_SCOPE); logger.debug("Put ContentPostProcessor config into session of " + crConf.getName() + "!"); } } if (confs != null) { for(ContentPostProcesser p:confs.values()) { content = p.processString(content, renderRequest); } } - if (urlencode) { + if (urlencode && content!=null) { content = URLEncoder.encode(content, "UTF-8"); } if (var != null) { if (content!=null && "".equals(content)) { content = null; } pageContext.setAttribute(var, content, PageContext.REQUEST_SCOPE); } else { pageContext.getOut().write(content); } } catch (CRException e) { throw new JspException("Error while rendering object " + object.getContentid(), e); } } else { pageContext.getOut().write(" -- no object set --"); } }catch(IOException e){ e.printStackTrace(); } return super.doEndTag(); } /** * Get the render request * * @return render request * @throws JspException * when the render request could not be found */ protected RenderRequest getRenderRequest() throws JspException { Object renderRequestObject = pageContext.findAttribute( "javax.portlet.request"); if (renderRequestObject instanceof RenderRequest) { return (RenderRequest) renderRequestObject; } else { throw new JspException( "Error while rendering tag: could not find javax.portlet.request"); } } }
true
true
public int doEndTag() throws JspException { // get the ContentRenderer RenderRequest renderRequest = getRenderRequest(); PortletSession session = renderRequest.getPortletSession(); ContentRenderer renderer = (ContentRenderer)renderRequest.getAttribute(RENDERER_PARAM); PLinkReplacer pLinkReplacer = (PLinkReplacer)renderRequest.getAttribute(PLINK_PARAM); CRConfigUtil crConf = (CRConfigUtil)renderRequest.getAttribute(CRCONF_PARAM); try { if (object != null) { try { String content = renderer.renderContent(object, contentAttribute, true, pLinkReplacer, false, null); /* Get the ContentPostProcessor-Config from the PortletSession or instance it from the Config*/ @SuppressWarnings("unchecked") Hashtable<String,ContentPostProcesser> confs = (Hashtable<String, ContentPostProcesser>) session.getAttribute(SESSION_KEY_CONTENTPOSTPROCESSOR_CONF, PortletSession.APPLICATION_SCOPE); if (confs == null){ confs = ContentPostProcesser.getProcessorTable(crConf); if (confs != null){ session.setAttribute(SESSION_KEY_CONTENTPOSTPROCESSOR_CONF, confs, PortletSession.APPLICATION_SCOPE); logger.debug("Put ContentPostProcessor config into session of " + crConf.getName() + "!"); } } if (confs != null) { for(ContentPostProcesser p:confs.values()) { content = p.processString(content, renderRequest); } } if (urlencode) { content = URLEncoder.encode(content, "UTF-8"); } if (var != null) { if (content!=null && "".equals(content)) { content = null; } pageContext.setAttribute(var, content, PageContext.REQUEST_SCOPE); } else { pageContext.getOut().write(content); } } catch (CRException e) { throw new JspException("Error while rendering object " + object.getContentid(), e); } } else { pageContext.getOut().write(" -- no object set --"); } }catch(IOException e){ e.printStackTrace(); } return super.doEndTag(); }
public int doEndTag() throws JspException { // get the ContentRenderer RenderRequest renderRequest = getRenderRequest(); PortletSession session = renderRequest.getPortletSession(); ContentRenderer renderer = (ContentRenderer)renderRequest.getAttribute(RENDERER_PARAM); PLinkReplacer pLinkReplacer = (PLinkReplacer)renderRequest.getAttribute(PLINK_PARAM); CRConfigUtil crConf = (CRConfigUtil)renderRequest.getAttribute(CRCONF_PARAM); try { if (object != null) { try { String content = renderer.renderContent(object, contentAttribute, true, pLinkReplacer, false, null); /* Get the ContentPostProcessor-Config from the PortletSession or instance it from the Config*/ @SuppressWarnings("unchecked") Hashtable<String,ContentPostProcesser> confs = (Hashtable<String, ContentPostProcesser>) session.getAttribute(SESSION_KEY_CONTENTPOSTPROCESSOR_CONF, PortletSession.APPLICATION_SCOPE); if (confs == null){ confs = ContentPostProcesser.getProcessorTable(crConf); if (confs != null){ session.setAttribute(SESSION_KEY_CONTENTPOSTPROCESSOR_CONF, confs, PortletSession.APPLICATION_SCOPE); logger.debug("Put ContentPostProcessor config into session of " + crConf.getName() + "!"); } } if (confs != null) { for(ContentPostProcesser p:confs.values()) { content = p.processString(content, renderRequest); } } if (urlencode && content!=null) { content = URLEncoder.encode(content, "UTF-8"); } if (var != null) { if (content!=null && "".equals(content)) { content = null; } pageContext.setAttribute(var, content, PageContext.REQUEST_SCOPE); } else { pageContext.getOut().write(content); } } catch (CRException e) { throw new JspException("Error while rendering object " + object.getContentid(), e); } } else { pageContext.getOut().write(" -- no object set --"); } }catch(IOException e){ e.printStackTrace(); } return super.doEndTag(); }
diff --git a/src/main/java/org/example/websocket/server/WebSocketServer.java b/src/main/java/org/example/websocket/server/WebSocketServer.java index cb96ade..35e1cd3 100644 --- a/src/main/java/org/example/websocket/server/WebSocketServer.java +++ b/src/main/java/org/example/websocket/server/WebSocketServer.java @@ -1,44 +1,44 @@ package org.example.websocket.server; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelInitializer; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioEventLoop; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.http.HttpChunkAggregator; import io.netty.handler.codec.http.HttpRequestDecoder; import io.netty.handler.codec.http.HttpResponseEncoder; import java.net.InetSocketAddress; public class WebSocketServer { public static void main(String[] args) throws Exception { final ServerBootstrap sb = new ServerBootstrap(); try { sb.eventLoop(new NioEventLoop(), new NioEventLoop()) .channel(new NioServerSocketChannel()) .localAddress(new InetSocketAddress(8080)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(final SocketChannel ch) throws Exception { ch.pipeline().addLast(new HttpRequestDecoder(), - new HttpChunkAggregator(65536), - new HttpResponseEncoder(), - new WebSocketServerHandler()); + new HttpChunkAggregator(65536), + new HttpResponseEncoder(), + new WebSocketServerHandler()); } }); final Channel ch = sb.bind().sync().channel(); System.out.println("Web socket server started at port 8080"); ch.closeFuture().sync(); } finally { sb.shutdown(); } } }
true
true
public static void main(String[] args) throws Exception { final ServerBootstrap sb = new ServerBootstrap(); try { sb.eventLoop(new NioEventLoop(), new NioEventLoop()) .channel(new NioServerSocketChannel()) .localAddress(new InetSocketAddress(8080)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(final SocketChannel ch) throws Exception { ch.pipeline().addLast(new HttpRequestDecoder(), new HttpChunkAggregator(65536), new HttpResponseEncoder(), new WebSocketServerHandler()); } }); final Channel ch = sb.bind().sync().channel(); System.out.println("Web socket server started at port 8080"); ch.closeFuture().sync(); } finally { sb.shutdown(); } }
public static void main(String[] args) throws Exception { final ServerBootstrap sb = new ServerBootstrap(); try { sb.eventLoop(new NioEventLoop(), new NioEventLoop()) .channel(new NioServerSocketChannel()) .localAddress(new InetSocketAddress(8080)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(final SocketChannel ch) throws Exception { ch.pipeline().addLast(new HttpRequestDecoder(), new HttpChunkAggregator(65536), new HttpResponseEncoder(), new WebSocketServerHandler()); } }); final Channel ch = sb.bind().sync().channel(); System.out.println("Web socket server started at port 8080"); ch.closeFuture().sync(); } finally { sb.shutdown(); } }
diff --git a/omod/src/main/java/org/openmrs/module/addresshierarchy/web/controller/AdvancedFeaturesController.java b/omod/src/main/java/org/openmrs/module/addresshierarchy/web/controller/AdvancedFeaturesController.java index 359e37f..c1a0b09 100644 --- a/omod/src/main/java/org/openmrs/module/addresshierarchy/web/controller/AdvancedFeaturesController.java +++ b/omod/src/main/java/org/openmrs/module/addresshierarchy/web/controller/AdvancedFeaturesController.java @@ -1,92 +1,92 @@ package org.openmrs.module.addresshierarchy.web.controller; import org.apache.commons.lang.StringUtils; import org.openmrs.GlobalProperty; import org.openmrs.api.context.Context; import org.openmrs.module.addresshierarchy.AddressHierarchyConstants; import org.openmrs.scheduler.TaskDefinition; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; @Controller public class AdvancedFeaturesController { @RequestMapping("/module/addresshierarchy/admin/advancedFeatures.form") public ModelAndView advancedFeatures(ModelMap map) { // load in the value of any existing task TaskDefinition updaterTask = Context.getSchedulerService().getTaskByName(AddressHierarchyConstants.TASK_NAME_ADDRESS_TO_ENTRY_MAP_UPDATER); if (updaterTask != null) { map.addAttribute("repeatInterval", updaterTask.getRepeatInterval().intValue() / 60); // convert the repeat interval (in seconds) to minutes map.addAttribute("updaterStarted", updaterTask.getStarted()); // if there is no last start time for the updater, this means the next execution is going to recalculate all the mappings, so set this attribute to true map.addAttribute("recalculateMappings", StringUtils.isBlank(Context.getAdministrationService().getGlobalProperty(AddressHierarchyConstants.GLOBAL_PROP_ADDRESS_TO_ENTRY_MAP_UPDATER_LAST_START_TIME)) ? true : false); } return new ModelAndView("/module/addresshierarchy/admin/advancedFeatures", map); } @RequestMapping("/module/addresshierarchy/admin/scheduleAddressToEntryMapping.form") public ModelAndView processAddressHierarchyUploadForm(@RequestParam(value = "repeatInterval", required = false) Integer repeatInterval, @RequestParam(value = "updaterStarted", required = false) Boolean updaterStarted, @RequestParam(value = "recalculateMappings", required = false) Boolean recalculateMappings, ModelMap map) { // load any existing task TaskDefinition updaterTask = Context.getSchedulerService().getTaskByName(AddressHierarchyConstants.TASK_NAME_ADDRESS_TO_ENTRY_MAP_UPDATER); // if there is no task, and the updater has been set to start, nothing to do if (updaterTask == null && (updaterStarted == null || !updaterStarted)) { return new ModelAndView("redirect:/module/addresshierarchy/admin/advancedFeatures.form"); } // otherwise, create a new task if need be if (updaterTask == null) { updaterTask = new TaskDefinition(); updaterTask.setName(AddressHierarchyConstants.TASK_NAME_ADDRESS_TO_ENTRY_MAP_UPDATER); updaterTask.setTaskClass(AddressHierarchyConstants.TASK_CLASS_ADDRESS_TO_ENTRY_MAP_UPDATER); } // start or stop the task as needed - if (updaterStarted) { + if (updaterStarted != null && updaterStarted) { updaterTask.setStarted(true); updaterTask.setStartOnStartup(true); } else { updaterTask.setStarted(false); updaterTask.setStartOnStartup(false); } // set the repeat interval if (repeatInterval != null) { updaterTask.setRepeatInterval(new Long(repeatInterval * 60)); } // if the task has been started, make sure we have at least a default repeat interval else if (updaterStarted != null && updaterStarted){ updaterTask.setRepeatInterval(AddressHierarchyConstants.TASK_PARAMETER_ADDRESS_ENTRY_MAP_DEFAULT_REPEAT_INTERVAL); } // if the recalculate mappings property has been set, reset the last start time to null (which will result in all address mappings being recalculated) if (recalculateMappings != null && recalculateMappings) { GlobalProperty lastStartTimeGlobalProp = Context.getAdministrationService().getGlobalPropertyObject(AddressHierarchyConstants.GLOBAL_PROP_ADDRESS_TO_ENTRY_MAP_UPDATER_LAST_START_TIME); lastStartTimeGlobalProp.setPropertyValue(null); Context.getAdministrationService().saveGlobalProperty(lastStartTimeGlobalProp); } // save the task if (updaterTask != null) { Context.getSchedulerService().saveTask(updaterTask); } // redirect back to the same page return new ModelAndView("redirect:/module/addresshierarchy/admin/advancedFeatures.form"); } }
true
true
public ModelAndView processAddressHierarchyUploadForm(@RequestParam(value = "repeatInterval", required = false) Integer repeatInterval, @RequestParam(value = "updaterStarted", required = false) Boolean updaterStarted, @RequestParam(value = "recalculateMappings", required = false) Boolean recalculateMappings, ModelMap map) { // load any existing task TaskDefinition updaterTask = Context.getSchedulerService().getTaskByName(AddressHierarchyConstants.TASK_NAME_ADDRESS_TO_ENTRY_MAP_UPDATER); // if there is no task, and the updater has been set to start, nothing to do if (updaterTask == null && (updaterStarted == null || !updaterStarted)) { return new ModelAndView("redirect:/module/addresshierarchy/admin/advancedFeatures.form"); } // otherwise, create a new task if need be if (updaterTask == null) { updaterTask = new TaskDefinition(); updaterTask.setName(AddressHierarchyConstants.TASK_NAME_ADDRESS_TO_ENTRY_MAP_UPDATER); updaterTask.setTaskClass(AddressHierarchyConstants.TASK_CLASS_ADDRESS_TO_ENTRY_MAP_UPDATER); } // start or stop the task as needed if (updaterStarted) { updaterTask.setStarted(true); updaterTask.setStartOnStartup(true); } else { updaterTask.setStarted(false); updaterTask.setStartOnStartup(false); } // set the repeat interval if (repeatInterval != null) { updaterTask.setRepeatInterval(new Long(repeatInterval * 60)); } // if the task has been started, make sure we have at least a default repeat interval else if (updaterStarted != null && updaterStarted){ updaterTask.setRepeatInterval(AddressHierarchyConstants.TASK_PARAMETER_ADDRESS_ENTRY_MAP_DEFAULT_REPEAT_INTERVAL); } // if the recalculate mappings property has been set, reset the last start time to null (which will result in all address mappings being recalculated) if (recalculateMappings != null && recalculateMappings) { GlobalProperty lastStartTimeGlobalProp = Context.getAdministrationService().getGlobalPropertyObject(AddressHierarchyConstants.GLOBAL_PROP_ADDRESS_TO_ENTRY_MAP_UPDATER_LAST_START_TIME); lastStartTimeGlobalProp.setPropertyValue(null); Context.getAdministrationService().saveGlobalProperty(lastStartTimeGlobalProp); } // save the task if (updaterTask != null) { Context.getSchedulerService().saveTask(updaterTask); } // redirect back to the same page return new ModelAndView("redirect:/module/addresshierarchy/admin/advancedFeatures.form"); }
public ModelAndView processAddressHierarchyUploadForm(@RequestParam(value = "repeatInterval", required = false) Integer repeatInterval, @RequestParam(value = "updaterStarted", required = false) Boolean updaterStarted, @RequestParam(value = "recalculateMappings", required = false) Boolean recalculateMappings, ModelMap map) { // load any existing task TaskDefinition updaterTask = Context.getSchedulerService().getTaskByName(AddressHierarchyConstants.TASK_NAME_ADDRESS_TO_ENTRY_MAP_UPDATER); // if there is no task, and the updater has been set to start, nothing to do if (updaterTask == null && (updaterStarted == null || !updaterStarted)) { return new ModelAndView("redirect:/module/addresshierarchy/admin/advancedFeatures.form"); } // otherwise, create a new task if need be if (updaterTask == null) { updaterTask = new TaskDefinition(); updaterTask.setName(AddressHierarchyConstants.TASK_NAME_ADDRESS_TO_ENTRY_MAP_UPDATER); updaterTask.setTaskClass(AddressHierarchyConstants.TASK_CLASS_ADDRESS_TO_ENTRY_MAP_UPDATER); } // start or stop the task as needed if (updaterStarted != null && updaterStarted) { updaterTask.setStarted(true); updaterTask.setStartOnStartup(true); } else { updaterTask.setStarted(false); updaterTask.setStartOnStartup(false); } // set the repeat interval if (repeatInterval != null) { updaterTask.setRepeatInterval(new Long(repeatInterval * 60)); } // if the task has been started, make sure we have at least a default repeat interval else if (updaterStarted != null && updaterStarted){ updaterTask.setRepeatInterval(AddressHierarchyConstants.TASK_PARAMETER_ADDRESS_ENTRY_MAP_DEFAULT_REPEAT_INTERVAL); } // if the recalculate mappings property has been set, reset the last start time to null (which will result in all address mappings being recalculated) if (recalculateMappings != null && recalculateMappings) { GlobalProperty lastStartTimeGlobalProp = Context.getAdministrationService().getGlobalPropertyObject(AddressHierarchyConstants.GLOBAL_PROP_ADDRESS_TO_ENTRY_MAP_UPDATER_LAST_START_TIME); lastStartTimeGlobalProp.setPropertyValue(null); Context.getAdministrationService().saveGlobalProperty(lastStartTimeGlobalProp); } // save the task if (updaterTask != null) { Context.getSchedulerService().saveTask(updaterTask); } // redirect back to the same page return new ModelAndView("redirect:/module/addresshierarchy/admin/advancedFeatures.form"); }
diff --git a/spring-richclient/src/org/springframework/richclient/form/builder/GridBagLayoutFormBuilder.java b/spring-richclient/src/org/springframework/richclient/form/builder/GridBagLayoutFormBuilder.java index fc80c793..56e7a308 100644 --- a/spring-richclient/src/org/springframework/richclient/form/builder/GridBagLayoutFormBuilder.java +++ b/spring-richclient/src/org/springframework/richclient/form/builder/GridBagLayoutFormBuilder.java @@ -1,329 +1,329 @@ /* * Copyright 2002-2004 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.springframework.richclient.form.builder; import java.awt.*; import javax.swing.*; import org.springframework.enums.ShortCodedEnum; import org.springframework.richclient.factory.ComponentFactory; import org.springframework.richclient.forms.SwingFormModel; import org.springframework.richclient.layout.GridBagLayoutBuilder; import org.springframework.richclient.layout.LayoutBuilder; /** * This provides an easy way to create panels using a {@link GridBagLayout}. * <p /> * * Usage is: * * <pre> * GridBagLayoutBuilder builder = new GridBagLayoutBuilder(); * * builder.appendRightLabel(&quot;label.field1&quot;).appendField(field1); * builder.appendRightLabel(&quot;label.field2&quot;).appendField(field2); * builder.nextLine(); * * builder.appendRightLabel(&quot;label.field3&quot;).appendField(field3); * // because &quot;field3&quot; is the last component on this line, but the panel has * // 4 columns, &quot;field3&quot; will span 3 columns * builder.nextLine(); * * // once everything's been put into the builder, ask it to build a panel * // to use in the UI. * JPanel panel = builder.getPanel(); * </pre> * * @author Jim Moore * @see #setAutoSpanLastComponent(boolean) * @see #setShowGuidelines(boolean) * @see #setComponentFactory(ComponentFactory) */ public class GridBagLayoutFormBuilder extends AbstractFormBuilder implements LayoutBuilder { private final GridBagLayoutBuilder builder; public static final class LabelOrientation extends ShortCodedEnum { public static final LabelOrientation TOP = new LabelOrientation(SwingConstants.TOP, "Top"); public static final LabelOrientation BOTTOM = new LabelOrientation(SwingConstants.BOTTOM, "Bottom"); public static final LabelOrientation LEFT = new LabelOrientation(SwingConstants.LEFT, "Left"); public static final LabelOrientation RIGHT = new LabelOrientation(SwingConstants.RIGHT, "Right"); private LabelOrientation(int code, String label) { super(code, label); } } public GridBagLayoutFormBuilder(SwingFormModel swingFormModel) { super(swingFormModel); this.builder = new GridBagLayoutBuilder(); } /** * Returns the underlying {@link GridBagLayoutBuilder}. Should be used * with caution. * * @return never null */ public final GridBagLayoutBuilder getBuilder() { return builder; } public void setComponentFactory(ComponentFactory componentFactory) { super.setComponentFactory(componentFactory); builder.setComponentFactory(componentFactory); } /** * Appends a label and field to the end of the current line.<p /> * * The label will be to the left of the field, and be right-justified.<br /> * The field will "grow" horizontally as space allows.<p /> * * @param propertyName the name of the property to create the controls for * * @return "this" to make it easier to string together append calls * * @see SwingFormModel#createLabel(String) * @see SwingFormModel#createBoundControl(String) */ public GridBagLayoutFormBuilder appendLabeledField(String propertyName) { return appendLabeledField(propertyName, LabelOrientation.LEFT); } /** * Appends a label and field to the end of the current line.<p /> * * The label will be to the left of the field, and be right-justified.<br /> * The field will "grow" horizontally as space allows.<p /> * * @param propertyName the name of the property to create the controls for * @param colSpan the number of columns the field should span * * @return "this" to make it easier to string together append calls * * @see SwingFormModel#createLabel(String) * @see SwingFormModel#createBoundControl(String) */ public GridBagLayoutFormBuilder appendLabeledField(String propertyName, int colSpan) { return appendLabeledField(propertyName, LabelOrientation.LEFT, colSpan); } /** * Appends a label and field to the end of the current line.<p /> * * The label will be to the left of the field, and be right-justified.<br /> * The field will "grow" horizontally as space allows.<p /> * * @param propertyName the name of the property to create the controls for * * @return "this" to make it easier to string together append calls * * @see SwingFormModel#createLabel(String) * @see SwingFormModel#createBoundControl(String) */ public GridBagLayoutFormBuilder appendLabeledField(String propertyName, LabelOrientation labelOrientation) { return appendLabeledField(propertyName, labelOrientation, 1); } /** * Appends a label and field to the end of the current line.<p /> * * The label will be to the left of the field, and be right-justified.<br /> * The field will "grow" horizontally as space allows.<p /> * * @param propertyName the name of the property to create the controls for * @param colSpan the number of columns the field should span * * @return "this" to make it easier to string together append calls * * @see SwingFormModel#createLabel(String) * @see SwingFormModel#createBoundControl(String) */ public GridBagLayoutFormBuilder appendLabeledField(String propertyName, LabelOrientation labelOrientation, int colSpan) { final JComponent field = getDefaultComponent(propertyName); return appendLabeledField(propertyName, field, labelOrientation, colSpan); } /** * Appends a label and field to the end of the current line.<p /> * * The label will be to the left of the field, and be right-justified.<br /> * The field will "grow" horizontally as space allows.<p /> * * @param propertyName the name of the property to create the controls for * * @return "this" to make it easier to string together append calls * * @see SwingFormModel#createLabel(String) * @see SwingFormModel#createBoundControl(String) */ public GridBagLayoutFormBuilder appendLabeledField(String propertyName, final JComponent field, LabelOrientation labelOrientation) { return appendLabeledField(propertyName, field, labelOrientation, 1); } /** * Appends a label and field to the end of the current line.<p /> * * The label will be to the left of the field, and be right-justified.<br /> * The field will "grow" horizontally as space allows.<p /> * * @param propertyName the name of the property to create the controls for * @param colSpan the number of columns the field should span * * @return "this" to make it easier to string together append calls * * @see SwingFormModel#createLabel(String) * @see FormComponentInterceptor#processLabel(String, JComponent) */ public GridBagLayoutFormBuilder appendLabeledField(String propertyName, final JComponent field, LabelOrientation labelOrientation, int colSpan) { return appendLabeledField(propertyName, field, labelOrientation, colSpan, 1, true, false); } /** * Appends a label and field to the end of the current line.<p /> * * The label will be to the left of the field, and be right-justified.<br /> * The field will "grow" horizontally as space allows.<p /> * * @param propertyName the name of the property to create the controls for * @param colSpan the number of columns the field should span * * @return "this" to make it easier to string together append calls * * @see SwingFormModel#createLabel(String) * @see FormComponentInterceptor#processLabel(String, JComponent) */ public GridBagLayoutFormBuilder appendLabeledField(String propertyName, final JComponent field, LabelOrientation labelOrientation, int colSpan, int rowSpan, boolean expandX, boolean expandY) { final JLabel label = getLabelFor(propertyName, field); if (labelOrientation == LabelOrientation.LEFT || labelOrientation == null) { - label.setAlignmentX(JLabel.RIGHT_ALIGNMENT); + label.setHorizontalAlignment(JLabel.RIGHT); builder.appendLabel(label).append(field, colSpan, rowSpan, expandX, expandY); } else if (labelOrientation == LabelOrientation.RIGHT) { - label.setAlignmentX(JLabel.LEFT_ALIGNMENT); + label.setHorizontalAlignment(JLabel.LEFT); builder.append(field, colSpan, rowSpan, expandX, expandY) .appendLabel(label); } else if (labelOrientation == LabelOrientation.TOP) { - label.setAlignmentX(JLabel.LEFT_ALIGNMENT); + label.setHorizontalAlignment(JLabel.LEFT); final int col = builder.getCurrentCol(); final int row = builder.getCurrentRow(); final Insets insets = builder.getDefaultInsets(); builder.append(label, col, row, colSpan, 1, false, expandY, insets).append(field, col, row + 1, colSpan, rowSpan, expandX, expandY, insets); } else if (labelOrientation == LabelOrientation.BOTTOM) { - label.setAlignmentX(JLabel.LEFT_ALIGNMENT); + label.setHorizontalAlignment(JLabel.LEFT); final int col = builder.getCurrentCol(); final int row = builder.getCurrentRow(); final Insets insets = builder.getDefaultInsets(); builder.append(field, col, row, colSpan, rowSpan, expandX, expandY, insets).append(label, col, row + rowSpan, colSpan, 1, false, expandY, insets); } return this; } /** * Appends a seperator (usually a horizonal line). Has an implicit * {@link #nextLine()} before and after it. * * @return "this" to make it easier to string together append calls */ public GridBagLayoutFormBuilder appendSeparator() { return appendSeparator(null); } /** * Appends a seperator (usually a horizonal line) using the provided * string as the key to look in the * {@link #setComponentFactory(ComponentFactory) ComponentFactory's} * message bundle for the text to put along with the seperator. Has an * implicit {@link #nextLine()} before and after it. * * @return "this" to make it easier to string together append calls */ public GridBagLayoutFormBuilder appendSeparator(String labelKey) { builder.appendSeparator(labelKey); return this; } /** * Ends the current line and starts a new one * * @return "this" to make it easier to string together append calls */ public GridBagLayoutFormBuilder nextLine() { builder.nextLine(); return this; } /** * Should this show "guidelines"? Useful for debugging layouts. */ public void setShowGuidelines(boolean showGuidelines) { builder.setShowGuidelines(showGuidelines); } /** * Creates and returns a JPanel with all the given components in it, using * the "hints" that were provided to the builder. * * @return a new JPanel with the components laid-out in it */ public JPanel getPanel() { return builder.getPanel(); } /** * @see GridBagLayoutBuilder#setAutoSpanLastComponent(boolean) */ public void setAutoSpanLastComponent(boolean autoSpanLastComponent) { builder.setAutoSpanLastComponent(autoSpanLastComponent); } }
false
true
public GridBagLayoutFormBuilder appendLabeledField(String propertyName, final JComponent field, LabelOrientation labelOrientation, int colSpan, int rowSpan, boolean expandX, boolean expandY) { final JLabel label = getLabelFor(propertyName, field); if (labelOrientation == LabelOrientation.LEFT || labelOrientation == null) { label.setAlignmentX(JLabel.RIGHT_ALIGNMENT); builder.appendLabel(label).append(field, colSpan, rowSpan, expandX, expandY); } else if (labelOrientation == LabelOrientation.RIGHT) { label.setAlignmentX(JLabel.LEFT_ALIGNMENT); builder.append(field, colSpan, rowSpan, expandX, expandY) .appendLabel(label); } else if (labelOrientation == LabelOrientation.TOP) { label.setAlignmentX(JLabel.LEFT_ALIGNMENT); final int col = builder.getCurrentCol(); final int row = builder.getCurrentRow(); final Insets insets = builder.getDefaultInsets(); builder.append(label, col, row, colSpan, 1, false, expandY, insets).append(field, col, row + 1, colSpan, rowSpan, expandX, expandY, insets); } else if (labelOrientation == LabelOrientation.BOTTOM) { label.setAlignmentX(JLabel.LEFT_ALIGNMENT); final int col = builder.getCurrentCol(); final int row = builder.getCurrentRow(); final Insets insets = builder.getDefaultInsets(); builder.append(field, col, row, colSpan, rowSpan, expandX, expandY, insets).append(label, col, row + rowSpan, colSpan, 1, false, expandY, insets); } return this; }
public GridBagLayoutFormBuilder appendLabeledField(String propertyName, final JComponent field, LabelOrientation labelOrientation, int colSpan, int rowSpan, boolean expandX, boolean expandY) { final JLabel label = getLabelFor(propertyName, field); if (labelOrientation == LabelOrientation.LEFT || labelOrientation == null) { label.setHorizontalAlignment(JLabel.RIGHT); builder.appendLabel(label).append(field, colSpan, rowSpan, expandX, expandY); } else if (labelOrientation == LabelOrientation.RIGHT) { label.setHorizontalAlignment(JLabel.LEFT); builder.append(field, colSpan, rowSpan, expandX, expandY) .appendLabel(label); } else if (labelOrientation == LabelOrientation.TOP) { label.setHorizontalAlignment(JLabel.LEFT); final int col = builder.getCurrentCol(); final int row = builder.getCurrentRow(); final Insets insets = builder.getDefaultInsets(); builder.append(label, col, row, colSpan, 1, false, expandY, insets).append(field, col, row + 1, colSpan, rowSpan, expandX, expandY, insets); } else if (labelOrientation == LabelOrientation.BOTTOM) { label.setHorizontalAlignment(JLabel.LEFT); final int col = builder.getCurrentCol(); final int row = builder.getCurrentRow(); final Insets insets = builder.getDefaultInsets(); builder.append(field, col, row, colSpan, rowSpan, expandX, expandY, insets).append(label, col, row + rowSpan, colSpan, 1, false, expandY, insets); } return this; }
diff --git a/src/no/runsafe/itemflangerorimega/tools/enchants/Lumberjacking.java b/src/no/runsafe/itemflangerorimega/tools/enchants/Lumberjacking.java index 2d6a94a..d0257b5 100644 --- a/src/no/runsafe/itemflangerorimega/tools/enchants/Lumberjacking.java +++ b/src/no/runsafe/itemflangerorimega/tools/enchants/Lumberjacking.java @@ -1,62 +1,62 @@ package no.runsafe.itemflangerorimega.tools.enchants; import no.runsafe.framework.api.ILocation; import no.runsafe.framework.api.block.IBlock; import no.runsafe.framework.api.player.IPlayer; import no.runsafe.framework.minecraft.Item; import no.runsafe.itemflangerorimega.tools.CustomToolEnchant; public class Lumberjacking extends CustomToolEnchant { @Override public String getEnchantText() { return "Lumberjacking I"; } @Override public String getSimpleName() { return "lumberjack"; } @Override public boolean onBlockBreak(IPlayer player, IBlock block) { if (player.isSurvivalist()) breakBlock(block, 0); return false; } private void breakBlock(IBlock block, int depth) { if (block.is(Item.BuildingBlock.Wood.Any)) { block.breakNaturally(); ILocation location = block.getLocation(); depth += 1; - if (depth < 30) + if (depth < 100) { check(location, 1, 0, 0, depth); check(location, -1, 0, 0, depth); check(location, 0, 0, 1, depth); check(location, 0, 0, -1, depth); check(location, 0, 1, 0, depth); check(location, 0, -1, 0, depth); } } } private void check(ILocation location, int offsetX, int offsetY, int offsetZ, int depth) { location = location.clone(); location.offset(offsetX, offsetY, offsetZ); IBlock block = location.getBlock(); if (block.is(Item.Decoration.Leaves.Any) || block.is(Item.BuildingBlock.Wood.Any)) breakBlock(block, depth); } }
true
true
private void breakBlock(IBlock block, int depth) { if (block.is(Item.BuildingBlock.Wood.Any)) { block.breakNaturally(); ILocation location = block.getLocation(); depth += 1; if (depth < 30) { check(location, 1, 0, 0, depth); check(location, -1, 0, 0, depth); check(location, 0, 0, 1, depth); check(location, 0, 0, -1, depth); check(location, 0, 1, 0, depth); check(location, 0, -1, 0, depth); } } }
private void breakBlock(IBlock block, int depth) { if (block.is(Item.BuildingBlock.Wood.Any)) { block.breakNaturally(); ILocation location = block.getLocation(); depth += 1; if (depth < 100) { check(location, 1, 0, 0, depth); check(location, -1, 0, 0, depth); check(location, 0, 0, 1, depth); check(location, 0, 0, -1, depth); check(location, 0, 1, 0, depth); check(location, 0, -1, 0, depth); } } }
diff --git a/src/main/java/org/primefaces/component/calendar/CalendarRenderer.java b/src/main/java/org/primefaces/component/calendar/CalendarRenderer.java index f8c56e56c..6b7baaff7 100644 --- a/src/main/java/org/primefaces/component/calendar/CalendarRenderer.java +++ b/src/main/java/org/primefaces/component/calendar/CalendarRenderer.java @@ -1,202 +1,202 @@ /* * Copyright 2010 Prime Technology. * * 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.calendar; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.Map; import javax.faces.FacesException; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import javax.faces.convert.ConverterException; import org.primefaces.event.DateSelectEvent; import org.primefaces.renderkit.CoreRenderer; import org.primefaces.util.ComponentUtils; public class CalendarRenderer extends CoreRenderer { @Override public void decode(FacesContext context, UIComponent component) { Calendar calendar = (Calendar) component; Map<String, String> params = context.getExternalContext().getRequestParameterMap(); String param = calendar.getClientId(context) + "_input"; if (params.containsKey(param)) { calendar.setSubmittedValue(params.get(param)); } } @Override public void encodeEnd(FacesContext context, UIComponent component) throws IOException { Calendar calendar = (Calendar) component; String value = CalendarUtils.getValueAsString(context, calendar); encodeMarkup(context, calendar, value); encodeScript(context, calendar, value); } protected void encodeMarkup(FacesContext context, Calendar calendar, String value) throws IOException { ResponseWriter writer = context.getResponseWriter(); String clientId = calendar.getClientId(context); String inputId = clientId + "_input"; writer.startElement("span", calendar); writer.writeAttribute("id", clientId, null); if(calendar.getStyle() != null) writer.writeAttribute("style", calendar.getStyle(), null); if(calendar.getStyleClass() != null) writer.writeAttribute("class", calendar.getStyleClass(), null); //popup container if(!calendar.isPopup()) { writer.startElement("div", null); writer.writeAttribute("id", clientId + "_inline", null); writer.endElement("div"); } //input String type = calendar.isPopup() ? "text" : "hidden"; writer.startElement("input", null); writer.writeAttribute("id", inputId, null); writer.writeAttribute("name", inputId, null); writer.writeAttribute("type", type, null); if(!isValueBlank(value)) { writer.writeAttribute("value", value, null); } if(calendar.isPopup()) { if(calendar.getInputStyle() != null) writer.writeAttribute("style", calendar.getInputStyle(), null); if(calendar.getInputStyleClass() != null) writer.writeAttribute("class", calendar.getInputStyleClass(), null); if(calendar.isReadOnlyInputText()) writer.writeAttribute("readonly", "readonly", null); if(calendar.isDisabled()) writer.writeAttribute("disabled", "disabled", null); renderPassThruAttributes(context, calendar, Calendar.INPUT_TEXT_ATTRS); } writer.endElement("input"); writer.endElement("span"); } protected void encodeScript(FacesContext context, Calendar calendar, String value) throws IOException { ResponseWriter writer = context.getResponseWriter(); String clientId = calendar.getClientId(context); writer.startElement("script", null); writer.writeAttribute("type", "text/javascript", null); writer.write("jQuery(function(){"); writer.write(calendar.resolveWidgetVar() + " = new PrimeFaces.widget.Calendar('" + clientId + "', {"); writer.write("popup:" + calendar.isPopup()); writer.write(",locale:'" + calendar.calculateLocale(context).toString() + "'"); if(!isValueBlank(value)) writer.write(",defaultDate:'" + value + "'"); if(calendar.getPattern() != null) writer.write(",dateFormat:'" + CalendarUtils.convertPattern(calendar.getPattern()) + "'"); if(calendar.getPages() != 1) writer.write(",numberOfMonths:" + calendar.getPages()); - if(calendar.getMindate() != null) writer.write(",minDate:'" + CalendarUtils.getDateAsString(calendar, calendar.getMindate() + "'")); - if(calendar.getMaxdate() != null) writer.write(",maxDate:'" + CalendarUtils.getDateAsString(calendar, calendar.getMaxdate() + "'")); + if(calendar.getMindate() != null) writer.write(",minDate:'" + CalendarUtils.getDateAsString(calendar, calendar.getMindate()) + "'"); + if(calendar.getMaxdate() != null) writer.write(",maxDate:'" + CalendarUtils.getDateAsString(calendar, calendar.getMaxdate()) + "'"); if(calendar.isShowButtonPanel()) writer.write(",showButtonPanel:true"); if(calendar.isShowWeek()) writer.write(",showWeek:true"); if(calendar.isDisabled()) writer.write(",disabled:true"); if(calendar.getYearRange() != null) writer.write(",yearRange:'" + calendar.getYearRange() + "'"); if(calendar.isNavigator()) { writer.write(",changeMonth:true"); writer.write(",changeYear:true"); } if(calendar.getEffect() != null) { writer.write(",showAnim:'" + calendar.getEffect() + "'"); writer.write(",duration:'" + calendar.getEffectDuration() + "'"); } String showOn = calendar.getShowOn(); if(!showOn.equalsIgnoreCase("focus")) { String iconSrc = calendar.getPopupIcon() != null ? getResourceURL(context, calendar.getPopupIcon()) : getResourceRequestPath(context, Calendar.POPUP_ICON); writer.write(",showOn:'" + showOn + "'"); writer.write(",buttonImage:'" + iconSrc + "'"); writer.write(",buttonImageOnly:" + calendar.isPopupIconOnly()); } if(calendar.isShowOtherMonths()) { writer.write(",showOtherMonths:true"); writer.write(",selectOtherMonths:" + calendar.isSelectOtherMonths()); } if(calendar.getSelectListener() != null) { UIComponent form = ComponentUtils.findParentForm(context, calendar); if (form == null) { throw new FacesException("Calendar \"" + calendar.getClientId(context) + "\" must be enclosed with a form when using ajax selection."); } writer.write(",formId:'" + form.getClientId(context) + "'"); writer.write(",url:'" + getActionURL(context) + "'"); writer.write(",hasSelectListener:true"); if(calendar.getOnSelectUpdate() != null) { writer.write(",onSelectUpdate:'" + ComponentUtils.findClientIds(context, calendar, calendar.getOnSelectUpdate()) + "'"); } } encodeClientBehaviors(context, calendar); writer.write("});});"); writer.endElement("script"); } @Override public Object getConvertedValue(FacesContext context, UIComponent component, Object value) throws ConverterException { Calendar calendar = (Calendar) component; String submittedValue = (String) value; if (isValueBlank(submittedValue)) { return null; } //Delegate to user supplied converter if defined if (calendar.getConverter() != null) { return calendar.getConverter().getAsObject(context, calendar, submittedValue); } try { Date convertedValue; Locale locale = calendar.calculateLocale(context); SimpleDateFormat format = new SimpleDateFormat(calendar.getPattern(), locale); format.setTimeZone(calendar.calculateTimeZone()); convertedValue = format.parse(submittedValue); if(calendar.getSelectListener() != null) { calendar.queueEvent(new DateSelectEvent(calendar, convertedValue)); } return convertedValue; } catch (ParseException e) { throw new ConverterException(e); } } }
true
true
protected void encodeScript(FacesContext context, Calendar calendar, String value) throws IOException { ResponseWriter writer = context.getResponseWriter(); String clientId = calendar.getClientId(context); writer.startElement("script", null); writer.writeAttribute("type", "text/javascript", null); writer.write("jQuery(function(){"); writer.write(calendar.resolveWidgetVar() + " = new PrimeFaces.widget.Calendar('" + clientId + "', {"); writer.write("popup:" + calendar.isPopup()); writer.write(",locale:'" + calendar.calculateLocale(context).toString() + "'"); if(!isValueBlank(value)) writer.write(",defaultDate:'" + value + "'"); if(calendar.getPattern() != null) writer.write(",dateFormat:'" + CalendarUtils.convertPattern(calendar.getPattern()) + "'"); if(calendar.getPages() != 1) writer.write(",numberOfMonths:" + calendar.getPages()); if(calendar.getMindate() != null) writer.write(",minDate:'" + CalendarUtils.getDateAsString(calendar, calendar.getMindate() + "'")); if(calendar.getMaxdate() != null) writer.write(",maxDate:'" + CalendarUtils.getDateAsString(calendar, calendar.getMaxdate() + "'")); if(calendar.isShowButtonPanel()) writer.write(",showButtonPanel:true"); if(calendar.isShowWeek()) writer.write(",showWeek:true"); if(calendar.isDisabled()) writer.write(",disabled:true"); if(calendar.getYearRange() != null) writer.write(",yearRange:'" + calendar.getYearRange() + "'"); if(calendar.isNavigator()) { writer.write(",changeMonth:true"); writer.write(",changeYear:true"); } if(calendar.getEffect() != null) { writer.write(",showAnim:'" + calendar.getEffect() + "'"); writer.write(",duration:'" + calendar.getEffectDuration() + "'"); } String showOn = calendar.getShowOn(); if(!showOn.equalsIgnoreCase("focus")) { String iconSrc = calendar.getPopupIcon() != null ? getResourceURL(context, calendar.getPopupIcon()) : getResourceRequestPath(context, Calendar.POPUP_ICON); writer.write(",showOn:'" + showOn + "'"); writer.write(",buttonImage:'" + iconSrc + "'"); writer.write(",buttonImageOnly:" + calendar.isPopupIconOnly()); } if(calendar.isShowOtherMonths()) { writer.write(",showOtherMonths:true"); writer.write(",selectOtherMonths:" + calendar.isSelectOtherMonths()); } if(calendar.getSelectListener() != null) { UIComponent form = ComponentUtils.findParentForm(context, calendar); if (form == null) { throw new FacesException("Calendar \"" + calendar.getClientId(context) + "\" must be enclosed with a form when using ajax selection."); } writer.write(",formId:'" + form.getClientId(context) + "'"); writer.write(",url:'" + getActionURL(context) + "'"); writer.write(",hasSelectListener:true"); if(calendar.getOnSelectUpdate() != null) { writer.write(",onSelectUpdate:'" + ComponentUtils.findClientIds(context, calendar, calendar.getOnSelectUpdate()) + "'"); } } encodeClientBehaviors(context, calendar); writer.write("});});"); writer.endElement("script"); }
protected void encodeScript(FacesContext context, Calendar calendar, String value) throws IOException { ResponseWriter writer = context.getResponseWriter(); String clientId = calendar.getClientId(context); writer.startElement("script", null); writer.writeAttribute("type", "text/javascript", null); writer.write("jQuery(function(){"); writer.write(calendar.resolveWidgetVar() + " = new PrimeFaces.widget.Calendar('" + clientId + "', {"); writer.write("popup:" + calendar.isPopup()); writer.write(",locale:'" + calendar.calculateLocale(context).toString() + "'"); if(!isValueBlank(value)) writer.write(",defaultDate:'" + value + "'"); if(calendar.getPattern() != null) writer.write(",dateFormat:'" + CalendarUtils.convertPattern(calendar.getPattern()) + "'"); if(calendar.getPages() != 1) writer.write(",numberOfMonths:" + calendar.getPages()); if(calendar.getMindate() != null) writer.write(",minDate:'" + CalendarUtils.getDateAsString(calendar, calendar.getMindate()) + "'"); if(calendar.getMaxdate() != null) writer.write(",maxDate:'" + CalendarUtils.getDateAsString(calendar, calendar.getMaxdate()) + "'"); if(calendar.isShowButtonPanel()) writer.write(",showButtonPanel:true"); if(calendar.isShowWeek()) writer.write(",showWeek:true"); if(calendar.isDisabled()) writer.write(",disabled:true"); if(calendar.getYearRange() != null) writer.write(",yearRange:'" + calendar.getYearRange() + "'"); if(calendar.isNavigator()) { writer.write(",changeMonth:true"); writer.write(",changeYear:true"); } if(calendar.getEffect() != null) { writer.write(",showAnim:'" + calendar.getEffect() + "'"); writer.write(",duration:'" + calendar.getEffectDuration() + "'"); } String showOn = calendar.getShowOn(); if(!showOn.equalsIgnoreCase("focus")) { String iconSrc = calendar.getPopupIcon() != null ? getResourceURL(context, calendar.getPopupIcon()) : getResourceRequestPath(context, Calendar.POPUP_ICON); writer.write(",showOn:'" + showOn + "'"); writer.write(",buttonImage:'" + iconSrc + "'"); writer.write(",buttonImageOnly:" + calendar.isPopupIconOnly()); } if(calendar.isShowOtherMonths()) { writer.write(",showOtherMonths:true"); writer.write(",selectOtherMonths:" + calendar.isSelectOtherMonths()); } if(calendar.getSelectListener() != null) { UIComponent form = ComponentUtils.findParentForm(context, calendar); if (form == null) { throw new FacesException("Calendar \"" + calendar.getClientId(context) + "\" must be enclosed with a form when using ajax selection."); } writer.write(",formId:'" + form.getClientId(context) + "'"); writer.write(",url:'" + getActionURL(context) + "'"); writer.write(",hasSelectListener:true"); if(calendar.getOnSelectUpdate() != null) { writer.write(",onSelectUpdate:'" + ComponentUtils.findClientIds(context, calendar, calendar.getOnSelectUpdate()) + "'"); } } encodeClientBehaviors(context, calendar); writer.write("});});"); writer.endElement("script"); }
diff --git a/web/src/test/java/org/openmrs/web/controller/patient/ShortPatientFormControllerTest.java b/web/src/test/java/org/openmrs/web/controller/patient/ShortPatientFormControllerTest.java index 5ddf9a12..a64d01f6 100644 --- a/web/src/test/java/org/openmrs/web/controller/patient/ShortPatientFormControllerTest.java +++ b/web/src/test/java/org/openmrs/web/controller/patient/ShortPatientFormControllerTest.java @@ -1,316 +1,318 @@ /** * The contents of this file are subject to the OpenMRS 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://license.openmrs.org * * 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) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.web.controller.patient; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.collections.MapUtils; import org.junit.Assert; import org.junit.Test; import org.openmrs.Patient; import org.openmrs.PatientIdentifier; import org.openmrs.PersonAddress; import org.openmrs.PersonName; import org.openmrs.api.context.Context; import org.openmrs.test.Verifies; import org.openmrs.util.LocationUtility; import org.openmrs.web.WebConstants; import org.openmrs.web.test.BaseWebContextSensitiveTest; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.ui.ModelMap; import org.springframework.validation.BindException; import org.springframework.validation.BindingResult; import org.springframework.web.bind.support.SessionStatus; import org.springframework.web.bind.support.SimpleSessionStatus; import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.context.request.WebRequest; /** * Consists of unit tests for the ShortPatientFormController * * @see ShortPatientFormController */ public class ShortPatientFormControllerTest extends BaseWebContextSensitiveTest { /** * @see {@link ShortPatientFormController#saveShortPatient(WebRequest,ShortPatientModel,BindingResult,SessionStatus)} */ @Test @Verifies(value = "should pass if all the form data is valid", method = "saveShortPatient(WebRequest,ShortPatientModel,BindingResult,SessionStatus)") public void saveShortPatient_shouldPassIfAllTheFormDataIsValid() throws Exception { Patient p = Context.getPatientService().getPatient(2); ShortPatientModel patientModel = new ShortPatientModel(p); WebRequest mockWebRequest = new ServletWebRequest(new MockHttpServletRequest()); SimpleSessionStatus status = new SimpleSessionStatus(); BindException errors = new BindException(patientModel, "patientModel"); mockWebRequest.setAttribute("personNameCache", BeanUtils.cloneBean(p.getPersonName()), WebRequest.SCOPE_SESSION); mockWebRequest.setAttribute("personAddressCache", p.getPersonAddress().clone(), WebRequest.SCOPE_SESSION); mockWebRequest.setAttribute("patientModel", patientModel, WebRequest.SCOPE_SESSION); ShortPatientFormController controller = (ShortPatientFormController) applicationContext .getBean("shortPatientFormController"); String redirectUrl = controller.saveShortPatient(mockWebRequest, (PersonName) mockWebRequest.getAttribute( "personNameCache", WebRequest.SCOPE_SESSION), (PersonAddress) mockWebRequest.getAttribute("personAddressCache", WebRequest.SCOPE_SESSION), (ShortPatientModel) mockWebRequest.getAttribute("patientModel", WebRequest.SCOPE_SESSION), errors, status); Assert.assertTrue("Should pass with no validation errors", !errors.hasErrors()); Assert.assertEquals("Patient.saved", mockWebRequest.getAttribute(WebConstants.OPENMRS_MSG_ATTR, WebRequest.SCOPE_SESSION)); Assert.assertTrue("Should set the status to complete", status.isComplete()); Assert.assertEquals("redirect:/patientDashboard.form?patientId=" + p.getPatientId(), redirectUrl); } /** * @see {@link ShortPatientFormController#saveShortPatient(WebRequest,ShortPatientModel,BindingResult,SessionStatus)} */ @Test @Verifies(value = "should create a new patient", method = "saveShortPatient(WebRequest,ShortPatientModel,BindingResult,SessionStatus)") public void saveShortPatient_shouldCreateANewPatient() throws Exception { int patientCount = Context.getPatientService().getAllPatients().size(); Patient p = new Patient(); ShortPatientModel patientModel = new ShortPatientModel(p); patientModel.setPersonName(new PersonName("new", "", "patient")); List<PatientIdentifier> identifiers = new ArrayList<PatientIdentifier>(); - identifiers.add(new PatientIdentifier("myID", Context.getPatientService().getPatientIdentifierType(2), - LocationUtility.getDefaultLocation())); + PatientIdentifier id = new PatientIdentifier("myID", Context.getPatientService().getPatientIdentifierType(2), + LocationUtility.getDefaultLocation()); + id.setPreferred(true); + identifiers.add(id); patientModel.setIdentifiers(identifiers); patientModel.getPatient().setBirthdate(new Date()); patientModel.getPatient().setGender("M"); WebRequest mockWebRequest = new ServletWebRequest(new MockHttpServletRequest()); BindException errors = new BindException(patientModel, "patientModel"); ShortPatientFormController controller = (ShortPatientFormController) applicationContext .getBean("shortPatientFormController"); String redirectUrl = controller.saveShortPatient(mockWebRequest, new PersonName(), new PersonAddress(), patientModel, errors, new SimpleSessionStatus()); Assert.assertTrue("Should pass with no validation errors", !errors.hasErrors()); Assert.assertNotNull(p.getId()); Assert.assertNotNull(p.getPersonName()); Assert.assertNotNull(p.getPersonName().getId());//the name was create and added Assert.assertEquals(patientCount + 1, Context.getPatientService().getAllPatients().size()); Assert.assertEquals("Patient.saved", mockWebRequest.getAttribute(WebConstants.OPENMRS_MSG_ATTR, WebRequest.SCOPE_SESSION)); Assert.assertEquals("redirect:/patientDashboard.form?patientId=" + p.getPatientId(), redirectUrl); } /** * @see {@link ShortPatientFormController#saveShortPatient(WebRequest,ShortPatientModel,BindingResult,SessionStatus)} */ @Test @Verifies(value = "should send the user back to the form in case of validation errors", method = "saveShortPatient(WebRequest,ShortPatientModel,BindingResult,SessionStatus)") public void saveShortPatient_shouldSendTheUserBackToTheFormInCaseOfValidationErrors() throws Exception { Patient p = new Patient(); ShortPatientModel patientModel = new ShortPatientModel(p); patientModel.setPersonName(new PersonName("new", "", "patient")); List<PatientIdentifier> identifiers = new ArrayList<PatientIdentifier>(); patientModel.setIdentifiers(identifiers); WebRequest mockWebRequest = new ServletWebRequest(new MockHttpServletRequest()); BindException errors = new BindException(patientModel, "patientModel"); ShortPatientFormController controller = (ShortPatientFormController) applicationContext .getBean("shortPatientFormController"); String formUrl = controller.saveShortPatient(mockWebRequest, new PersonName(), new PersonAddress(), patientModel, errors, new SimpleSessionStatus()); Assert.assertTrue("Should report validation errors", errors.hasErrors()); Assert.assertEquals("/admin/patients/shortPatientForm", formUrl); } /** * @see {@link ShortPatientFormController#saveShortPatient(WebRequest,ShortPatientModel,BindingResult,SessionStatus)} */ @Test @Verifies(value = "should void a name and replace it with a new one if it is changed to a unique value", method = "saveShortPatient(WebRequest,ShortPatientModel,BindingResult,SessionStatus)") public void saveShortPatient_shouldVoidANameAndReplaceItWithANewOneIfItIsChangedToAUniqueValue() throws Exception { Patient p = Context.getPatientService().getPatient(2); ShortPatientModel patientModel = new ShortPatientModel(p); PersonName oldPersonName = p.getPersonName(); String oldGivenName = oldPersonName.getGivenName(); int nameCount = p.getNames().size(); BindException errors = new BindException(patientModel, "patientModel"); ServletWebRequest mockWebRequest = new ServletWebRequest(new MockHttpServletRequest()); PersonName personNameCache = (PersonName) BeanUtils.cloneBean(p.getPersonName()); //edit the name and submit patientModel.getPersonName().setGivenName("Changed"); ShortPatientFormController controller = (ShortPatientFormController) applicationContext .getBean("shortPatientFormController"); String redirectUrl = controller.saveShortPatient(mockWebRequest, personNameCache, (PersonAddress) p .getPersonAddress().clone(), patientModel, errors, new SimpleSessionStatus()); Assert.assertEquals(nameCount + 1, p.getNames().size()); Assert.assertTrue("The old name should be voided", oldPersonName.isVoided()); Assert.assertNotNull("The void reason should be set", oldPersonName.getVoidReason()); Assert.assertTrue("The old name should have remained un changed", oldGivenName.equalsIgnoreCase(oldPersonName .getGivenName())); Assert.assertEquals("Changed", p.getGivenName());//the changes should have taken effect Assert.assertTrue("Should pass with no validation errors", !errors.hasErrors()); Assert.assertEquals("redirect:/patientDashboard.form?patientId=" + p.getPatientId(), redirectUrl); } /** * @see {@link ShortPatientFormController#showForm(Integer,ModelMap,WebRequest)} */ @Test @Verifies(value = "should redirect to the shortPatientForm", method = "showForm(Integer,ModelMap,WebRequest)") public void showForm_shouldRedirectToTheShortPatientForm() throws Exception { ServletWebRequest mockWebRequest = new ServletWebRequest(new MockHttpServletRequest()); ShortPatientFormController controller = (ShortPatientFormController) applicationContext .getBean("shortPatientFormController"); ModelMap model = new ModelMap(); String redirectUrl = controller.showForm(2, model, mockWebRequest); Assert.assertTrue(MapUtils.isNotEmpty(model)); Assert.assertEquals("/admin/patients/shortPatientForm", redirectUrl); } /** * @see {@link ShortPatientFormController#saveShortPatient(WebRequest,ShortPatientModel,BindingResult,SessionStatus)} */ @Test @Verifies(value = "should add a new name if the person had no names", method = "saveShortPatient(WebRequest,ShortPatientModel,BindingResult,SessionStatus)") public void saveShortPatient_shouldAddANewNameIfThePersonHadNoNames() throws Exception { Patient p = Context.getPatientService().getPatient(2); p.getPersonName().setVoided(true); Context.getPatientService().savePatient(p); Assert.assertNull(p.getPersonName());//make sure all names are voided //add a name that will used as a duplicate for testing purposes PersonName newName = new PersonName("new", null, "name"); newName.setDateCreated(new Date()); ShortPatientModel patientModel = new ShortPatientModel(p); patientModel.setPersonName(newName); BindException errors = new BindException(patientModel, "patientModel"); ServletWebRequest mockWebRequest = new ServletWebRequest(new MockHttpServletRequest()); ShortPatientFormController controller = (ShortPatientFormController) applicationContext .getBean("shortPatientFormController"); String redirectUrl = controller.saveShortPatient(mockWebRequest, new PersonName(), (PersonAddress) p .getPersonAddress().clone(), patientModel, errors, new SimpleSessionStatus()); Assert.assertTrue("Should pass with no validation errors", !errors.hasErrors()); Assert.assertEquals("redirect:/patientDashboard.form?patientId=" + p.getPatientId(), redirectUrl); Assert.assertNotNull(newName.getId());//name should have been added to DB } /** * @see {@link ShortPatientFormController#saveShortPatient(WebRequest,ShortPatientModel,BindingResult,SessionStatus)} */ @Test @Verifies(value = "should void an address and replace it with a new one if it is changed to a unique value", method = "saveShortPatient(WebRequest,ShortPatientModel,BindingResult,SessionStatus)") public void saveShortPatient_shouldVoidAnAddressAndReplaceItWithANewOneIfItIsChangedToAUniqueValue() throws Exception { Patient p = Context.getPatientService().getPatient(2); ShortPatientModel patientModel = new ShortPatientModel(p); PersonAddress oldPersonAddress = patientModel.getPersonAddress(); String oldAddress1 = oldPersonAddress.getAddress1(); int addressCount = p.getAddresses().size(); BindException errors = new BindException(patientModel, "patientModel"); ServletWebRequest mockWebRequest = new ServletWebRequest(new MockHttpServletRequest()); PersonAddress personAddressCache = (PersonAddress) p.getPersonAddress().clone(); //edit address1 value and submit patientModel.getPersonAddress().setAddress1("Kampala"); ShortPatientFormController controller = (ShortPatientFormController) applicationContext .getBean("shortPatientFormController"); String redirectUrl = controller.saveShortPatient(mockWebRequest, (PersonName) BeanUtils.cloneBean(p.getPersonName()), personAddressCache, patientModel, errors, new SimpleSessionStatus()); Assert.assertEquals(addressCount + 1, p.getAddresses().size()); Assert.assertTrue("The old address should be voided", oldPersonAddress.isVoided()); Assert.assertNotNull("The void reason should be set", oldPersonAddress.getVoidReason()); Assert.assertTrue("The old address should have remained the same", oldAddress1.equalsIgnoreCase(oldPersonAddress .getAddress1())); Assert.assertEquals("Kampala", p.getPersonAddress().getAddress1());//the changes should have taken effect Assert.assertEquals("redirect:/patientDashboard.form?patientId=" + p.getPatientId(), redirectUrl); } /** * @see {@link ShortPatientFormController#saveShortPatient(WebRequest,PersonName,ShortPatientModel,BindingResult,SessionStatus)} */ @Test @Verifies(value = "should add a new address if the person had none", method = "saveShortPatient(WebRequest,PersonName,ShortPatientModel,BindingResult,SessionStatus)") public void saveShortPatient_shouldAddANewAddressIfThePersonHadNone() throws Exception { Patient p = Context.getPatientService().getPatient(2); p.getPersonAddress().setVoided(true); Context.getPatientService().savePatient(p); Assert.assertNull(p.getPersonAddress());//make sure all addresses are voided //add a name that will used as a duplicate for testing purposes PersonAddress newAddress = new PersonAddress(); newAddress.setAddress1("Kampala"); newAddress.setDateCreated(new Date()); ShortPatientModel patientModel = new ShortPatientModel(p); patientModel.setPersonAddress(newAddress); BindException errors = new BindException(patientModel, "patientModel"); ServletWebRequest mockWebRequest = new ServletWebRequest(new MockHttpServletRequest()); ShortPatientFormController controller = (ShortPatientFormController) applicationContext .getBean("shortPatientFormController"); String redirectUrl = controller.saveShortPatient(mockWebRequest, (PersonName) BeanUtils.cloneBean(p.getPersonName()), new PersonAddress(), patientModel, errors, new SimpleSessionStatus()); Assert.assertTrue("Should pass with no validation errors", !errors.hasErrors()); Assert.assertEquals("redirect:/patientDashboard.form?patientId=" + p.getPatientId(), redirectUrl); Assert.assertNotNull(newAddress.getId());//name should have been added to DB } /** * @see {@link ShortPatientFormController#saveShortPatient(WebRequest,PersonName,PersonAddress,ShortPatientModel,BindingResult,SessionStatus)} */ @Test @Verifies(value = "should ignore a new address that was added and voided at same time", method = "saveShortPatient(WebRequest,PersonName,PersonAddress,ShortPatientModel,BindingResult,SessionStatus)") public void saveShortPatient_shouldIgnoreANewAddressThatWasAddedAndVoidedAtSameTime() throws Exception { Patient p = Context.getPatientService().getPatient(2); p.getPersonAddress().setVoided(true); Context.getPatientService().savePatient(p); //make sure all addresses are voided so that whatever is entered a new address Assert.assertNull(p.getPersonAddress()); //add the new address PersonAddress newAddress = new PersonAddress(); newAddress.setAddress1("Kampala"); newAddress.setDateCreated(new Date()); newAddress.setVoided(true); ShortPatientModel patientModel = new ShortPatientModel(p); patientModel.setPersonAddress(newAddress); BindException errors = new BindException(patientModel, "patientModel"); ServletWebRequest mockWebRequest = new ServletWebRequest(new MockHttpServletRequest()); ShortPatientFormController controller = (ShortPatientFormController) applicationContext .getBean("shortPatientFormController"); String redirectUrl = controller.saveShortPatient(mockWebRequest, (PersonName) BeanUtils.cloneBean(p.getPersonName()), new PersonAddress(), patientModel, errors, new SimpleSessionStatus()); Assert.assertTrue("Should pass with no validation errors", !errors.hasErrors()); Assert.assertEquals("redirect:/patientDashboard.form?patientId=" + p.getPatientId(), redirectUrl); Assert.assertNull(p.getPersonAddress());//address should have been ignored } }
true
true
public void saveShortPatient_shouldCreateANewPatient() throws Exception { int patientCount = Context.getPatientService().getAllPatients().size(); Patient p = new Patient(); ShortPatientModel patientModel = new ShortPatientModel(p); patientModel.setPersonName(new PersonName("new", "", "patient")); List<PatientIdentifier> identifiers = new ArrayList<PatientIdentifier>(); identifiers.add(new PatientIdentifier("myID", Context.getPatientService().getPatientIdentifierType(2), LocationUtility.getDefaultLocation())); patientModel.setIdentifiers(identifiers); patientModel.getPatient().setBirthdate(new Date()); patientModel.getPatient().setGender("M"); WebRequest mockWebRequest = new ServletWebRequest(new MockHttpServletRequest()); BindException errors = new BindException(patientModel, "patientModel"); ShortPatientFormController controller = (ShortPatientFormController) applicationContext .getBean("shortPatientFormController"); String redirectUrl = controller.saveShortPatient(mockWebRequest, new PersonName(), new PersonAddress(), patientModel, errors, new SimpleSessionStatus()); Assert.assertTrue("Should pass with no validation errors", !errors.hasErrors()); Assert.assertNotNull(p.getId()); Assert.assertNotNull(p.getPersonName()); Assert.assertNotNull(p.getPersonName().getId());//the name was create and added Assert.assertEquals(patientCount + 1, Context.getPatientService().getAllPatients().size()); Assert.assertEquals("Patient.saved", mockWebRequest.getAttribute(WebConstants.OPENMRS_MSG_ATTR, WebRequest.SCOPE_SESSION)); Assert.assertEquals("redirect:/patientDashboard.form?patientId=" + p.getPatientId(), redirectUrl); }
public void saveShortPatient_shouldCreateANewPatient() throws Exception { int patientCount = Context.getPatientService().getAllPatients().size(); Patient p = new Patient(); ShortPatientModel patientModel = new ShortPatientModel(p); patientModel.setPersonName(new PersonName("new", "", "patient")); List<PatientIdentifier> identifiers = new ArrayList<PatientIdentifier>(); PatientIdentifier id = new PatientIdentifier("myID", Context.getPatientService().getPatientIdentifierType(2), LocationUtility.getDefaultLocation()); id.setPreferred(true); identifiers.add(id); patientModel.setIdentifiers(identifiers); patientModel.getPatient().setBirthdate(new Date()); patientModel.getPatient().setGender("M"); WebRequest mockWebRequest = new ServletWebRequest(new MockHttpServletRequest()); BindException errors = new BindException(patientModel, "patientModel"); ShortPatientFormController controller = (ShortPatientFormController) applicationContext .getBean("shortPatientFormController"); String redirectUrl = controller.saveShortPatient(mockWebRequest, new PersonName(), new PersonAddress(), patientModel, errors, new SimpleSessionStatus()); Assert.assertTrue("Should pass with no validation errors", !errors.hasErrors()); Assert.assertNotNull(p.getId()); Assert.assertNotNull(p.getPersonName()); Assert.assertNotNull(p.getPersonName().getId());//the name was create and added Assert.assertEquals(patientCount + 1, Context.getPatientService().getAllPatients().size()); Assert.assertEquals("Patient.saved", mockWebRequest.getAttribute(WebConstants.OPENMRS_MSG_ATTR, WebRequest.SCOPE_SESSION)); Assert.assertEquals("redirect:/patientDashboard.form?patientId=" + p.getPatientId(), redirectUrl); }
diff --git a/maven-core/src/main/java/org/apache/maven/plugin/DefaultPluginManager.java b/maven-core/src/main/java/org/apache/maven/plugin/DefaultPluginManager.java index 5e55a7273..1237e5347 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/DefaultPluginManager.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/DefaultPluginManager.java @@ -1,1191 +1,1191 @@ package org.apache.maven.plugin; /* * Copyright 2001-2005 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.artifact.Artifact; import org.apache.maven.artifact.factory.ArtifactFactory; import org.apache.maven.artifact.metadata.ArtifactMetadataRetrievalException; import org.apache.maven.artifact.metadata.ArtifactMetadataSource; import org.apache.maven.artifact.metadata.ResolutionGroup; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.resolver.ArtifactNotFoundException; import org.apache.maven.artifact.resolver.ArtifactResolutionException; import org.apache.maven.artifact.resolver.ArtifactResolutionResult; import org.apache.maven.artifact.resolver.ArtifactResolver; import org.apache.maven.artifact.resolver.filter.ArtifactFilter; import org.apache.maven.artifact.resolver.filter.ExclusionSetFilter; import org.apache.maven.artifact.resolver.filter.ScopeArtifactFilter; import org.apache.maven.artifact.versioning.DefaultArtifactVersion; import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException; import org.apache.maven.artifact.versioning.VersionRange; import org.apache.maven.execution.MavenSession; import org.apache.maven.execution.RuntimeInformation; import org.apache.maven.model.Plugin; import org.apache.maven.model.ReportPlugin; import org.apache.maven.monitor.event.EventDispatcher; import org.apache.maven.monitor.event.MavenEvents; import org.apache.maven.monitor.logging.DefaultLog; import org.apache.maven.plugin.descriptor.MojoDescriptor; import org.apache.maven.plugin.descriptor.Parameter; import org.apache.maven.plugin.descriptor.PluginDescriptor; import org.apache.maven.plugin.descriptor.PluginDescriptorBuilder; import org.apache.maven.plugin.logging.Log; import org.apache.maven.plugin.version.PluginVersionManager; import org.apache.maven.plugin.version.PluginVersionNotFoundException; import org.apache.maven.plugin.version.PluginVersionResolutionException; import org.apache.maven.project.MavenProject; import org.apache.maven.project.MavenProjectBuilder; import org.apache.maven.project.ProjectBuildingException; import org.apache.maven.project.artifact.InvalidDependencyVersionException; import org.apache.maven.project.artifact.MavenMetadataSource; import org.apache.maven.project.path.PathTranslator; import org.apache.maven.reporting.MavenReport; import org.apache.maven.settings.Settings; import org.codehaus.plexus.PlexusConstants; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.PlexusContainerException; import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import org.codehaus.plexus.component.configurator.ComponentConfigurator; import org.codehaus.plexus.component.configurator.ConfigurationListener; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.component.repository.exception.ComponentLifecycleException; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.configuration.PlexusConfiguration; import org.codehaus.plexus.configuration.xml.XmlPlexusConfiguration; import org.codehaus.plexus.context.Context; import org.codehaus.plexus.context.ContextException; import org.codehaus.plexus.logging.AbstractLogEnabled; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Contextualizable; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable; import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.xml.Xpp3Dom; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; public class DefaultPluginManager extends AbstractLogEnabled implements PluginManager, Initializable, Contextualizable { protected PlexusContainer container; protected PluginDescriptorBuilder pluginDescriptorBuilder; protected ArtifactFilter artifactFilter; private Log mojoLogger; private Map resolvedCoreArtifactFiles = new HashMap(); // component requirements protected PathTranslator pathTranslator; protected MavenPluginCollector pluginCollector; protected PluginVersionManager pluginVersionManager; protected ArtifactFactory artifactFactory; protected ArtifactResolver artifactResolver; protected ArtifactMetadataSource artifactMetadataSource; protected RuntimeInformation runtimeInformation; protected MavenProjectBuilder mavenProjectBuilder; protected PluginMappingManager pluginMappingManager; // END component requirements public DefaultPluginManager() { pluginDescriptorBuilder = new PluginDescriptorBuilder(); } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- public PluginDescriptor getPluginDescriptorForPrefix( String prefix ) { return pluginCollector.getPluginDescriptorForPrefix( prefix ); } public Plugin getPluginDefinitionForPrefix( String prefix, MavenSession session, MavenProject project ) { // TODO: since this is only used in the lifecycle executor, maybe it should be moved there? There is no other // use for the mapping manager in here return pluginMappingManager.getByPrefix( prefix, session.getSettings().getPluginGroups(), project.getPluginArtifactRepositories(), session.getLocalRepository() ); } public PluginDescriptor verifyPlugin( Plugin plugin, MavenProject project, Settings settings, ArtifactRepository localRepository ) throws ArtifactResolutionException, PluginVersionResolutionException, ArtifactNotFoundException, InvalidVersionSpecificationException, InvalidPluginException, PluginManagerException, PluginNotFoundException, PluginVersionNotFoundException { // TODO: this should be possibly outside // All version-resolution logic has been moved to DefaultPluginVersionManager. if ( plugin.getVersion() == null ) { String version = pluginVersionManager.resolvePluginVersion( plugin.getGroupId(), plugin.getArtifactId(), project, settings, localRepository ); plugin.setVersion( version ); } return verifyVersionedPlugin( plugin, project, localRepository ); } private PluginDescriptor verifyVersionedPlugin( Plugin plugin, MavenProject project, ArtifactRepository localRepository ) throws PluginVersionResolutionException, ArtifactNotFoundException, ArtifactResolutionException, InvalidVersionSpecificationException, InvalidPluginException, PluginManagerException, PluginNotFoundException { // TODO: this might result in an artifact "RELEASE" being resolved continuously // FIXME: need to find out how a plugin gets marked as 'installed' // and no ChildContainer exists. The check for that below fixes // the 'Can't find plexus container for plugin: xxx' error. try { VersionRange versionRange = VersionRange.createFromVersionSpec( plugin.getVersion() ); List remoteRepositories = new ArrayList(); remoteRepositories.addAll( project.getPluginArtifactRepositories() ); remoteRepositories.addAll( project.getRemoteArtifactRepositories() ); checkRequiredMavenVersion( plugin, localRepository, remoteRepositories ); Artifact pluginArtifact = artifactFactory.createPluginArtifact( plugin.getGroupId(), plugin.getArtifactId(), versionRange ); pluginArtifact = project.replaceWithActiveArtifact( pluginArtifact ); artifactResolver.resolve( pluginArtifact, project.getPluginArtifactRepositories(), localRepository ); PlexusContainer pluginContainer = container.getChildContainer( plugin.getKey() ); File pluginFile = pluginArtifact.getFile(); if ( !pluginCollector.isPluginInstalled( plugin ) || pluginContainer == null ) { addPlugin( plugin, pluginArtifact, project, localRepository ); } else if ( pluginFile.lastModified() > pluginContainer.getCreationDate().getTime() ) { getLogger().info( "Reloading plugin container for: " + plugin.getKey() + ". The plugin artifact has changed." ); pluginContainer.dispose(); pluginCollector.flushPluginDescriptor( plugin ); addPlugin( plugin, pluginArtifact, project, localRepository ); } project.addPlugin( plugin ); } catch ( ArtifactNotFoundException e ) { String groupId = plugin.getGroupId(); String artifactId = plugin.getArtifactId(); String version = plugin.getVersion(); if ( groupId == null || artifactId == null || version == null ) { throw new PluginNotFoundException( e ); } else if ( groupId.equals( e.getGroupId() ) && artifactId.equals( e.getArtifactId() ) && version.equals( e.getVersion() ) && "maven-plugin".equals( e.getType() ) ) { throw new PluginNotFoundException( e ); } else { throw e; } } return pluginCollector.getPluginDescriptor( plugin ); } /** * @todo would be better to store this in the plugin descriptor, but then it won't be available to the version * manager which executes before the plugin is instantiated */ private void checkRequiredMavenVersion( Plugin plugin, ArtifactRepository localRepository, List remoteRepositories ) throws PluginVersionResolutionException, InvalidPluginException { try { Artifact artifact = artifactFactory.createProjectArtifact( plugin.getGroupId(), plugin.getArtifactId(), plugin.getVersion() ); MavenProject project = mavenProjectBuilder.buildFromRepository( artifact, remoteRepositories, localRepository, false ); // if we don't have the required Maven version, then ignore an update if ( project.getPrerequisites() != null && project.getPrerequisites().getMaven() != null ) { DefaultArtifactVersion requiredVersion = new DefaultArtifactVersion( project.getPrerequisites().getMaven() ); if ( runtimeInformation.getApplicationVersion().compareTo( requiredVersion ) < 0 ) { throw new PluginVersionResolutionException( plugin.getGroupId(), plugin.getArtifactId(), "Plugin requires Maven version " + requiredVersion ); } } } catch ( ProjectBuildingException e ) { throw new InvalidPluginException( "Unable to build project for plugin '" + plugin.getKey() + "': " + e.getMessage(), e ); } } protected void addPlugin( Plugin plugin, Artifact pluginArtifact, MavenProject project, ArtifactRepository localRepository ) throws PluginManagerException, InvalidPluginException { PlexusContainer child; try { child = container.createChildContainer( plugin.getKey(), Collections.singletonList( pluginArtifact.getFile() ), Collections.EMPTY_MAP, Collections.singletonList( pluginCollector ) ); } catch ( PlexusContainerException e ) { throw new PluginManagerException( "Failed to create plugin container for plugin '" + plugin + "': " + e.getMessage(), e ); } // this plugin's descriptor should have been discovered in the child creation, so we should be able to // circle around and set the artifacts and class realm PluginDescriptor addedPlugin = pluginCollector.getPluginDescriptor( plugin ); addedPlugin.setClassRealm( child.getContainerRealm() ); // we're only setting the plugin's artifact itself as the artifact list, to allow it to be retrieved // later when the plugin is first invoked. Retrieving this artifact will in turn allow us to // transitively resolve its dependencies, and add them to the plugin container... addedPlugin.setArtifacts( Collections.singletonList( pluginArtifact ) ); try { // the only Plugin instance which will have dependencies is the one specified in the project. // We need to look for a Plugin instance there, in case the instance we're using didn't come from // the project. Plugin projectPlugin = (Plugin) project.getBuild().getPluginsAsMap().get( plugin.getKey() ); if ( projectPlugin == null ) { projectPlugin = plugin; } Set artifacts = MavenMetadataSource.createArtifacts( artifactFactory, projectPlugin.getDependencies(), null, null, project ); // Set artifacts = // MavenMetadataSource.createArtifacts( artifactFactory, plugin.getDependencies(), null, null, project ); addedPlugin.setIntroducedDependencyArtifacts( artifacts ); } catch ( InvalidDependencyVersionException e ) { throw new InvalidPluginException( "Plugin '" + plugin + "' is invalid: " + e.getMessage(), e ); } } // ---------------------------------------------------------------------- // Mojo execution // ---------------------------------------------------------------------- public void executeMojo( MavenProject project, MojoExecution mojoExecution, MavenSession session ) throws ArtifactResolutionException, MojoExecutionException, MojoFailureException, ArtifactNotFoundException, InvalidDependencyVersionException, PluginManagerException, PluginConfigurationException { MojoDescriptor mojoDescriptor = mojoExecution.getMojoDescriptor(); // NOTE: I'm putting these checks in here, since this is the central point of access for // anything that wants to execute a mojo. if ( mojoDescriptor.isProjectRequired() && !session.isUsingPOMsFromFilesystem() ) { throw new MojoExecutionException( "Cannot execute mojo: " + mojoDescriptor.getGoal() + - ". It requires a project, but the build is not using one." ); + ". It requires a project with an existing pom.xml, but the build is not using one." ); } if ( mojoDescriptor.isOnlineRequired() && session.getSettings().isOffline() ) { // TODO: Should we error out, or simply warn and skip?? throw new MojoExecutionException( "Mojo: " + mojoDescriptor.getGoal() + " requires online mode for execution. Maven is currently offline." ); } if ( mojoDescriptor.isDependencyResolutionRequired() != null ) { Collection projects; if ( mojoDescriptor.isAggregator() ) { projects = session.getSortedProjects(); } else { projects = Collections.singleton( project ); } for ( Iterator i = projects.iterator(); i.hasNext(); ) { MavenProject p = (MavenProject) i.next(); resolveTransitiveDependencies( session, artifactResolver, mojoDescriptor.isDependencyResolutionRequired(), artifactFactory, p ); } downloadDependencies( project, session, artifactResolver ); } String goalName = mojoDescriptor.getFullGoalName(); Mojo plugin; PluginDescriptor pluginDescriptor = mojoDescriptor.getPluginDescriptor(); String goalId = mojoDescriptor.getGoal(); String groupId = pluginDescriptor.getGroupId(); String artifactId = pluginDescriptor.getArtifactId(); String executionId = mojoExecution.getExecutionId(); Xpp3Dom dom = project.getGoalConfiguration( groupId, artifactId, executionId, goalId ); Xpp3Dom reportDom = project.getReportConfiguration( groupId, artifactId, executionId ); dom = Xpp3Dom.mergeXpp3Dom( dom, reportDom ); if ( mojoExecution.getConfiguration() != null ) { dom = Xpp3Dom.mergeXpp3Dom( dom, mojoExecution.getConfiguration() ); } plugin = getConfiguredMojo( session, dom, project, false, mojoExecution ); // Event monitoring. String event = MavenEvents.MOJO_EXECUTION; EventDispatcher dispatcher = session.getEventDispatcher(); String goalExecId = goalName; if ( mojoExecution.getExecutionId() != null ) { goalExecId += " {execution: " + mojoExecution.getExecutionId() + "}"; } dispatcher.dispatchStart( event, goalExecId ); ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( mojoDescriptor.getPluginDescriptor().getClassRealm().getClassLoader() ); plugin.execute(); dispatcher.dispatchEnd( event, goalExecId ); } catch ( MojoExecutionException e ) { session.getEventDispatcher().dispatchError( event, goalExecId, e ); throw e; } catch ( MojoFailureException e ) { session.getEventDispatcher().dispatchError( event, goalExecId, e ); throw e; } finally { Thread.currentThread().setContextClassLoader( oldClassLoader ); try { PlexusContainer pluginContainer = getPluginContainer( mojoDescriptor.getPluginDescriptor() ); pluginContainer.release( plugin ); } catch ( ComponentLifecycleException e ) { if ( getLogger().isErrorEnabled() ) { getLogger().error( "Error releasing plugin - ignoring.", e ); } } } } public MavenReport getReport( MavenProject project, MojoExecution mojoExecution, MavenSession session ) throws ArtifactNotFoundException, PluginConfigurationException, PluginManagerException, ArtifactResolutionException { MojoDescriptor mojoDescriptor = mojoExecution.getMojoDescriptor(); PluginDescriptor descriptor = mojoDescriptor.getPluginDescriptor(); Xpp3Dom dom = project.getReportConfiguration( descriptor.getGroupId(), descriptor.getArtifactId(), mojoExecution.getExecutionId() ); if ( mojoExecution.getConfiguration() != null ) { dom = Xpp3Dom.mergeXpp3Dom( dom, mojoExecution.getConfiguration() ); } return (MavenReport) getConfiguredMojo( session, dom, project, true, mojoExecution ); } public PluginDescriptor verifyReportPlugin( ReportPlugin reportPlugin, MavenProject project, MavenSession session ) throws PluginVersionResolutionException, ArtifactResolutionException, ArtifactNotFoundException, InvalidVersionSpecificationException, InvalidPluginException, PluginManagerException, PluginNotFoundException, PluginVersionNotFoundException { String version = reportPlugin.getVersion(); if ( version == null ) { version = pluginVersionManager.resolveReportPluginVersion( reportPlugin.getGroupId(), reportPlugin.getArtifactId(), project, session.getSettings(), session.getLocalRepository() ); reportPlugin.setVersion( version ); } Plugin forLookup = new Plugin(); forLookup.setGroupId( reportPlugin.getGroupId() ); forLookup.setArtifactId( reportPlugin.getArtifactId() ); forLookup.setVersion( version ); return verifyVersionedPlugin( forLookup, project, session.getLocalRepository() ); } private PlexusContainer getPluginContainer( PluginDescriptor pluginDescriptor ) throws PluginManagerException { String pluginKey = pluginDescriptor.getPluginLookupKey(); PlexusContainer pluginContainer = container.getChildContainer( pluginKey ); if ( pluginContainer == null ) { throw new PluginManagerException( "Cannot find Plexus container for plugin: " + pluginKey ); } return pluginContainer; } private Mojo getConfiguredMojo( MavenSession session, Xpp3Dom dom, MavenProject project, boolean report, MojoExecution mojoExecution ) throws PluginConfigurationException, ArtifactNotFoundException, PluginManagerException, ArtifactResolutionException { MojoDescriptor mojoDescriptor = mojoExecution.getMojoDescriptor(); PluginDescriptor pluginDescriptor = mojoDescriptor.getPluginDescriptor(); PlexusContainer pluginContainer = getPluginContainer( pluginDescriptor ); // if this is the first time this plugin has been used, the plugin's container will only // contain the plugin's artifact in isolation; we need to finish resolving the plugin's // dependencies, and add them to the container. ensurePluginContainerIsComplete( pluginDescriptor, pluginContainer, project, session ); Mojo plugin; try { plugin = (Mojo) pluginContainer.lookup( Mojo.ROLE, mojoDescriptor.getRoleHint() ); if ( report && !( plugin instanceof MavenReport ) ) { // TODO: the mojoDescriptor should actually capture this information so we don't get this far return null; } } catch ( ComponentLookupException e ) { throw new PluginManagerException( "Unable to find the mojo '" + mojoDescriptor.getRoleHint() + "' in the plugin '" + pluginDescriptor.getPluginLookupKey() + "'", e ); } if ( plugin instanceof ContextEnabled ) { Map pluginContext = session.getPluginContext( pluginDescriptor, project ); ( (ContextEnabled) plugin ).setPluginContext( pluginContext ); } plugin.setLog( mojoLogger ); XmlPlexusConfiguration pomConfiguration; if ( dom == null ) { pomConfiguration = new XmlPlexusConfiguration( "configuration" ); } else { pomConfiguration = new XmlPlexusConfiguration( dom ); } // Validate against non-editable (@readonly) parameters, to make sure users aren't trying to // override in the POM. validatePomConfiguration( mojoDescriptor, pomConfiguration ); PlexusConfiguration mergedConfiguration = mergeMojoConfiguration( pomConfiguration, mojoDescriptor ); // TODO: plexus changes to make this more like the component descriptor so this can be used instead // PlexusConfiguration mergedConfiguration = mergeConfiguration( pomConfiguration, // mojoDescriptor.getConfiguration() ); ExpressionEvaluator expressionEvaluator = new PluginParameterExpressionEvaluator( session, mojoExecution, pathTranslator, getLogger(), project, session.getExecutionProperties() ); PlexusConfiguration extractedMojoConfiguration = extractMojoConfiguration( mergedConfiguration, mojoDescriptor ); checkRequiredParameters( mojoDescriptor, extractedMojoConfiguration, expressionEvaluator ); populatePluginFields( plugin, mojoDescriptor, extractedMojoConfiguration, pluginContainer, expressionEvaluator ); return plugin; } private void ensurePluginContainerIsComplete( PluginDescriptor pluginDescriptor, PlexusContainer pluginContainer, MavenProject project, MavenSession session ) throws ArtifactNotFoundException, PluginManagerException, ArtifactResolutionException { // if the plugin's already been used once, don't re-do this step... // otherwise, we have to finish resolving the plugin's classpath and start the container. if ( pluginDescriptor.getArtifacts() != null && pluginDescriptor.getArtifacts().size() == 1 ) { Artifact pluginArtifact = (Artifact) pluginDescriptor.getArtifacts().get( 0 ); ArtifactRepository localRepository = session.getLocalRepository(); ResolutionGroup resolutionGroup; try { resolutionGroup = artifactMetadataSource.retrieve( pluginArtifact, localRepository, project.getPluginArtifactRepositories() ); } catch ( ArtifactMetadataRetrievalException e ) { throw new ArtifactResolutionException( "Unable to download metadata from repository for plugin '" + pluginArtifact.getId() + "': " + e.getMessage(), pluginArtifact, e ); } Set dependencies = new HashSet( resolutionGroup.getArtifacts() ); dependencies.addAll( pluginDescriptor.getIntroducedDependencyArtifacts() ); ArtifactResolutionResult result = artifactResolver.resolveTransitively( dependencies, pluginArtifact, localRepository, resolutionGroup.getResolutionRepositories(), artifactMetadataSource, artifactFilter ); Set resolved = result.getArtifacts(); for ( Iterator it = resolved.iterator(); it.hasNext(); ) { Artifact artifact = (Artifact) it.next(); if ( !artifact.equals( pluginArtifact ) ) { artifact = project.replaceWithActiveArtifact( artifact ); try { pluginContainer.addJarResource( artifact.getFile() ); } catch ( PlexusContainerException e ) { throw new PluginManagerException( "Error adding plugin dependency '" + artifact.getDependencyConflictId() + "' into plugin manager: " + e.getMessage(), e ); } } } pluginDescriptor.setClassRealm( pluginContainer.getContainerRealm() ); List unresolved = new ArrayList( dependencies ); unresolved.removeAll( resolved ); resolveCoreArtifacts( unresolved, localRepository, resolutionGroup.getResolutionRepositories() ); List allResolved = new ArrayList( resolved.size() + unresolved.size() ); allResolved.addAll( resolved ); allResolved.addAll( unresolved ); pluginDescriptor.setArtifacts( allResolved ); } } private void resolveCoreArtifacts( List unresolved, ArtifactRepository localRepository, List resolutionRepositories ) throws ArtifactResolutionException, ArtifactNotFoundException { for ( Iterator it = unresolved.iterator(); it.hasNext(); ) { Artifact artifact = (Artifact) it.next(); File artifactFile = (File) resolvedCoreArtifactFiles.get( artifact.getId() ); if ( artifactFile == null ) { String resource = "/META-INF/maven/" + artifact.getGroupId() + "/" + artifact.getArtifactId() + "/pom.xml"; URL resourceUrl = container.getContainerRealm().getResource( resource ); if ( resourceUrl == null ) { artifactResolver.resolve( artifact, resolutionRepositories, localRepository ); artifactFile = artifact.getFile(); } else { String artifactPath = resourceUrl.getPath(); if ( artifactPath.startsWith( "file:" ) ) { artifactPath = artifactPath.substring( "file:".length() ); } artifactPath = artifactPath.substring( 0, artifactPath.length() - resource.length() ); if ( artifactPath.endsWith( "/" ) ) { artifactPath = artifactPath.substring( 0, artifactPath.length() - 1 ); } if ( artifactPath.endsWith( "!" ) ) { artifactPath = artifactPath.substring( 0, artifactPath.length() - 1 ); } artifactFile = new File( artifactPath ).getAbsoluteFile(); } resolvedCoreArtifactFiles.put( artifact.getId(), artifactFile ); } artifact.setFile( artifactFile ); } } private PlexusConfiguration extractMojoConfiguration( PlexusConfiguration mergedConfiguration, MojoDescriptor mojoDescriptor ) { Map parameterMap = mojoDescriptor.getParameterMap(); PlexusConfiguration[] mergedChildren = mergedConfiguration.getChildren(); XmlPlexusConfiguration extractedConfiguration = new XmlPlexusConfiguration( "configuration" ); for ( int i = 0; i < mergedChildren.length; i++ ) { PlexusConfiguration child = mergedChildren[i]; if ( parameterMap.containsKey( child.getName() ) ) { extractedConfiguration.addChild( copyConfiguration( child ) ); } else { // TODO: I defy anyone to find these messages in the '-X' output! Do we need a new log level? // ideally, this would be elevated above the true debug output, but below the default INFO level... // [BP] (2004-07-18): need to understand the context more but would prefer this could be either WARN or // removed - shouldn't need DEBUG to diagnose a problem most of the time. getLogger().debug( "*** WARNING: Configuration \'" + child.getName() + "\' is not used in goal \'" + mojoDescriptor.getFullGoalName() + "; this may indicate a typo... ***" ); } } return extractedConfiguration; } private void checkRequiredParameters( MojoDescriptor goal, PlexusConfiguration configuration, ExpressionEvaluator expressionEvaluator ) throws PluginConfigurationException { // TODO: this should be built in to the configurator, as we presently double process the expressions List parameters = goal.getParameters(); if ( parameters == null ) { return; } List invalidParameters = new ArrayList(); for ( int i = 0; i < parameters.size(); i++ ) { Parameter parameter = (Parameter) parameters.get( i ); if ( parameter.isRequired() ) { // the key for the configuration map we're building. String key = parameter.getName(); Object fieldValue = null; String expression = null; PlexusConfiguration value = configuration.getChild( key, false ); try { if ( value != null ) { expression = value.getValue( null ); fieldValue = expressionEvaluator.evaluate( expression ); if ( fieldValue == null ) { fieldValue = value.getAttribute( "default-value", null ); } } if ( fieldValue == null && StringUtils.isNotEmpty( parameter.getAlias() ) ) { value = configuration.getChild( parameter.getAlias(), false ); if ( value != null ) { expression = value.getValue( null ); fieldValue = expressionEvaluator.evaluate( expression ); if ( fieldValue == null ) { fieldValue = value.getAttribute( "default-value", null ); } } } } catch ( ExpressionEvaluationException e ) { throw new PluginConfigurationException( goal.getPluginDescriptor(), e.getMessage(), e ); } // only mark as invalid if there are no child nodes if ( fieldValue == null && ( value == null || value.getChildCount() == 0 ) ) { parameter.setExpression( expression ); invalidParameters.add( parameter ); } } } if ( !invalidParameters.isEmpty() ) { throw new PluginParameterException( goal, invalidParameters ); } } private void validatePomConfiguration( MojoDescriptor goal, PlexusConfiguration pomConfiguration ) throws PluginConfigurationException { List parameters = goal.getParameters(); if ( parameters == null ) { return; } for ( int i = 0; i < parameters.size(); i++ ) { Parameter parameter = (Parameter) parameters.get( i ); // the key for the configuration map we're building. String key = parameter.getName(); PlexusConfiguration value = pomConfiguration.getChild( key, false ); if ( value == null && StringUtils.isNotEmpty( parameter.getAlias() ) ) { key = parameter.getAlias(); value = pomConfiguration.getChild( key, false ); } if ( value != null ) { // Make sure the parameter is either editable/configurable, or else is NOT specified in the POM if ( !parameter.isEditable() ) { StringBuffer errorMessage = new StringBuffer() .append( "ERROR: Cannot override read-only parameter: " ); errorMessage.append( key ); errorMessage.append( " in goal: " ).append( goal.getFullGoalName() ); throw new PluginConfigurationException( goal.getPluginDescriptor(), errorMessage.toString() ); } String deprecated = parameter.getDeprecated(); if ( StringUtils.isNotEmpty( deprecated ) ) { getLogger().warn( "DEPRECATED [" + parameter.getName() + "]: " + deprecated ); } } } } private PlexusConfiguration mergeMojoConfiguration( XmlPlexusConfiguration fromPom, MojoDescriptor mojoDescriptor ) { XmlPlexusConfiguration result = new XmlPlexusConfiguration( fromPom.getName() ); result.setValue( fromPom.getValue( null ) ); if ( mojoDescriptor.getParameters() != null ) { PlexusConfiguration fromMojo = mojoDescriptor.getMojoConfiguration(); for ( Iterator it = mojoDescriptor.getParameters().iterator(); it.hasNext(); ) { Parameter parameter = (Parameter) it.next(); String paramName = parameter.getName(); String alias = parameter.getAlias(); PlexusConfiguration pomConfig = fromPom.getChild( paramName ); PlexusConfiguration aliased = null; if ( alias != null ) { aliased = fromPom.getChild( alias ); } PlexusConfiguration mojoConfig = fromMojo.getChild( paramName, false ); // first we'll merge configurations from the aliased and real params. // TODO: Is this the right thing to do? if ( aliased != null ) { if ( pomConfig == null ) { pomConfig = new XmlPlexusConfiguration( paramName ); } pomConfig = buildTopDownMergedConfiguration( pomConfig, aliased ); } boolean addedPomConfig = false; if ( pomConfig != null ) { pomConfig = buildTopDownMergedConfiguration( pomConfig, mojoConfig ); if ( StringUtils.isNotEmpty( pomConfig.getValue( null ) ) || pomConfig.getChildCount() > 0 ) { result.addChild( pomConfig ); addedPomConfig = true; } } if ( !addedPomConfig && mojoConfig != null ) { result.addChild( copyConfiguration( mojoConfig ) ); } } } return result; } private XmlPlexusConfiguration buildTopDownMergedConfiguration( PlexusConfiguration dominant, PlexusConfiguration recessive ) { XmlPlexusConfiguration result = new XmlPlexusConfiguration( dominant.getName() ); String value = dominant.getValue( null ); if ( StringUtils.isEmpty( value ) && recessive != null ) { value = recessive.getValue( null ); } if ( StringUtils.isNotEmpty( value ) ) { result.setValue( value ); } String[] attributeNames = dominant.getAttributeNames(); for ( int i = 0; i < attributeNames.length; i++ ) { String attributeValue = dominant.getAttribute( attributeNames[i], null ); result.setAttribute( attributeNames[i], attributeValue ); } if ( recessive != null ) { attributeNames = recessive.getAttributeNames(); for ( int i = 0; i < attributeNames.length; i++ ) { String attributeValue = recessive.getAttribute( attributeNames[i], null ); // TODO: recessive seems to be dominant here? result.setAttribute( attributeNames[i], attributeValue ); } } PlexusConfiguration[] children = dominant.getChildren(); for ( int i = 0; i < children.length; i++ ) { PlexusConfiguration childDom = children[i]; PlexusConfiguration childRec = recessive == null ? null : recessive.getChild( childDom.getName(), false ); if ( childRec != null ) { result.addChild( buildTopDownMergedConfiguration( childDom, childRec ) ); } else { // FIXME: copy, or use reference? result.addChild( copyConfiguration( childDom ) ); } } return result; } public static PlexusConfiguration copyConfiguration( PlexusConfiguration src ) { // TODO: shouldn't be necessary XmlPlexusConfiguration dom = new XmlPlexusConfiguration( src.getName() ); dom.setValue( src.getValue( null ) ); String[] attributeNames = src.getAttributeNames(); for ( int i = 0; i < attributeNames.length; i++ ) { String attributeName = attributeNames[i]; dom.setAttribute( attributeName, src.getAttribute( attributeName, null ) ); } PlexusConfiguration[] children = src.getChildren(); for ( int i = 0; i < children.length; i++ ) { dom.addChild( copyConfiguration( children[i] ) ); } return dom; } // ---------------------------------------------------------------------- // Mojo Parameter Handling // ---------------------------------------------------------------------- private void populatePluginFields( Mojo plugin, MojoDescriptor mojoDescriptor, PlexusConfiguration configuration, PlexusContainer pluginContainer, ExpressionEvaluator expressionEvaluator ) throws PluginConfigurationException { ComponentConfigurator configurator = null; try { String configuratorId = mojoDescriptor.getComponentConfigurator(); // TODO: could the configuration be passed to lookup and the configurator known to plexus via the descriptor // so that this meethod could entirely be handled by a plexus lookup? if ( StringUtils.isNotEmpty( configuratorId ) ) { configurator = (ComponentConfigurator) pluginContainer.lookup( ComponentConfigurator.ROLE, configuratorId ); } else { configurator = (ComponentConfigurator) pluginContainer.lookup( ComponentConfigurator.ROLE ); } ConfigurationListener listener = new DebugConfigurationListener( getLogger() ); getLogger().debug( "Configuring mojo '" + mojoDescriptor.getId() + "' -->" ); configurator.configureComponent( plugin, configuration, expressionEvaluator, pluginContainer.getContainerRealm(), listener ); getLogger().debug( "-- end configuration --" ); } catch ( ComponentConfigurationException e ) { throw new PluginConfigurationException( mojoDescriptor.getPluginDescriptor(), "Unable to parse the created DOM for plugin configuration", e ); } catch ( ComponentLookupException e ) { throw new PluginConfigurationException( mojoDescriptor.getPluginDescriptor(), "Unable to retrieve component configurator for plugin configuration", e ); } finally { if ( configurator != null ) { try { pluginContainer.release( configurator ); } catch ( ComponentLifecycleException e ) { getLogger().debug( "Failed to release plugin container - ignoring." ); } } } } public static String createPluginParameterRequiredMessage( MojoDescriptor mojo, Parameter parameter, String expression ) { StringBuffer message = new StringBuffer(); message.append( "The '" ); message.append( parameter.getName() ); message.append( "' parameter is required for the execution of the " ); message.append( mojo.getFullGoalName() ); message.append( " mojo and cannot be null." ); if ( expression != null ) { message.append( " The retrieval expression was: " ).append( expression ); } return message.toString(); } // ---------------------------------------------------------------------- // Lifecycle // ---------------------------------------------------------------------- public void contextualize( Context context ) throws ContextException { container = (PlexusContainer) context.get( PlexusConstants.PLEXUS_KEY ); mojoLogger = new DefaultLog( container.getLoggerManager().getLoggerForComponent( Mojo.ROLE ) ); } public void initialize() { // TODO: configure this from bootstrap or scan lib Set artifacts = new HashSet(); artifacts.add( "classworlds" ); artifacts.add( "commons-cli" ); artifacts.add( "doxia-sink-api" ); artifacts.add( "jsch" ); artifacts.add( "maven-artifact" ); artifacts.add( "maven-artifact-manager" ); artifacts.add( "maven-core" ); artifacts.add( "maven-model" ); artifacts.add( "maven-monitor" ); artifacts.add( "maven-plugin-api" ); artifacts.add( "maven-plugin-descriptor" ); artifacts.add( "maven-plugin-parameter-documenter" ); artifacts.add( "maven-plugin-registry" ); artifacts.add( "maven-profile" ); artifacts.add( "maven-project" ); artifacts.add( "maven-reporting-api" ); artifacts.add( "maven-repository-metadata" ); artifacts.add( "maven-settings" ); artifacts.add( "plexus-container-default" ); artifacts.add( "plexus-interactivity-api" ); artifacts.add( "plexus-utils" ); artifacts.add( "wagon-provider-api" ); artifacts.add( "wagon-file" ); artifacts.add( "wagon-http-lightweight" ); artifacts.add( "wagon-ssh" ); artifactFilter = new ExclusionSetFilter( artifacts ); } // ---------------------------------------------------------------------- // Artifact resolution // ---------------------------------------------------------------------- private void resolveTransitiveDependencies( MavenSession context, ArtifactResolver artifactResolver, String scope, ArtifactFactory artifactFactory, MavenProject project ) throws ArtifactResolutionException, ArtifactNotFoundException, InvalidDependencyVersionException { ArtifactFilter filter = new ScopeArtifactFilter( scope ); // TODO: such a call in MavenMetadataSource too - packaging not really the intention of type Artifact artifact = artifactFactory.createBuildArtifact( project.getGroupId(), project.getArtifactId(), project.getVersion(), project.getPackaging() ); // TODO: we don't need to resolve over and over again, as long as we are sure that the parameters are the same // check this with yourkit as a hot spot. // Don't recreate if already created - for effeciency, and because clover plugin adds to it if ( project.getDependencyArtifacts() == null ) { project.setDependencyArtifacts( project.createArtifacts( artifactFactory, null, null ) ); } ArtifactResolutionResult result = artifactResolver.resolveTransitively( project.getDependencyArtifacts(), artifact, context.getLocalRepository(), project.getRemoteArtifactRepositories(), artifactMetadataSource, filter ); project.setArtifacts( result.getArtifacts() ); } // ---------------------------------------------------------------------- // Artifact downloading // ---------------------------------------------------------------------- private void downloadDependencies( MavenProject project, MavenSession context, ArtifactResolver artifactResolver ) throws ArtifactResolutionException, ArtifactNotFoundException { ArtifactRepository localRepository = context.getLocalRepository(); List remoteArtifactRepositories = project.getRemoteArtifactRepositories(); for ( Iterator it = project.getArtifacts().iterator(); it.hasNext(); ) { Artifact artifact = (Artifact) it.next(); artifactResolver.resolve( artifact, remoteArtifactRepositories, localRepository ); } } public Object getPluginComponent( Plugin plugin, String role, String roleHint ) throws PluginManagerException, ComponentLookupException { PluginDescriptor pluginDescriptor = pluginCollector.getPluginDescriptor( plugin ); PlexusContainer pluginContainer = getPluginContainer( pluginDescriptor ); return pluginContainer.lookup( role, roleHint ); } public Map getPluginComponents( Plugin plugin, String role ) throws ComponentLookupException, PluginManagerException { PluginDescriptor pluginDescriptor = pluginCollector.getPluginDescriptor( plugin ); PlexusContainer pluginContainer = getPluginContainer( pluginDescriptor ); return pluginContainer.lookupMap( role ); } }
true
true
public void executeMojo( MavenProject project, MojoExecution mojoExecution, MavenSession session ) throws ArtifactResolutionException, MojoExecutionException, MojoFailureException, ArtifactNotFoundException, InvalidDependencyVersionException, PluginManagerException, PluginConfigurationException { MojoDescriptor mojoDescriptor = mojoExecution.getMojoDescriptor(); // NOTE: I'm putting these checks in here, since this is the central point of access for // anything that wants to execute a mojo. if ( mojoDescriptor.isProjectRequired() && !session.isUsingPOMsFromFilesystem() ) { throw new MojoExecutionException( "Cannot execute mojo: " + mojoDescriptor.getGoal() + ". It requires a project, but the build is not using one." ); } if ( mojoDescriptor.isOnlineRequired() && session.getSettings().isOffline() ) { // TODO: Should we error out, or simply warn and skip?? throw new MojoExecutionException( "Mojo: " + mojoDescriptor.getGoal() + " requires online mode for execution. Maven is currently offline." ); } if ( mojoDescriptor.isDependencyResolutionRequired() != null ) { Collection projects; if ( mojoDescriptor.isAggregator() ) { projects = session.getSortedProjects(); } else { projects = Collections.singleton( project ); } for ( Iterator i = projects.iterator(); i.hasNext(); ) { MavenProject p = (MavenProject) i.next(); resolveTransitiveDependencies( session, artifactResolver, mojoDescriptor.isDependencyResolutionRequired(), artifactFactory, p ); } downloadDependencies( project, session, artifactResolver ); } String goalName = mojoDescriptor.getFullGoalName(); Mojo plugin; PluginDescriptor pluginDescriptor = mojoDescriptor.getPluginDescriptor(); String goalId = mojoDescriptor.getGoal(); String groupId = pluginDescriptor.getGroupId(); String artifactId = pluginDescriptor.getArtifactId(); String executionId = mojoExecution.getExecutionId(); Xpp3Dom dom = project.getGoalConfiguration( groupId, artifactId, executionId, goalId ); Xpp3Dom reportDom = project.getReportConfiguration( groupId, artifactId, executionId ); dom = Xpp3Dom.mergeXpp3Dom( dom, reportDom ); if ( mojoExecution.getConfiguration() != null ) { dom = Xpp3Dom.mergeXpp3Dom( dom, mojoExecution.getConfiguration() ); } plugin = getConfiguredMojo( session, dom, project, false, mojoExecution ); // Event monitoring. String event = MavenEvents.MOJO_EXECUTION; EventDispatcher dispatcher = session.getEventDispatcher(); String goalExecId = goalName; if ( mojoExecution.getExecutionId() != null ) { goalExecId += " {execution: " + mojoExecution.getExecutionId() + "}"; } dispatcher.dispatchStart( event, goalExecId ); ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( mojoDescriptor.getPluginDescriptor().getClassRealm().getClassLoader() ); plugin.execute(); dispatcher.dispatchEnd( event, goalExecId ); } catch ( MojoExecutionException e ) { session.getEventDispatcher().dispatchError( event, goalExecId, e ); throw e; } catch ( MojoFailureException e ) { session.getEventDispatcher().dispatchError( event, goalExecId, e ); throw e; } finally { Thread.currentThread().setContextClassLoader( oldClassLoader ); try { PlexusContainer pluginContainer = getPluginContainer( mojoDescriptor.getPluginDescriptor() ); pluginContainer.release( plugin ); } catch ( ComponentLifecycleException e ) { if ( getLogger().isErrorEnabled() ) { getLogger().error( "Error releasing plugin - ignoring.", e ); } } } }
public void executeMojo( MavenProject project, MojoExecution mojoExecution, MavenSession session ) throws ArtifactResolutionException, MojoExecutionException, MojoFailureException, ArtifactNotFoundException, InvalidDependencyVersionException, PluginManagerException, PluginConfigurationException { MojoDescriptor mojoDescriptor = mojoExecution.getMojoDescriptor(); // NOTE: I'm putting these checks in here, since this is the central point of access for // anything that wants to execute a mojo. if ( mojoDescriptor.isProjectRequired() && !session.isUsingPOMsFromFilesystem() ) { throw new MojoExecutionException( "Cannot execute mojo: " + mojoDescriptor.getGoal() + ". It requires a project with an existing pom.xml, but the build is not using one." ); } if ( mojoDescriptor.isOnlineRequired() && session.getSettings().isOffline() ) { // TODO: Should we error out, or simply warn and skip?? throw new MojoExecutionException( "Mojo: " + mojoDescriptor.getGoal() + " requires online mode for execution. Maven is currently offline." ); } if ( mojoDescriptor.isDependencyResolutionRequired() != null ) { Collection projects; if ( mojoDescriptor.isAggregator() ) { projects = session.getSortedProjects(); } else { projects = Collections.singleton( project ); } for ( Iterator i = projects.iterator(); i.hasNext(); ) { MavenProject p = (MavenProject) i.next(); resolveTransitiveDependencies( session, artifactResolver, mojoDescriptor.isDependencyResolutionRequired(), artifactFactory, p ); } downloadDependencies( project, session, artifactResolver ); } String goalName = mojoDescriptor.getFullGoalName(); Mojo plugin; PluginDescriptor pluginDescriptor = mojoDescriptor.getPluginDescriptor(); String goalId = mojoDescriptor.getGoal(); String groupId = pluginDescriptor.getGroupId(); String artifactId = pluginDescriptor.getArtifactId(); String executionId = mojoExecution.getExecutionId(); Xpp3Dom dom = project.getGoalConfiguration( groupId, artifactId, executionId, goalId ); Xpp3Dom reportDom = project.getReportConfiguration( groupId, artifactId, executionId ); dom = Xpp3Dom.mergeXpp3Dom( dom, reportDom ); if ( mojoExecution.getConfiguration() != null ) { dom = Xpp3Dom.mergeXpp3Dom( dom, mojoExecution.getConfiguration() ); } plugin = getConfiguredMojo( session, dom, project, false, mojoExecution ); // Event monitoring. String event = MavenEvents.MOJO_EXECUTION; EventDispatcher dispatcher = session.getEventDispatcher(); String goalExecId = goalName; if ( mojoExecution.getExecutionId() != null ) { goalExecId += " {execution: " + mojoExecution.getExecutionId() + "}"; } dispatcher.dispatchStart( event, goalExecId ); ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( mojoDescriptor.getPluginDescriptor().getClassRealm().getClassLoader() ); plugin.execute(); dispatcher.dispatchEnd( event, goalExecId ); } catch ( MojoExecutionException e ) { session.getEventDispatcher().dispatchError( event, goalExecId, e ); throw e; } catch ( MojoFailureException e ) { session.getEventDispatcher().dispatchError( event, goalExecId, e ); throw e; } finally { Thread.currentThread().setContextClassLoader( oldClassLoader ); try { PlexusContainer pluginContainer = getPluginContainer( mojoDescriptor.getPluginDescriptor() ); pluginContainer.release( plugin ); } catch ( ComponentLifecycleException e ) { if ( getLogger().isErrorEnabled() ) { getLogger().error( "Error releasing plugin - ignoring.", e ); } } } }
diff --git a/src/com/vaadin/terminal/gwt/client/ui/VCalendarPanel.java b/src/com/vaadin/terminal/gwt/client/ui/VCalendarPanel.java index 9020360e8..f971a1704 100644 --- a/src/com/vaadin/terminal/gwt/client/ui/VCalendarPanel.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VCalendarPanel.java @@ -1,1689 +1,1691 @@ /* @ITMillApache2LicenseForJavaFiles@ */ package com.vaadin.terminal.gwt.client.ui; import java.util.Date; import java.util.List; import com.google.gwt.dom.client.Node; import com.google.gwt.event.dom.client.BlurEvent; import com.google.gwt.event.dom.client.BlurHandler; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.DomEvent; import com.google.gwt.event.dom.client.FocusEvent; import com.google.gwt.event.dom.client.FocusHandler; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyDownEvent; import com.google.gwt.event.dom.client.KeyDownHandler; import com.google.gwt.event.dom.client.KeyPressEvent; import com.google.gwt.event.dom.client.KeyPressHandler; import com.google.gwt.event.dom.client.MouseDownEvent; import com.google.gwt.event.dom.client.MouseDownHandler; import com.google.gwt.event.dom.client.MouseOutEvent; import com.google.gwt.event.dom.client.MouseOutHandler; import com.google.gwt.event.dom.client.MouseUpEvent; import com.google.gwt.event.dom.client.MouseUpHandler; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.DeferredCommand; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.FlexTable; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.InlineHTML; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.Widget; import com.vaadin.terminal.gwt.client.ApplicationConnection; import com.vaadin.terminal.gwt.client.BrowserInfo; import com.vaadin.terminal.gwt.client.DateTimeService; @SuppressWarnings("deprecation") public class VCalendarPanel extends FocusableFlexTable implements KeyDownHandler, KeyPressHandler, MouseOutHandler, MouseDownHandler, MouseUpHandler, BlurHandler, FocusHandler { public interface SubmitListener { /** * Called when calendar user triggers a submitting operation in calendar * panel. Eg. clicking on day or hitting enter. */ void onSubmit(); /** * On eg. ESC key. */ void onCancel(); } /** * Blur listener that listens to blur event from the panel */ public interface FocusOutListener { /** * @return true if the calendar panel is not used after focus moves out */ boolean onFocusOut(DomEvent event); } /** * Dispatches an event when the panel changes its _focused_ value. */ public interface ValueChangeListener { /** * * @return true if the calendar panel will not be used anymore */ void changed(Date date); } /** * Dispatches an event when the panel when time is changed */ public interface TimeChangeListener { void changed(int hour, int min, int sec, int msec); } /** * Represents a Date button in the calendar */ private class VEventButton extends Button { public VEventButton() { addMouseDownHandler(VCalendarPanel.this); addMouseOutHandler(VCalendarPanel.this); addMouseUpHandler(VCalendarPanel.this); } } private static final String CN_FOCUSED = "focused"; private static final String CN_TODAY = "today"; private static final String CN_SELECTED = "selected"; /** * Represents a click handler for when a user selects a value by using the * mouse */ private ClickHandler dayClickHandler = new ClickHandler() { /* * (non-Javadoc) * * @see * com.google.gwt.event.dom.client.ClickHandler#onClick(com.google.gwt * .event.dom.client.ClickEvent) */ public void onClick(ClickEvent event) { Day day = (Day) event.getSource(); focusDay(day.getDay()); selectFocused(); onSubmit(); } }; private VEventButton prevYear; private VEventButton nextYear; private VEventButton prevMonth; private VEventButton nextMonth; private VTime time; private FlexTable days = new FlexTable(); /* Needed to identify resolution changes */ private int oldResolution = 0; private int resolution = VDateField.RESOLUTION_YEAR; private int focusedRow; private int focusedColumn; private Timer mouseTimer; private Date value; private boolean enabled = true; private boolean readonly = false; private DateTimeService dateTimeService; private boolean showISOWeekNumbers; private Date focusedDate; private Day selectedDay; private Day focusedDay; private FocusOutListener focusOutListener; private SubmitListener submitListener; private ValueChangeListener valueChangeListener; private TimeChangeListener timeChangeListener; private boolean hasFocus = false; public VCalendarPanel() { setStyleName(VDateField.CLASSNAME + "-calendarpanel"); /* * Firefox auto-repeat works correctly only if we use a key press * handler, other browsers handle it correctly when using a key down * handler */ if (BrowserInfo.get().isGecko()) { addKeyPressHandler(this); } else { addKeyDownHandler(this); } addFocusHandler(this); addBlurHandler(this); } /** * Sets the focus to given day of current time. Used when moving in the * calender with the keyboard. * * @param day * The day number from by Date.getDate() */ private void focusDay(int day) { // Only used when calender body is present if (resolution > VDateField.RESOLUTION_MONTH) { if (focusedDay != null) focusedDay.removeStyleDependentName(CN_FOCUSED); if (day > 0 && focusedDate != null) { focusedDate.setDate(day); int rowCount = days.getRowCount(); for (int i = 0; i < rowCount; i++) { int cellCount = days.getCellCount(i); for (int j = 0; j < cellCount; j++) { Widget widget = days.getWidget(i, j); if (widget != null && widget instanceof Day) { Day curday = (Day) widget; if (curday.getDay() == day) { curday.addStyleDependentName(CN_FOCUSED); focusedDay = curday; focusedColumn = j; focusedRow = i; return; } } } } } } } /** * Sets the selection hightlight to a given date of current time * * @param day */ private void selectDate(int day) { value.setDate(day); if (selectedDay != null) selectedDay.removeStyleDependentName(CN_SELECTED); int rowCount = days.getRowCount(); for (int i = 0; i < rowCount; i++) { int cellCount = days.getCellCount(i); for (int j = 0; j < cellCount; j++) { Widget widget = days.getWidget(i, j); if (widget != null && widget instanceof Day) { Day curday = (Day) widget; if (curday.getDay() == day) { curday.addStyleDependentName(CN_SELECTED); selectedDay = curday; return; } } } } } /** * Updates year, month, day from focusedDate to value */ private void selectFocused() { if (focusedDate != null) { int changedFields = 0; if (value.getYear() != focusedDate.getYear()) { value.setYear(focusedDate.getYear()); changedFields += VDateField.RESOLUTION_YEAR; } if (value.getMonth() != focusedDate.getMonth()) { value.setMonth(focusedDate.getMonth()); changedFields += VDateField.RESOLUTION_MONTH; } if (value.getDate() != focusedDate.getDate()) { value.setDate(focusedDate.getDate()); changedFields += VDateField.RESOLUTION_DAY; } selectDate(focusedDate.getDate()); } else { ApplicationConnection.getConsole().log( "Trying to select a the focused date which is NULL!"); } } protected boolean onValueChange() { return false; } private int getResolution() { return resolution; } public void setResolution(int resolution) { if (resolution != this.resolution) { this.oldResolution = this.resolution; this.resolution = resolution; } } private boolean isReadonly() { return readonly; } private boolean isEnabled() { return enabled; } private void clearCalendarBody(boolean remove) { if (!remove) { // Leave the cells in place but clear their contents // This has the side effect of ensuring that the calendar always // contain 7 rows. for (int row = 1; row < 7; row++) { for (int col = 0; col < 8; col++) { days.setHTML(row, col, "&nbsp;"); } } } else if (getRowCount() > 1) { removeRow(1); days.clear(); } } /** * Builds the top buttons and current month and year header. * * @param forceRedraw * Forces the builder to recreate the instances of the buttons. * @param needsMonth * Should the month buttons be visible? */ private void buildCalendarHeader(boolean forceRedraw, boolean needsMonth) { if (forceRedraw) { if (prevMonth == null) { getFlexCellFormatter().setStyleName(0, 0, VDateField.CLASSNAME + "-calendarpanel-prevyear"); getFlexCellFormatter().setStyleName(0, 4, VDateField.CLASSNAME + "-calendarpanel-nextyear"); getFlexCellFormatter().setStyleName(0, 3, VDateField.CLASSNAME + "-calendarpanel-nextmonth"); getFlexCellFormatter().setStyleName(0, 1, VDateField.CLASSNAME + "-calendarpanel-prevmonth"); getRowFormatter().addStyleName(0, VDateField.CLASSNAME + "-calendarpanel-header"); prevYear = new VEventButton(); prevYear.setHTML("&laquo;"); prevYear.setStyleName("v-button-prevyear"); prevYear.setTabIndex(-1); nextYear = new VEventButton(); nextYear.setHTML("&raquo;"); nextYear.setStyleName("v-button-nextyear"); nextYear.setTabIndex(-1); setWidget(0, 0, prevYear); setWidget(0, 4, nextYear); if (needsMonth) { prevMonth = new VEventButton(); prevMonth.setHTML("&lsaquo;"); prevMonth.setStyleName("v-button-prevmonth"); prevMonth.setTabIndex(-1); nextMonth = new VEventButton(); nextMonth.setHTML("&rsaquo;"); nextMonth.setStyleName("v-button-nextmonth"); nextMonth.setTabIndex(-1); setWidget(0, 3, nextMonth); setWidget(0, 1, prevMonth); } } else if (!needsMonth) { // Remove month traverse buttons remove(prevMonth); remove(nextMonth); prevMonth = null; nextMonth = null; } } final String monthName = needsMonth ? getDateTimeService().getMonth( focusedDate.getMonth()) : ""; final int year = focusedDate.getYear() + 1900; getFlexCellFormatter().setStyleName(0, 2, VDateField.CLASSNAME + "-calendarpanel-month"); setHTML(0, 2, "<span class=\"" + VDateField.CLASSNAME + "-calendarpanel-month\">" + monthName + " " + year + "</span>"); } private DateTimeService getDateTimeService() { return dateTimeService; } public void setDateTimeService(DateTimeService dateTimeService) { this.dateTimeService = dateTimeService; } /** * Returns whether ISO 8601 week numbers should be shown in the value * selector or not. ISO 8601 defines that a week always starts with a Monday * so the week numbers are only shown if this is the case. * * @return true if week number should be shown, false otherwise */ public boolean isShowISOWeekNumbers() { return showISOWeekNumbers; } public void setShowISOWeekNumbers(boolean showISOWeekNumbers) { this.showISOWeekNumbers = showISOWeekNumbers; } /** * Builds the day and time selectors of the calendar. */ private void buildCalendarBody() { final int weekColumn = 0; final int firstWeekdayColumn = 1; final int headerRow = 0; setWidget(1, 0, days); setCellPadding(0); setCellSpacing(0); getFlexCellFormatter().setColSpan(1, 0, 5); getFlexCellFormatter().setStyleName(1, 0, VDateField.CLASSNAME + "-calendarpanel-body"); days.getFlexCellFormatter().setStyleName(headerRow, weekColumn, "v-week"); days.setHTML(headerRow, weekColumn, "<strong></strong>"); // Hide the week column if week numbers are not to be displayed. days.getFlexCellFormatter().setVisible(headerRow, weekColumn, isShowISOWeekNumbers()); days.getRowFormatter().setStyleName(headerRow, VDateField.CLASSNAME + "-calendarpanel-weekdays"); if (isShowISOWeekNumbers()) { days.getFlexCellFormatter().setStyleName(headerRow, weekColumn, "v-first"); days.getFlexCellFormatter().setStyleName(headerRow, firstWeekdayColumn, ""); days.getRowFormatter().addStyleName(headerRow, VDateField.CLASSNAME + "-calendarpanel-weeknumbers"); } else { days.getFlexCellFormatter().setStyleName(headerRow, weekColumn, ""); days.getFlexCellFormatter().setStyleName(headerRow, firstWeekdayColumn, "v-first"); } days.getFlexCellFormatter().setStyleName(headerRow, firstWeekdayColumn + 6, "v-last"); // Print weekday names final int firstDay = getDateTimeService().getFirstDayOfWeek(); for (int i = 0; i < 7; i++) { int day = i + firstDay; if (day > 6) { day = 0; } if (getResolution() > VDateField.RESOLUTION_MONTH) { days.setHTML(headerRow, firstWeekdayColumn + i, "<strong>" + getDateTimeService().getShortDay(day) + "</strong>"); } else { days.setHTML(headerRow, firstWeekdayColumn + i, ""); } } // The day of month that is selected, -1 if no day of this month is // selected (i.e, showing another month/year than selected or nothing is // selected) int dayOfMonthSelected = -1; // The day of month that is today, -1 if no day of this month is today // (i.e., showing another month/year than current) int dayOfMonthToday = -1; boolean initiallyNull = value == null; if (!initiallyNull && value.getMonth() == focusedDate.getMonth() && value.getYear() == focusedDate.getYear()) { dayOfMonthSelected = value.getDate(); } final Date today = new Date(); if (today.getMonth() == focusedDate.getMonth() && today.getYear() == focusedDate.getYear()) { dayOfMonthToday = today.getDate(); } final int startWeekDay = getDateTimeService().getStartWeekDay( focusedDate); final int daysInMonth = DateTimeService .getNumberOfDaysInMonth(focusedDate); int dayCount = 0; final Date curr = new Date(focusedDate.getTime()); // No month has more than 6 weeks so 6 is a safe maximum for rows. for (int weekOfMonth = 1; weekOfMonth < 7; weekOfMonth++) { boolean weekNumberProcessed[] = new boolean[] { false, false, false, false, false, false, false }; for (int dayOfWeek = 0; dayOfWeek < 7; dayOfWeek++) { if (!(weekOfMonth == 1 && dayOfWeek < startWeekDay)) { if (dayCount >= daysInMonth) { // All days printed and we are done break; } final int dayOfMonth = ++dayCount; curr.setDate(dayCount); // Actually write the day of month Day day = new Day(dayOfMonth); if (dayOfMonthSelected == dayOfMonth) { day.addStyleDependentName(CN_SELECTED); selectedDay = day; } if (dayOfMonthToday == dayOfMonth) { day.addStyleDependentName(CN_TODAY); } if (dayOfMonth == focusedDate.getDate()) { - day.addStyleDependentName(CN_FOCUSED); focusedDay = day; focusedRow = weekOfMonth; focusedColumn = firstWeekdayColumn + dayOfWeek; + if (hasFocus) { + day.addStyleDependentName(CN_FOCUSED); + } } days.setWidget(weekOfMonth, firstWeekdayColumn + dayOfWeek, day); // ISO week numbers if requested if (!weekNumberProcessed[weekOfMonth]) { days.getCellFormatter().setVisible(weekOfMonth, weekColumn, isShowISOWeekNumbers()); if (isShowISOWeekNumbers()) { final String baseCssClass = VDateField.CLASSNAME + "-calendarpanel-weeknumber"; String weekCssClass = baseCssClass; int weekNumber = DateTimeService .getISOWeekNumber(curr); days.setHTML(weekOfMonth, 0, "<span class=\"" + weekCssClass + "\"" + ">" + weekNumber + "</span>"); weekNumberProcessed[weekOfMonth] = true; } } } } } } /** * Do we need the time selector * * @return True if it is required */ private boolean isTimeSelectorNeeded() { return getResolution() > VDateField.RESOLUTION_DAY; } /** * Updates the calendar and text field with the selected dates. */ public void renderCalendar() { if (focusedDate == null) { focusedDate = new Date(); } if (getResolution() <= VDateField.RESOLUTION_MONTH && valueChangeListener != null) { valueChangeListener.changed(focusedDate); } Date start = new Date(); final boolean needsMonth = getResolution() > VDateField.RESOLUTION_YEAR; boolean needsBody = getResolution() >= VDateField.RESOLUTION_DAY; buildCalendarHeader(true, needsMonth); clearCalendarBody(!needsBody); if (needsBody) { buildCalendarBody(); } if (isTimeSelectorNeeded() && (time == null || this.resolution != this.oldResolution)) { time = new VTime(); setWidget(2, 0, time); getFlexCellFormatter().setColSpan(2, 0, 5); getFlexCellFormatter().setStyleName(2, 0, VDateField.CLASSNAME + "-calendarpanel-time"); this.oldResolution = this.resolution; } else if (isTimeSelectorNeeded()) { time.updateTimes(); } else if (time != null) { remove(time); } Date end = new Date(); ApplicationConnection.getConsole().error( "Rendering calendar panel for(ms) " + (end.getTime() - start.getTime())); } /** * Selects the next month */ private void focusNextMonth() { int currentMonth = focusedDate.getMonth(); focusedDate.setMonth(currentMonth + 1); int requestedMonth = (currentMonth + 1) % 12; /* * If the selected value was e.g. 31.3 the new value would be 31.4 but * this value is invalid so the new value will be 1.5. This is taken * care of by decreasing the value until we have the correct month. */ while (focusedDate.getMonth() != requestedMonth) { focusedDate.setDate(focusedDate.getDate() - 1); } renderCalendar(); } /** * Selects the previous month */ private void focusPreviousMonth() { int currentMonth = focusedDate.getMonth(); focusedDate.setMonth(currentMonth - 1); /* * If the selected value was e.g. 31.12 the new value would be 31.11 but * this value is invalid so the new value will be 1.12. This is taken * care of by decreasing the value until we have the correct month. */ while (focusedDate.getMonth() == currentMonth) { focusedDate.setDate(focusedDate.getDate() - 1); } renderCalendar(); } /** * Selects the previous year */ private void focusPreviousYear(int years) { focusedDate.setYear(focusedDate.getYear() - years); renderCalendar(); } /** * Selects the next year */ private void focusNextYear(int years) { focusedDate.setYear(focusedDate.getYear() + years); renderCalendar(); } /** * Handles a user click on the component * * @param sender * The component that was clicked * @param updateVariable * Should the value field be updated * */ private void processClickEvent(Widget sender) { if (!isEnabled() || isReadonly()) { return; } if (sender == prevYear) { focusPreviousYear(1); } else if (sender == nextYear) { focusNextYear(1); } else if (sender == prevMonth) { focusPreviousMonth(); } else if (sender == nextMonth) { focusNextMonth(); } } public interface CalendarEntrySource { public List getEntries(Date date, int resolution); } /* * (non-Javadoc) * * @see * com.google.gwt.event.dom.client.KeyDownHandler#onKeyDown(com.google.gwt * .event.dom.client.KeyDownEvent) */ public void onKeyDown(KeyDownEvent event) { handleKeyPress(event); } /* * (non-Javadoc) * * @see * com.google.gwt.event.dom.client.KeyPressHandler#onKeyPress(com.google * .gwt.event.dom.client.KeyPressEvent) */ public void onKeyPress(KeyPressEvent event) { handleKeyPress(event); } /** * Handles the keypress from both the onKeyPress event and the onKeyDown * event * * @param event * The keydown/keypress event */ private void handleKeyPress(DomEvent event) { if (time != null && time.getElement().isOrHasChild( (Node) event.getNativeEvent().getEventTarget().cast())) { int nativeKeyCode = event.getNativeEvent().getKeyCode(); if (nativeKeyCode == getSelectKey()) { ApplicationConnection.getConsole().log( "keydown on listselects" + event.getNativeEvent().getKeyCode()); onSubmit(); // submit happens if enter key hit down on listboxes event.preventDefault(); event.stopPropagation(); } return; } // Check tabs int keycode = event.getNativeEvent().getKeyCode(); if (keycode == KeyCodes.KEY_TAB && event.getNativeEvent().getShiftKey()) { if (onTabOut(event)) { return; } } // Handle the navigation if (handleNavigation(keycode, event.getNativeEvent().getCtrlKey() || event.getNativeEvent().getMetaKey(), event.getNativeEvent() .getShiftKey())) { event.preventDefault(); } } /** * Notifies submit-listeners of a submit event */ private void onSubmit() { if (getSubmitListener() != null) { getSubmitListener().onSubmit(); } } /** * Notifies submit-listeners of a cancel event */ private void onCancel() { if (getSubmitListener() != null) { getSubmitListener().onCancel(); } } /** * Handles the keyboard navigation when the resolution is set to years. * * @param keycode * The keycode to process * @param ctrl * Is ctrl pressed? * @param shift * is shift pressed * @return Returns true if the keycode was processed, else false */ protected boolean handleNavigationYearMode(int keycode, boolean ctrl, boolean shift) { // Ctrl and Shift selection not supported if (ctrl || shift) { return false; } else if (keycode == getPreviousKey()) { focusNextYear(10); // Add 10 years return true; } else if (keycode == getForwardKey()) { focusNextYear(1); // Add 1 year return true; } else if (keycode == getNextKey()) { focusPreviousYear(10); // Subtract 10 years return true; } else if (keycode == getBackwardKey()) { focusPreviousYear(1); // Subtract 1 year return true; } else if (keycode == getSelectKey()) { value = (Date) focusedDate.clone(); onSubmit(); return true; } else if (keycode == getResetKey()) { // Restore showing value the selected value focusedDate.setTime(value.getTime()); renderCalendar(); return true; } else if (keycode == getCloseKey()) { // TODO fire listener, on users responsibility?? return true; } return false; } /** * Handle the keyboard navigation when the resolution is set to MONTH * * @param keycode * The keycode to handle * @param ctrl * Was the ctrl key pressed? * @param shift * Was the shift key pressed? * @return */ protected boolean handleNavigationMonthMode(int keycode, boolean ctrl, boolean shift) { // Ctrl selection not supported if (ctrl) { return false; } else if (keycode == getPreviousKey()) { focusNextYear(1); // Add 1 year return true; } else if (keycode == getForwardKey()) { focusNextMonth(); // Add 1 month return true; } else if (keycode == getNextKey()) { focusPreviousYear(1); // Subtract 1 year return true; } else if (keycode == getBackwardKey()) { focusPreviousMonth(); // Subtract 1 month return true; } else if (keycode == getSelectKey()) { value = (Date) focusedDate.clone(); onSubmit(); return true; } else if (keycode == getResetKey()) { // Restore showing value the selected value focusedDate.setTime(value.getTime()); renderCalendar(); return true; } else if (keycode == getCloseKey() || keycode == KeyCodes.KEY_TAB) { // TODO fire close event return true; } return false; } /** * Handle keyboard navigation what the resolution is set to DAY * * @param keycode * The keycode to handle * @param ctrl * Was the ctrl key pressed? * @param shift * Was the shift key pressed? * @return Return true if the key press was handled by the method, else * return false. */ protected boolean handleNavigationDayMode(int keycode, boolean ctrl, boolean shift) { // Ctrl key is not in use if (ctrl) { return false; } /* * Jumps to the next day. */ if (keycode == getForwardKey() && !shift) { // Calculate new showing value Date newCurrentDate = (Date) focusedDate.clone(); newCurrentDate.setDate(newCurrentDate.getDate() + 1); if (newCurrentDate.getMonth() == focusedDate.getMonth()) { // Month did not change, only move the selection focusDay(focusedDate.getDate() + 1); } else { // If the month changed we need to re-render the calendar focusedDate.setDate(focusedDate.getDate() + 1); renderCalendar(); } return true; /* * Jumps to the previous day */ } else if (keycode == getBackwardKey() && !shift) { // Calculate new showing value Date newCurrentDate = (Date) focusedDate.clone(); newCurrentDate.setDate(newCurrentDate.getDate() - 1); if (newCurrentDate.getMonth() == focusedDate.getMonth()) { // Month did not change, only move the selection focusDay(focusedDate.getDate() - 1); } else { // If the month changed we need to re-render the calendar focusedDate.setDate(focusedDate.getDate() - 1); renderCalendar(); } return true; /* * Jumps one week back in the calendar */ } else if (keycode == getPreviousKey() && !shift) { // Calculate new showing value Date newCurrentDate = (Date) focusedDate.clone(); newCurrentDate.setDate(newCurrentDate.getDate() - 7); if (newCurrentDate.getMonth() == focusedDate.getMonth() && focusedRow > 1) { // Month did not change, only move the selection focusDay(focusedDate.getDate() - 7); } else { // If the month changed we need to re-render the calendar focusedDate.setDate(focusedDate.getDate() - 7); renderCalendar(); } return true; /* * Jumps one week forward in the calendar */ } else if (keycode == getNextKey() && !ctrl && !shift) { // Calculate new showing value Date newCurrentDate = (Date) focusedDate.clone(); newCurrentDate.setDate(newCurrentDate.getDate() + 7); if (newCurrentDate.getMonth() == focusedDate.getMonth()) { // Month did not change, only move the selection focusDay(focusedDate.getDate() + 7); } else { // If the month changed we need to re-render the calendar focusedDate.setDate(focusedDate.getDate() + 7); renderCalendar(); } return true; /* * Selects the value that is chosen */ } else if (keycode == getSelectKey() && !shift) { selectFocused(); onSubmit(); // submit return true; } else if (keycode == getCloseKey()) { onCancel(); // TODO close event return true; /* * Jumps to the next month */ } else if (shift && keycode == getForwardKey()) { focusNextMonth(); return true; /* * Jumps to the previous month */ } else if (shift && keycode == getBackwardKey()) { focusPreviousMonth(); return true; /* * Jumps to the next year */ } else if (shift && keycode == getPreviousKey()) { focusNextYear(1); return true; /* * Jumps to the previous year */ } else if (shift && keycode == getNextKey()) { focusPreviousYear(1); return true; /* * Resets the selection */ } else if (keycode == getResetKey() && !shift) { // Restore showing value the selected value focusedDate.setTime(value.getTime()); renderCalendar(); return true; } return false; } /** * Handles the keyboard navigation * * @param keycode * The key code that was pressed * @param ctrl * Was the ctrl key pressed * @param shift * Was the shift key pressed * @return Return true if key press was handled by the component, else * return false */ protected boolean handleNavigation(int keycode, boolean ctrl, boolean shift) { if (!isEnabled() || isReadonly()) { return false; } else if (resolution == VDateField.RESOLUTION_YEAR) { return handleNavigationYearMode(keycode, ctrl, shift); } else if (resolution == VDateField.RESOLUTION_MONTH) { return handleNavigationMonthMode(keycode, ctrl, shift); } else if (resolution == VDateField.RESOLUTION_DAY) { return handleNavigationDayMode(keycode, ctrl, shift); } else { return handleNavigationDayMode(keycode, ctrl, shift); } } /** * Returns the reset key which will reset the calendar to the previous * selection. By default this is backspace but it can be overriden to change * the key to whatever you want. * * @return */ protected int getResetKey() { return KeyCodes.KEY_BACKSPACE; } /** * Returns the select key which selects the value. By default this is the * enter key but it can be changed to whatever you like by overriding this * method. * * @return */ protected int getSelectKey() { return KeyCodes.KEY_ENTER; } /** * Returns the key that closes the popup window if this is a VPopopCalendar. * Else this does nothing. By default this is the Escape key but you can * change the key to whatever you want by overriding this method. * * @return */ protected int getCloseKey() { return KeyCodes.KEY_ESCAPE; } /** * The key that selects the next day in the calendar. By default this is the * right arrow key but by overriding this method it can be changed to * whatever you like. * * @return */ protected int getForwardKey() { return KeyCodes.KEY_RIGHT; } /** * The key that selects the previous day in the calendar. By default this is * the left arrow key but by overriding this method it can be changed to * whatever you like. * * @return */ protected int getBackwardKey() { return KeyCodes.KEY_LEFT; } /** * The key that selects the next week in the calendar. By default this is * the down arrow key but by overriding this method it can be changed to * whatever you like. * * @return */ protected int getNextKey() { return KeyCodes.KEY_DOWN; } /** * The key that selects the previous week in the calendar. By default this * is the up arrow key but by overriding this method it can be changed to * whatever you like. * * @return */ protected int getPreviousKey() { return KeyCodes.KEY_UP; } /* * (non-Javadoc) * * @see * com.google.gwt.event.dom.client.MouseOutHandler#onMouseOut(com.google * .gwt.event.dom.client.MouseOutEvent) */ public void onMouseOut(MouseOutEvent event) { if (mouseTimer != null) { mouseTimer.cancel(); } } /* * (non-Javadoc) * * @see * com.google.gwt.event.dom.client.MouseDownHandler#onMouseDown(com.google * .gwt.event.dom.client.MouseDownEvent) */ public void onMouseDown(MouseDownEvent event) { // Allow user to click-n-hold for fast-forward or fast-rewind. // Timer is first used for a 500ms delay after mousedown. After that has // elapsed, another timer is triggered to go off every 150ms. Both // timers are cancelled on mouseup or mouseout. if (event.getSource() instanceof VEventButton) { final Widget sender = (Widget) event.getSource(); processClickEvent(sender); mouseTimer = new Timer() { @Override public void run() { mouseTimer = new Timer() { @Override public void run() { processClickEvent(sender); } }; mouseTimer.scheduleRepeating(150); } }; mouseTimer.schedule(500); } } /* * (non-Javadoc) * * @see * com.google.gwt.event.dom.client.MouseUpHandler#onMouseUp(com.google.gwt * .event.dom.client.MouseUpEvent) */ public void onMouseUp(MouseUpEvent event) { if (mouseTimer != null) { mouseTimer.cancel(); } } /** * Sets the data of the Panel. * * @param currentDate * The date to set */ public void setDate(Date currentDate) { // Check that we are not re-rendering a already active date if if (currentDate == value && currentDate != null) { return; } Date oldValue = value; value = currentDate; if (focusedDate == null && value != null) { focusedDate = (Date) value.clone(); } // Re-render calendar if the month or year has changed if (oldValue == null || value == null || oldValue.getYear() != value.getYear() || oldValue.getMonth() != value.getMonth()) { renderCalendar(); } else { focusDay(currentDate.getDate()); selectFocused(); } if (!hasFocus) focusDay(-1); } /** * TimeSelector is a widget consisting of list boxes that modifie the Date * object that is given for. * */ public class VTime extends FlowPanel implements ChangeHandler { private ListBox hours; private ListBox mins; private ListBox sec; private ListBox msec; private ListBox ampm; private ListBox lastField; /** * Constructor */ public VTime() { super(); setStyleName(VDateField.CLASSNAME + "-time"); buildTime(); } private ListBox createListBox() { ListBox lb = new ListBox(); lb.setStyleName(VNativeSelect.CLASSNAME); lb.addChangeHandler(this); lb.addBlurHandler(VCalendarPanel.this); lb.addFocusHandler(VCalendarPanel.this); return lb; } /** * Constructs the ListBoxes and updates their value * * @param redraw * Should new instances of the listboxes be created */ private void buildTime() { clear(); hours = createListBox(); if (getDateTimeService().isTwelveHourClock()) { hours.addItem("12"); for (int i = 1; i < 12; i++) { hours.addItem((i < 10) ? "0" + i : "" + i); } } else { for (int i = 0; i < 24; i++) { hours.addItem((i < 10) ? "0" + i : "" + i); } } hours.addChangeHandler(this); if (getDateTimeService().isTwelveHourClock()) { ampm = createListBox(); final String[] ampmText = getDateTimeService().getAmPmStrings(); ampm.addItem(ampmText[0]); ampm.addItem(ampmText[1]); ampm.addChangeHandler(this); } if (getResolution() >= VDateField.RESOLUTION_MIN) { mins = createListBox(); for (int i = 0; i < 60; i++) { mins.addItem((i < 10) ? "0" + i : "" + i); } mins.addChangeHandler(this); } if (getResolution() >= VDateField.RESOLUTION_SEC) { sec = createListBox(); for (int i = 0; i < 60; i++) { sec.addItem((i < 10) ? "0" + i : "" + i); } sec.addChangeHandler(this); } if (getResolution() == VDateField.RESOLUTION_MSEC) { msec = createListBox(); for (int i = 0; i < 1000; i++) { if (i < 10) { msec.addItem("00" + i); } else if (i < 100) { msec.addItem("0" + i); } else { msec.addItem("" + i); } } msec.addChangeHandler(this); } final String delimiter = getDateTimeService().getClockDelimeter(); if (isReadonly()) { int h = 0; if (value != null) { h = value.getHours(); } if (getDateTimeService().isTwelveHourClock()) { h -= h < 12 ? 0 : 12; } add(new VLabel(h < 10 ? "0" + h : "" + h)); } else { add(hours); lastField = hours; } if (getResolution() >= VDateField.RESOLUTION_MIN) { add(new VLabel(delimiter)); if (isReadonly()) { final int m = mins.getSelectedIndex(); add(new VLabel(m < 10 ? "0" + m : "" + m)); } else { add(mins); lastField = mins; } } if (getResolution() >= VDateField.RESOLUTION_SEC) { add(new VLabel(delimiter)); if (isReadonly()) { final int s = sec.getSelectedIndex(); add(new VLabel(s < 10 ? "0" + s : "" + s)); } else { add(sec); lastField = sec; } } if (getResolution() == VDateField.RESOLUTION_MSEC) { add(new VLabel(".")); if (isReadonly()) { final int m = getMilliseconds(); final String ms = m < 100 ? "0" + m : "" + m; add(new VLabel(m < 10 ? "0" + ms : ms)); } else { add(msec); lastField = msec; } } if (getResolution() == VDateField.RESOLUTION_HOUR) { add(new VLabel(delimiter + "00")); // o'clock } if (getDateTimeService().isTwelveHourClock()) { add(new VLabel("&nbsp;")); if (isReadonly()) { int i = 0; if (value != null) { i = (value.getHours() < 12) ? 0 : 1; } add(new VLabel(ampm.getItemText(i))); } else { add(ampm); lastField = ampm; } } if (isReadonly()) { return; } // Update times updateTimes(); ListBox lastDropDown = (ListBox) getWidget(getWidgetCount() - 1); lastDropDown.addKeyDownHandler(new KeyDownHandler() { public void onKeyDown(KeyDownEvent event) { boolean shiftKey = event.getNativeEvent().getShiftKey(); if (shiftKey) { return; } else { int nativeKeyCode = event.getNativeKeyCode(); if (nativeKeyCode == KeyCodes.KEY_TAB) { onTabOut(event); } } } }); } /** * Updates the valus to correspond to the values in value */ public void updateTimes() { boolean selected = true; if (value == null) { value = new Date(); selected = false; } if (getDateTimeService().isTwelveHourClock()) { int h = value.getHours(); ampm.setSelectedIndex(h < 12 ? 0 : 1); h -= ampm.getSelectedIndex() * 12; hours.setSelectedIndex(h); } else { hours.setSelectedIndex(value.getHours()); } if (getResolution() >= VDateField.RESOLUTION_MIN) { mins.setSelectedIndex(value.getMinutes()); } if (getResolution() >= VDateField.RESOLUTION_SEC) { sec.setSelectedIndex(value.getSeconds()); } if (getResolution() == VDateField.RESOLUTION_MSEC) { if (selected) { msec.setSelectedIndex(getMilliseconds()); } else { msec.setSelectedIndex(0); } } if (getDateTimeService().isTwelveHourClock()) { ampm.setSelectedIndex(value.getHours() < 12 ? 0 : 1); } hours.setEnabled(isEnabled()); if (mins != null) { mins.setEnabled(isEnabled()); } if (sec != null) { sec.setEnabled(isEnabled()); } if (msec != null) { msec.setEnabled(isEnabled()); } if (ampm != null) { ampm.setEnabled(isEnabled()); } } private int getMilliseconds() { return DateTimeService.getMilliseconds(value); } private DateTimeService getDateTimeService() { if (dateTimeService == null) { dateTimeService = new DateTimeService(); } return dateTimeService; } /* * (non-Javadoc) VT * * @see * com.google.gwt.event.dom.client.ChangeHandler#onChange(com.google.gwt * .event.dom.client.ChangeEvent) */ public void onChange(ChangeEvent event) { /* * Value from dropdowns gets always set for the value. Like year and * month when resolution is month or year. */ if (event.getSource() == hours) { int h = hours.getSelectedIndex(); if (getDateTimeService().isTwelveHourClock()) { h = h + ampm.getSelectedIndex() * 12; } value.setHours(h); if (timeChangeListener != null) { timeChangeListener.changed(h, value.getMinutes(), value .getSeconds(), DateTimeService .getMilliseconds(value)); } event.preventDefault(); event.stopPropagation(); } else if (event.getSource() == mins) { final int m = mins.getSelectedIndex(); value.setMinutes(m); if (timeChangeListener != null) { timeChangeListener.changed(value.getHours(), m, value .getSeconds(), DateTimeService .getMilliseconds(value)); } event.preventDefault(); event.stopPropagation(); } else if (event.getSource() == sec) { final int s = sec.getSelectedIndex(); value.setSeconds(s); if (timeChangeListener != null) { timeChangeListener.changed(value.getHours(), value .getMinutes(), s, DateTimeService .getMilliseconds(value)); } event.preventDefault(); event.stopPropagation(); } else if (event.getSource() == msec) { final int ms = msec.getSelectedIndex(); DateTimeService.setMilliseconds(value, ms); if (timeChangeListener != null) { timeChangeListener.changed(value.getHours(), value .getMinutes(), value.getSeconds(), ms); } event.preventDefault(); event.stopPropagation(); } else if (event.getSource() == ampm) { final int h = hours.getSelectedIndex() + (ampm.getSelectedIndex() * 12); value.setHours(h); if (timeChangeListener != null) { timeChangeListener.changed(h, value.getMinutes(), value .getSeconds(), DateTimeService .getMilliseconds(value)); } event.preventDefault(); event.stopPropagation(); } } } private class Day extends InlineHTML { private static final String BASECLASS = VDateField.CLASSNAME + "-calendarpanel-day"; private final int day; Day(int dayOfMonth) { super("" + dayOfMonth); setStyleName(BASECLASS); day = dayOfMonth; addClickHandler(dayClickHandler); } public int getDay() { return day; } } public Date getDate() { return value; } /** * If true should be returned if the panel will not be used after this * event. * * @param event * @return */ protected boolean onTabOut(DomEvent event) { if (focusOutListener != null) { return focusOutListener.onFocusOut(event); } return false; } /** * A focus out listener is triggered when the panel loosed focus. This can * happen either after a user clicks outside the panel or tabs out. * * @param listener * The listener to trigger */ public void setFocusOutListener(FocusOutListener listener) { focusOutListener = listener; } /** * The submit listener is called when the user selects a value from the * calender either by clicking the day or selects it by keyboard. * * @param submitListener * The listener to trigger */ public void setSubmitListener(SubmitListener submitListener) { this.submitListener = submitListener; } /** * The value change listener is triggered when the focused date changes by * user either clicking on a new date or by using the keyboard. * * @param listener * The listener to trigger */ public void setValueChangeListener(ValueChangeListener listener) { this.valueChangeListener = listener; } /** * The time change listener is triggered when the user changes the time. * * @param listener */ public void setTimeChangeListener(TimeChangeListener listener) { this.timeChangeListener = listener; } /** * Returns the submit listener that listens to selection made from the panel * * @return The listener or NULL if no listener has been set */ public SubmitListener getSubmitListener() { return submitListener; } /* * (non-Javadoc) * * @see * com.google.gwt.event.dom.client.BlurHandler#onBlur(com.google.gwt.event * .dom.client.BlurEvent) */ public void onBlur(final BlurEvent event) { if (isAttached()) { DeferredCommand.addCommand(new Command() { public void execute() { if (!hasFocus) { onTabOut(event); } } }); } if (event.getSource() instanceof VCalendarPanel) { hasFocus = false; focusDay(-1); } } /* * (non-Javadoc) * * @see * com.google.gwt.event.dom.client.FocusHandler#onFocus(com.google.gwt.event * .dom.client.FocusEvent) */ public void onFocus(FocusEvent event) { if (event.getSource() instanceof VCalendarPanel) { hasFocus = true; // Focuses the current day if the calendar shows the days focusDay(focusedDay.getDay()); } } }
false
true
private void buildCalendarBody() { final int weekColumn = 0; final int firstWeekdayColumn = 1; final int headerRow = 0; setWidget(1, 0, days); setCellPadding(0); setCellSpacing(0); getFlexCellFormatter().setColSpan(1, 0, 5); getFlexCellFormatter().setStyleName(1, 0, VDateField.CLASSNAME + "-calendarpanel-body"); days.getFlexCellFormatter().setStyleName(headerRow, weekColumn, "v-week"); days.setHTML(headerRow, weekColumn, "<strong></strong>"); // Hide the week column if week numbers are not to be displayed. days.getFlexCellFormatter().setVisible(headerRow, weekColumn, isShowISOWeekNumbers()); days.getRowFormatter().setStyleName(headerRow, VDateField.CLASSNAME + "-calendarpanel-weekdays"); if (isShowISOWeekNumbers()) { days.getFlexCellFormatter().setStyleName(headerRow, weekColumn, "v-first"); days.getFlexCellFormatter().setStyleName(headerRow, firstWeekdayColumn, ""); days.getRowFormatter().addStyleName(headerRow, VDateField.CLASSNAME + "-calendarpanel-weeknumbers"); } else { days.getFlexCellFormatter().setStyleName(headerRow, weekColumn, ""); days.getFlexCellFormatter().setStyleName(headerRow, firstWeekdayColumn, "v-first"); } days.getFlexCellFormatter().setStyleName(headerRow, firstWeekdayColumn + 6, "v-last"); // Print weekday names final int firstDay = getDateTimeService().getFirstDayOfWeek(); for (int i = 0; i < 7; i++) { int day = i + firstDay; if (day > 6) { day = 0; } if (getResolution() > VDateField.RESOLUTION_MONTH) { days.setHTML(headerRow, firstWeekdayColumn + i, "<strong>" + getDateTimeService().getShortDay(day) + "</strong>"); } else { days.setHTML(headerRow, firstWeekdayColumn + i, ""); } } // The day of month that is selected, -1 if no day of this month is // selected (i.e, showing another month/year than selected or nothing is // selected) int dayOfMonthSelected = -1; // The day of month that is today, -1 if no day of this month is today // (i.e., showing another month/year than current) int dayOfMonthToday = -1; boolean initiallyNull = value == null; if (!initiallyNull && value.getMonth() == focusedDate.getMonth() && value.getYear() == focusedDate.getYear()) { dayOfMonthSelected = value.getDate(); } final Date today = new Date(); if (today.getMonth() == focusedDate.getMonth() && today.getYear() == focusedDate.getYear()) { dayOfMonthToday = today.getDate(); } final int startWeekDay = getDateTimeService().getStartWeekDay( focusedDate); final int daysInMonth = DateTimeService .getNumberOfDaysInMonth(focusedDate); int dayCount = 0; final Date curr = new Date(focusedDate.getTime()); // No month has more than 6 weeks so 6 is a safe maximum for rows. for (int weekOfMonth = 1; weekOfMonth < 7; weekOfMonth++) { boolean weekNumberProcessed[] = new boolean[] { false, false, false, false, false, false, false }; for (int dayOfWeek = 0; dayOfWeek < 7; dayOfWeek++) { if (!(weekOfMonth == 1 && dayOfWeek < startWeekDay)) { if (dayCount >= daysInMonth) { // All days printed and we are done break; } final int dayOfMonth = ++dayCount; curr.setDate(dayCount); // Actually write the day of month Day day = new Day(dayOfMonth); if (dayOfMonthSelected == dayOfMonth) { day.addStyleDependentName(CN_SELECTED); selectedDay = day; } if (dayOfMonthToday == dayOfMonth) { day.addStyleDependentName(CN_TODAY); } if (dayOfMonth == focusedDate.getDate()) { day.addStyleDependentName(CN_FOCUSED); focusedDay = day; focusedRow = weekOfMonth; focusedColumn = firstWeekdayColumn + dayOfWeek; } days.setWidget(weekOfMonth, firstWeekdayColumn + dayOfWeek, day); // ISO week numbers if requested if (!weekNumberProcessed[weekOfMonth]) { days.getCellFormatter().setVisible(weekOfMonth, weekColumn, isShowISOWeekNumbers()); if (isShowISOWeekNumbers()) { final String baseCssClass = VDateField.CLASSNAME + "-calendarpanel-weeknumber"; String weekCssClass = baseCssClass; int weekNumber = DateTimeService .getISOWeekNumber(curr); days.setHTML(weekOfMonth, 0, "<span class=\"" + weekCssClass + "\"" + ">" + weekNumber + "</span>"); weekNumberProcessed[weekOfMonth] = true; } } } } } }
private void buildCalendarBody() { final int weekColumn = 0; final int firstWeekdayColumn = 1; final int headerRow = 0; setWidget(1, 0, days); setCellPadding(0); setCellSpacing(0); getFlexCellFormatter().setColSpan(1, 0, 5); getFlexCellFormatter().setStyleName(1, 0, VDateField.CLASSNAME + "-calendarpanel-body"); days.getFlexCellFormatter().setStyleName(headerRow, weekColumn, "v-week"); days.setHTML(headerRow, weekColumn, "<strong></strong>"); // Hide the week column if week numbers are not to be displayed. days.getFlexCellFormatter().setVisible(headerRow, weekColumn, isShowISOWeekNumbers()); days.getRowFormatter().setStyleName(headerRow, VDateField.CLASSNAME + "-calendarpanel-weekdays"); if (isShowISOWeekNumbers()) { days.getFlexCellFormatter().setStyleName(headerRow, weekColumn, "v-first"); days.getFlexCellFormatter().setStyleName(headerRow, firstWeekdayColumn, ""); days.getRowFormatter().addStyleName(headerRow, VDateField.CLASSNAME + "-calendarpanel-weeknumbers"); } else { days.getFlexCellFormatter().setStyleName(headerRow, weekColumn, ""); days.getFlexCellFormatter().setStyleName(headerRow, firstWeekdayColumn, "v-first"); } days.getFlexCellFormatter().setStyleName(headerRow, firstWeekdayColumn + 6, "v-last"); // Print weekday names final int firstDay = getDateTimeService().getFirstDayOfWeek(); for (int i = 0; i < 7; i++) { int day = i + firstDay; if (day > 6) { day = 0; } if (getResolution() > VDateField.RESOLUTION_MONTH) { days.setHTML(headerRow, firstWeekdayColumn + i, "<strong>" + getDateTimeService().getShortDay(day) + "</strong>"); } else { days.setHTML(headerRow, firstWeekdayColumn + i, ""); } } // The day of month that is selected, -1 if no day of this month is // selected (i.e, showing another month/year than selected or nothing is // selected) int dayOfMonthSelected = -1; // The day of month that is today, -1 if no day of this month is today // (i.e., showing another month/year than current) int dayOfMonthToday = -1; boolean initiallyNull = value == null; if (!initiallyNull && value.getMonth() == focusedDate.getMonth() && value.getYear() == focusedDate.getYear()) { dayOfMonthSelected = value.getDate(); } final Date today = new Date(); if (today.getMonth() == focusedDate.getMonth() && today.getYear() == focusedDate.getYear()) { dayOfMonthToday = today.getDate(); } final int startWeekDay = getDateTimeService().getStartWeekDay( focusedDate); final int daysInMonth = DateTimeService .getNumberOfDaysInMonth(focusedDate); int dayCount = 0; final Date curr = new Date(focusedDate.getTime()); // No month has more than 6 weeks so 6 is a safe maximum for rows. for (int weekOfMonth = 1; weekOfMonth < 7; weekOfMonth++) { boolean weekNumberProcessed[] = new boolean[] { false, false, false, false, false, false, false }; for (int dayOfWeek = 0; dayOfWeek < 7; dayOfWeek++) { if (!(weekOfMonth == 1 && dayOfWeek < startWeekDay)) { if (dayCount >= daysInMonth) { // All days printed and we are done break; } final int dayOfMonth = ++dayCount; curr.setDate(dayCount); // Actually write the day of month Day day = new Day(dayOfMonth); if (dayOfMonthSelected == dayOfMonth) { day.addStyleDependentName(CN_SELECTED); selectedDay = day; } if (dayOfMonthToday == dayOfMonth) { day.addStyleDependentName(CN_TODAY); } if (dayOfMonth == focusedDate.getDate()) { focusedDay = day; focusedRow = weekOfMonth; focusedColumn = firstWeekdayColumn + dayOfWeek; if (hasFocus) { day.addStyleDependentName(CN_FOCUSED); } } days.setWidget(weekOfMonth, firstWeekdayColumn + dayOfWeek, day); // ISO week numbers if requested if (!weekNumberProcessed[weekOfMonth]) { days.getCellFormatter().setVisible(weekOfMonth, weekColumn, isShowISOWeekNumbers()); if (isShowISOWeekNumbers()) { final String baseCssClass = VDateField.CLASSNAME + "-calendarpanel-weeknumber"; String weekCssClass = baseCssClass; int weekNumber = DateTimeService .getISOWeekNumber(curr); days.setHTML(weekOfMonth, 0, "<span class=\"" + weekCssClass + "\"" + ">" + weekNumber + "</span>"); weekNumberProcessed[weekOfMonth] = true; } } } } } }
diff --git a/src/main/java/ar/com/cuyum/cnc/service/TransformationService.java b/src/main/java/ar/com/cuyum/cnc/service/TransformationService.java index 8ad951e..a91cbc0 100644 --- a/src/main/java/ar/com/cuyum/cnc/service/TransformationService.java +++ b/src/main/java/ar/com/cuyum/cnc/service/TransformationService.java @@ -1,201 +1,201 @@ /** * */ package ar.com.cuyum.cnc.service; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringWriter; import java.net.URL; import javax.ejb.Stateless; import javax.faces.context.FacesContext; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.InputStreamBody; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; /** * @author Jorge Morando * */ @Stateless public class TransformationService { public transient Logger log = Logger.getLogger(TransformationService.class); // private static String XSL_FORM = "form.xsl"; private static String XSL_FORM = "formCnc.xsl"; private static String XSL_DATA = "data.xsl"; private static String XSL_HTML = "jrxfhtml.xsl"; private HttpClient client = new DefaultHttpClient(); private boolean remoteTransformation = false; private URL remoteTransformationServiceUrl = null; /*================ POINT OF ENTRANCE =================*/ public String transform(InputStream xmlStream){ String transformedXml = null; if(remoteTransformation){ transformedXml = requestTransformation(xmlStream); }else{ transformedXml = performTransformation(xmlStream); } return transformedXml; } /*=============TRANSFORMATION ALTERNATIVES============*/ private String performTransformation(InputStream xmlStream){ log.debug("Transformando el xml localmente"); String result = "<html><body>Error.</body></html>"; try { result = transformHtml(xmlStream); } catch (Exception e) { log.error("Error transformando localmente el xml",e); } return result; } private String requestTransformation(InputStream xmlStream){ HttpPost request = buildRequest(xmlStream); HttpResponse rawResponse = execute(request); String transformedXml = processResponse(rawResponse); return transformedXml; } /*=================VIA SAXON SERVICE===================*/ private String transformHtml(InputStream xmlStream) throws Exception { // Create a transform factory instance. TransformerFactory tfactory = TransformerFactory.newInstance(); StringWriter resultForm = new StringWriter(); // StringWriter resultData = new StringWriter(); // Create a transformer for the stylesheet. - Transformer transformerForm = tfactory.newTransformer(new StreamSource(new InputStreamReader(loadXsl(XSL_FORM),"UTF-8"))); + Transformer transformerForm = tfactory.newTransformer(new StreamSource(new InputStreamReader(loadXsl(XSL_FORM),"UTF8"))); // Create a transformer for the stylesheet. // Transformer transformerData = tfactory.newTransformer(new StreamSource(new InputStreamReader(loadXsl(XSL_DATA),"UTF-8"))); // get the xml bytes byte[] xmlBytes = IOUtils.toByteArray(xmlStream); // InputStream xmlStreamData = new ByteArrayInputStream(xmlBytes); InputStream xmlStreamForm = new ByteArrayInputStream(xmlBytes); // Transform the source XML to System.out. // transformerData.transform(new StreamSource(new InputStreamReader(xmlStreamData),"UTF-8"), new StreamResult(resultData)); - transformerForm.transform(new StreamSource(new InputStreamReader(xmlStreamForm),"UTF-8"), new StreamResult(resultForm)); + transformerForm.transform(new StreamSource(new InputStreamReader(xmlStreamForm),"UTF8"), new StreamResult(resultForm)); // return "<root>"+resultData.toString()+resultForm.toString()+"</root>"; return resultForm.toString(); } private InputStream loadXsl(String xsl){ InputStream xslIS = FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream("/WEB-INF/xsl/"+xsl); return xslIS; } /*=============== VIA HTTP REQUEST======================*/ private final HttpPost buildRequest(InputStream xmlFile) { HttpPost method = null; try { method = new HttpPost("http://joaco.cuyum.com:9999/formRenderServices/transform.php"); MultipartEntity entity = new MultipartEntity(); entity.addPart("xmlFile", new InputStreamBody(xmlFile, "text/xml")); method.setEntity(entity); } catch (Exception e) { log.error(e); } return method; } private HttpResponse execute(HttpRequestBase method) { HttpResponse resp = null; try { log.info("Ejecutando: " + method); resp = client.execute(method); } catch (Exception e) { log.error(e.getMessage()); } return resp; } private final String processResponse(HttpResponse rawResponse) { String entity = "<root></root>"; try { entity = EntityUtils.toString(rawResponse.getEntity()); } catch (Exception e) { log.error(e); } return entity; } /*================= SERVICE CONFIGURATION===============*/ /** * By default the transformation is made locally but it can be made via remote <br /> * transformation service by providing url to a service that consumes an xml and produces an xml. * @return */ public boolean isRemoteTransformation() { return remoteTransformation; } /** * By default the transformation is made locally but it can be made via remote <br /> * transformation service by providing url to a service that consumes an xml and produces an xml. * @return */ public void setRemoteTransformation(boolean remoteTransformation) { this.remoteTransformation = remoteTransformation; } /** * By default the transformation is made locally but it can be made via remote <br /> * transformation service by providing url to a service that consumes an xml and produces an xml. * @return the URL for the remote service */ public URL getRemoteTransformationServiceUrl() { return remoteTransformationServiceUrl; } /** * By default the transformation is made locally but it can be made via remote <br /> * transformation service by providing url to a service that consumes an xml and produces an xml. * @return */ public void setRemoteTransformationServiceUrl(URL remoteTransformationServiceUrl) { if(remoteTransformationServiceUrl != null){ this.setRemoteTransformation(true); this.remoteTransformationServiceUrl = remoteTransformationServiceUrl; } } }
false
true
private String transformHtml(InputStream xmlStream) throws Exception { // Create a transform factory instance. TransformerFactory tfactory = TransformerFactory.newInstance(); StringWriter resultForm = new StringWriter(); // StringWriter resultData = new StringWriter(); // Create a transformer for the stylesheet. Transformer transformerForm = tfactory.newTransformer(new StreamSource(new InputStreamReader(loadXsl(XSL_FORM),"UTF-8"))); // Create a transformer for the stylesheet. // Transformer transformerData = tfactory.newTransformer(new StreamSource(new InputStreamReader(loadXsl(XSL_DATA),"UTF-8"))); // get the xml bytes byte[] xmlBytes = IOUtils.toByteArray(xmlStream); // InputStream xmlStreamData = new ByteArrayInputStream(xmlBytes); InputStream xmlStreamForm = new ByteArrayInputStream(xmlBytes); // Transform the source XML to System.out. // transformerData.transform(new StreamSource(new InputStreamReader(xmlStreamData),"UTF-8"), new StreamResult(resultData)); transformerForm.transform(new StreamSource(new InputStreamReader(xmlStreamForm),"UTF-8"), new StreamResult(resultForm)); // return "<root>"+resultData.toString()+resultForm.toString()+"</root>"; return resultForm.toString(); }
private String transformHtml(InputStream xmlStream) throws Exception { // Create a transform factory instance. TransformerFactory tfactory = TransformerFactory.newInstance(); StringWriter resultForm = new StringWriter(); // StringWriter resultData = new StringWriter(); // Create a transformer for the stylesheet. Transformer transformerForm = tfactory.newTransformer(new StreamSource(new InputStreamReader(loadXsl(XSL_FORM),"UTF8"))); // Create a transformer for the stylesheet. // Transformer transformerData = tfactory.newTransformer(new StreamSource(new InputStreamReader(loadXsl(XSL_DATA),"UTF-8"))); // get the xml bytes byte[] xmlBytes = IOUtils.toByteArray(xmlStream); // InputStream xmlStreamData = new ByteArrayInputStream(xmlBytes); InputStream xmlStreamForm = new ByteArrayInputStream(xmlBytes); // Transform the source XML to System.out. // transformerData.transform(new StreamSource(new InputStreamReader(xmlStreamData),"UTF-8"), new StreamResult(resultData)); transformerForm.transform(new StreamSource(new InputStreamReader(xmlStreamForm),"UTF8"), new StreamResult(resultForm)); // return "<root>"+resultData.toString()+resultForm.toString()+"</root>"; return resultForm.toString(); }
diff --git a/src/java/org/jdesktop/swingx/plaf/basic/BasicHeaderUI.java b/src/java/org/jdesktop/swingx/plaf/basic/BasicHeaderUI.java index 234c2b72..4f81852d 100644 --- a/src/java/org/jdesktop/swingx/plaf/basic/BasicHeaderUI.java +++ b/src/java/org/jdesktop/swingx/plaf/basic/BasicHeaderUI.java @@ -1,322 +1,320 @@ /* * $Id$ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx.plaf.basic; import org.jdesktop.swingx.JXHeader; import org.jdesktop.swingx.JXLabel; import org.jdesktop.swingx.JXHeader.IconPosition; import org.jdesktop.swingx.painter.MattePainter; import org.jdesktop.swingx.painter.Painter; import org.jdesktop.swingx.plaf.HeaderUI; import org.jdesktop.swingx.plaf.PainterUIResource; import javax.swing.*; import javax.swing.plaf.ColorUIResource; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.FontUIResource; import javax.swing.plaf.basic.BasicHTML; import javax.swing.text.View; import java.awt.*; import java.awt.event.HierarchyBoundsAdapter; import java.awt.event.HierarchyBoundsListener; import java.awt.event.HierarchyEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; /** * * @author rbair * @author rah003 */ public class BasicHeaderUI extends HeaderUI { // Implementation detail. Neeeded to expose getMultiLineSupport() method to allow restoring view // lost after LAF switch protected class DescriptionPane extends JXLabel { @Override public void paint(Graphics g) { // switch off jxlabel default antialiasing ((Graphics2D)g).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); super.paint(g); } public MultiLineSupport getMultiLineSupport() { return super.getMultiLineSupport(); } } protected JLabel titleLabel; protected DescriptionPane descriptionPane; protected JLabel imagePanel; private PropertyChangeListener propListener; private HierarchyBoundsListener boundsListener; private Color gradientLightColor; private Color gradientDarkColor; /** Creates a new instance of BasicHeaderUI */ public BasicHeaderUI() { } /** * Returns an instance of the UI delegate for the specified component. * Each subclass must provide its own static <code>createUI</code> * method that returns an instance of that UI delegate subclass. * If the UI delegate subclass is stateless, it may return an instance * that is shared by multiple components. If the UI delegate is * stateful, then it should return a new instance per component. * The default implementation of this method throws an error, as it * should never be invoked. */ public static ComponentUI createUI(JComponent c) { return new BasicHeaderUI(); } /** * Configures the specified component appropriate for the look and feel. * This method is invoked when the <code>ComponentUI</code> instance is being installed * as the UI delegate on the specified component. This method should * completely configure the component for the look and feel, * including the following: * <ol> * <li>Install any default property values for color, fonts, borders, * icons, opacity, etc. on the component. Whenever possible, * property values initialized by the client program should <i>not</i> * be overridden. * <li>Install a <code>LayoutManager</code> on the component if necessary. * <li>Create/add any required sub-components to the component. * <li>Create/install event listeners on the component. * <li>Create/install a <code>PropertyChangeListener</code> on the component in order * to detect and respond to component property changes appropriately. * <li>Install keyboard UI (mnemonics, traversal, etc.) on the component. * <li>Initialize any appropriate instance data. * </ol> * @param c the component where this UI delegate is being installed * * @see #uninstallUI * @see javax.swing.JComponent#setUI * @see javax.swing.JComponent#updateUI */ @Override public void installUI(JComponent c) { super.installUI(c); assert c instanceof JXHeader; JXHeader header = (JXHeader)c; titleLabel = new JLabel(); descriptionPane = new DescriptionPane(); descriptionPane.setLineWrap(true); descriptionPane.setOpaque(false); installDefaults(header); imagePanel = new JLabel(); imagePanel.setIcon(header.getIcon() == null ? UIManager.getIcon("Header.defaultIcon") : header.getIcon()); installComponents(header); installListeners(header); } /** * Reverses configuration which was done on the specified component during * <code>installUI</code>. This method is invoked when this * <code>UIComponent</code> instance is being removed as the UI delegate * for the specified component. This method should undo the * configuration performed in <code>installUI</code>, being careful to * leave the <code>JComponent</code> instance in a clean state (no * extraneous listeners, look-and-feel-specific property objects, etc.). * This should include the following: * <ol> * <li>Remove any UI-set borders from the component. * <li>Remove any UI-set layout managers on the component. * <li>Remove any UI-added sub-components from the component. * <li>Remove any UI-added event/property listeners from the component. * <li>Remove any UI-installed keyboard UI from the component. * <li>Nullify any allocated instance data objects to allow for GC. * </ol> * @param c the component from which this UI delegate is being removed; * this argument is often ignored, * but might be used if the UI object is stateless * and shared by multiple components * * @see #installUI * @see javax.swing.JComponent#updateUI */ @Override public void uninstallUI(JComponent c) { assert c instanceof JXHeader; JXHeader header = (JXHeader)c; uninstallDefaults(header); uninstallListeners(header); uninstallComponents(header); titleLabel = null; descriptionPane = null; imagePanel = null; } protected void installDefaults(JXHeader h) { gradientLightColor = UIManager.getColor("JXHeader.startBackground"); if (gradientLightColor == null) { // fallback to white gradientLightColor = Color.WHITE; } gradientDarkColor = UIManager.getColor("JXHeader.background"); //for backwards compatibility (mostly for substance and synthetica, //I suspect) I'll fall back on the "control" color if JXHeader.background //isn't specified. if (gradientDarkColor == null) { gradientDarkColor = UIManager.getColor("control"); } Painter p = h.getBackgroundPainter(); if (p == null || p instanceof PainterUIResource) { h.setBackgroundPainter(createBackgroundPainter()); } // title properties Font titleFont = h.getTitleFont(); if (titleFont == null || titleFont instanceof FontUIResource) { titleFont = UIManager.getFont("JXHeader.titleFont"); // fallback to label font titleLabel.setFont(titleFont != null ? titleFont : UIManager.getFont("Label.font")); } Color titleForeground = h.getTitleForeground(); if (titleForeground == null || titleForeground instanceof ColorUIResource) { titleForeground = UIManager.getColor("JXHeader.titleForeground"); // fallback to label foreground titleLabel.setForeground(titleForeground != null ? titleForeground : UIManager.getColor("Label.foreground")); } - titleLabel.setText(h.getTitle() == null ? "Title For Header Goes Here" : h.getTitle()); + titleLabel.setText(h.getTitle()); // description properties Font descFont = h.getDescriptionFont(); if (descFont == null || descFont instanceof FontUIResource) { descFont = UIManager.getFont("JXHeader.descriptionFont"); // fallback to label font descriptionPane.setFont(descFont != null ? descFont : UIManager.getFont("Label.font")); } Color descForeground = h.getDescriptionForeground(); if (descForeground == null || descForeground instanceof ColorUIResource) { descForeground = UIManager.getColor("JXHeader.descriptionForeground"); // fallback to label foreground descriptionPane.setForeground(descForeground != null ? descForeground : UIManager.getColor("Label.foreground")); } - descriptionPane - .setText(h.getDescription() == null ? "The description for the header goes here.\nExample: Click the Copy Code button to generate the corresponding Java code." - : h.getDescription()); + descriptionPane.setText(h.getDescription()); } protected void uninstallDefaults(JXHeader h) { } protected void installListeners(final JXHeader h) { propListener = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { onPropertyChange(h, evt.getPropertyName(), evt.getOldValue(), evt.getNewValue()); } }; boundsListener = new HierarchyBoundsAdapter() { public void ancestorResized(HierarchyEvent e) { if (h == e.getComponent()) { View v = (View) descriptionPane.getClientProperty(BasicHTML.propertyKey); // view might get lost on LAF change ... if (v == null) { descriptionPane.putClientProperty(BasicHTML.propertyKey, descriptionPane.getMultiLineSupport().createView(descriptionPane)); v = (View) descriptionPane.getClientProperty(BasicHTML.propertyKey); } if (v != null) { v.setSize(h.getParent().getWidth() - h.getInsets().left - h.getInsets().right - descriptionPane.getInsets().left - descriptionPane.getInsets().right - descriptionPane.getBounds().x, descriptionPane.getHeight()); } } }}; h.addPropertyChangeListener(propListener); h.addHierarchyBoundsListener(boundsListener); } protected void uninstallListeners(JXHeader h) { h.removePropertyChangeListener(propListener); h.removeHierarchyBoundsListener(boundsListener); } protected void onPropertyChange(JXHeader h, String propertyName, Object oldValue, final Object newValue) { if ("title".equals(propertyName)) { titleLabel.setText(h.getTitle()); } else if ("description".equals(propertyName)) { descriptionPane.setText(h.getDescription()); } else if ("icon".equals(propertyName)) { imagePanel.setIcon(h.getIcon()); } else if ("enabled".equals(propertyName)) { boolean enabled = h.isEnabled(); titleLabel.setEnabled(enabled); descriptionPane.setEnabled(enabled); imagePanel.setEnabled(enabled); } else if ("titleFont".equals(propertyName)) { titleLabel.setFont((Font)newValue); } else if ("descriptionFont".equals(propertyName)) { descriptionPane.setFont((Font)newValue); } else if ("titleForeground".equals(propertyName)) { titleLabel.setForeground((Color)newValue); } else if ("descriptionForeground".equals(propertyName)) { descriptionPane.setForeground((Color)newValue); } else if ("iconPosition".equals(propertyName)) { resetLayout(h); } } protected void installComponents(JXHeader h) { h.setLayout(new GridBagLayout()); resetLayout(h); } private void resetLayout(JXHeader h) { h.remove(titleLabel); h.remove(descriptionPane); h.remove(imagePanel); if (h.getIconPosition() == null || h.getIconPosition() == IconPosition.RIGHT) { h.add(titleLabel, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL, new Insets(12, 12, 0, 11), 0, 0)); h.add(descriptionPane, new GridBagConstraints(0, 1, 1, 1, 1.0, 1.0, GridBagConstraints.FIRST_LINE_START, GridBagConstraints.BOTH, new Insets(0, 24, 12, 11), 0, 0)); h.add(imagePanel, new GridBagConstraints(1, 0, 1, 2, 0.0, 1.0, GridBagConstraints.FIRST_LINE_END, GridBagConstraints.NONE, new Insets(12, 0, 11, 11), 0, 0)); } else { h.add(titleLabel, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL, new Insets(12, 12, 0, 11), 0, 0)); h.add(descriptionPane, new GridBagConstraints(1, 1, 1, 1, 1.0, 1.0, GridBagConstraints.FIRST_LINE_START, GridBagConstraints.BOTH, new Insets(0, 24, 12, 11), 0, 0)); h.add(imagePanel, new GridBagConstraints(0, 0, 1, 2, 0.0, 1.0, GridBagConstraints.FIRST_LINE_END, GridBagConstraints.NONE, new Insets(12, 11, 0, 11), 0, 0)); } } protected void uninstallComponents(JXHeader h) { h.remove(titleLabel); h.remove(descriptionPane); h.remove(imagePanel); } protected Painter createBackgroundPainter() { MattePainter p = new MattePainter(new GradientPaint(0, 0, gradientLightColor, 1, 0, gradientDarkColor)); p.setPaintStretched(true); return new PainterUIResource(p); } }
false
true
protected void installDefaults(JXHeader h) { gradientLightColor = UIManager.getColor("JXHeader.startBackground"); if (gradientLightColor == null) { // fallback to white gradientLightColor = Color.WHITE; } gradientDarkColor = UIManager.getColor("JXHeader.background"); //for backwards compatibility (mostly for substance and synthetica, //I suspect) I'll fall back on the "control" color if JXHeader.background //isn't specified. if (gradientDarkColor == null) { gradientDarkColor = UIManager.getColor("control"); } Painter p = h.getBackgroundPainter(); if (p == null || p instanceof PainterUIResource) { h.setBackgroundPainter(createBackgroundPainter()); } // title properties Font titleFont = h.getTitleFont(); if (titleFont == null || titleFont instanceof FontUIResource) { titleFont = UIManager.getFont("JXHeader.titleFont"); // fallback to label font titleLabel.setFont(titleFont != null ? titleFont : UIManager.getFont("Label.font")); } Color titleForeground = h.getTitleForeground(); if (titleForeground == null || titleForeground instanceof ColorUIResource) { titleForeground = UIManager.getColor("JXHeader.titleForeground"); // fallback to label foreground titleLabel.setForeground(titleForeground != null ? titleForeground : UIManager.getColor("Label.foreground")); } titleLabel.setText(h.getTitle() == null ? "Title For Header Goes Here" : h.getTitle()); // description properties Font descFont = h.getDescriptionFont(); if (descFont == null || descFont instanceof FontUIResource) { descFont = UIManager.getFont("JXHeader.descriptionFont"); // fallback to label font descriptionPane.setFont(descFont != null ? descFont : UIManager.getFont("Label.font")); } Color descForeground = h.getDescriptionForeground(); if (descForeground == null || descForeground instanceof ColorUIResource) { descForeground = UIManager.getColor("JXHeader.descriptionForeground"); // fallback to label foreground descriptionPane.setForeground(descForeground != null ? descForeground : UIManager.getColor("Label.foreground")); } descriptionPane .setText(h.getDescription() == null ? "The description for the header goes here.\nExample: Click the Copy Code button to generate the corresponding Java code." : h.getDescription()); }
protected void installDefaults(JXHeader h) { gradientLightColor = UIManager.getColor("JXHeader.startBackground"); if (gradientLightColor == null) { // fallback to white gradientLightColor = Color.WHITE; } gradientDarkColor = UIManager.getColor("JXHeader.background"); //for backwards compatibility (mostly for substance and synthetica, //I suspect) I'll fall back on the "control" color if JXHeader.background //isn't specified. if (gradientDarkColor == null) { gradientDarkColor = UIManager.getColor("control"); } Painter p = h.getBackgroundPainter(); if (p == null || p instanceof PainterUIResource) { h.setBackgroundPainter(createBackgroundPainter()); } // title properties Font titleFont = h.getTitleFont(); if (titleFont == null || titleFont instanceof FontUIResource) { titleFont = UIManager.getFont("JXHeader.titleFont"); // fallback to label font titleLabel.setFont(titleFont != null ? titleFont : UIManager.getFont("Label.font")); } Color titleForeground = h.getTitleForeground(); if (titleForeground == null || titleForeground instanceof ColorUIResource) { titleForeground = UIManager.getColor("JXHeader.titleForeground"); // fallback to label foreground titleLabel.setForeground(titleForeground != null ? titleForeground : UIManager.getColor("Label.foreground")); } titleLabel.setText(h.getTitle()); // description properties Font descFont = h.getDescriptionFont(); if (descFont == null || descFont instanceof FontUIResource) { descFont = UIManager.getFont("JXHeader.descriptionFont"); // fallback to label font descriptionPane.setFont(descFont != null ? descFont : UIManager.getFont("Label.font")); } Color descForeground = h.getDescriptionForeground(); if (descForeground == null || descForeground instanceof ColorUIResource) { descForeground = UIManager.getColor("JXHeader.descriptionForeground"); // fallback to label foreground descriptionPane.setForeground(descForeground != null ? descForeground : UIManager.getColor("Label.foreground")); } descriptionPane.setText(h.getDescription()); }
diff --git a/src/main/java/hudson/maven/RedeployPublisher.java b/src/main/java/hudson/maven/RedeployPublisher.java index 162ea6f..88e1fd9 100644 --- a/src/main/java/hudson/maven/RedeployPublisher.java +++ b/src/main/java/hudson/maven/RedeployPublisher.java @@ -1,441 +1,441 @@ /* * The MIT License * * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, id:cactusman, Seiji Sogabe, Olivier Lamy * * 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 hudson.maven; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.Util; import hudson.maven.reporters.MavenAbstractArtifactRecord; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.model.Hudson; import hudson.model.Node; import hudson.model.Result; import hudson.model.TaskListener; import hudson.remoting.Callable; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Maven.MavenInstallation; import hudson.tasks.Publisher; import hudson.tasks.Recorder; import hudson.util.FormValidation; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map.Entry; import java.util.Properties; import net.sf.json.JSONObject; import org.apache.commons.lang.StringUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.deployer.ArtifactDeploymentException; import org.apache.maven.artifact.metadata.ArtifactMetadata; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.ArtifactRepositoryFactory; import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy; import org.apache.maven.artifact.repository.Authentication; import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout; import org.apache.maven.repository.Proxy; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest; /** * {@link Publisher} for {@link MavenModuleSetBuild} to deploy artifacts * after a build is fully succeeded. * * @author Kohsuke Kawaguchi * @since 1.191 */ public class RedeployPublisher extends Recorder { /** * Repository ID. This is matched up with <tt>~/.m2/settings.xml</tt> for authentication related information. */ public final String id; /** * Repository URL to deploy artifacts to. */ public final String url; public final boolean uniqueVersion; public final boolean evenIfUnstable; /** * For backward compatibility */ public RedeployPublisher(String id, String url, boolean uniqueVersion) { this(id, url, uniqueVersion, false); } /** * @since 1.347 */ @DataBoundConstructor public RedeployPublisher(String id, String url, boolean uniqueVersion, boolean evenIfUnstable) { this.id = id; this.url = Util.fixEmptyAndTrim(url); this.uniqueVersion = uniqueVersion; this.evenIfUnstable = evenIfUnstable; } public boolean perform(AbstractBuild<?,?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { if(build.getResult().isWorseThan(getTreshold())) return true; // build failed. Don't publish if (url==null) { listener.getLogger().println("No Repository URL is specified."); build.setResult(Result.FAILURE); return true; } List<MavenAbstractArtifactRecord> mars = getActions( build, listener ); if(mars==null || mars.isEmpty()) { listener.getLogger().println("No artifacts are recorded. Is this a Maven project?"); build.setResult(Result.FAILURE); return true; } listener.getLogger().println("Deploying artifacts to "+url); try { //MavenEmbedder embedder = MavenUtil.createEmbedder(listener,build); MavenEmbedder embedder = createEmbedder(listener,build); ArtifactRepositoryLayout layout = (ArtifactRepositoryLayout) embedder.lookup( ArtifactRepositoryLayout.ROLE,"default"); ArtifactRepositoryFactory factory = (ArtifactRepositoryFactory) embedder.lookup(ArtifactRepositoryFactory.ROLE); final ArtifactRepository repository = factory.createDeploymentArtifactRepository( id, url, layout, uniqueVersion); WrappedArtifactRepository repo = new WrappedArtifactRepository(repository,uniqueVersion); for (MavenAbstractArtifactRecord mar : mars) mar.deploy(embedder,repo,listener); return true; } catch (MavenEmbedderException e) { e.printStackTrace(listener.error(e.getMessage())); } catch (ComponentLookupException e) { e.printStackTrace(listener.error(e.getMessage())); } catch (ArtifactDeploymentException e) { e.printStackTrace(listener.error(e.getMessage())); } // failed build.setResult(Result.FAILURE); return true; } /** * * copy from MavenUtil but here we have to ignore localRepo path and setting as thoses paths comes * from the remote node and can not exist in master see http://issues.jenkins-ci.org/browse/JENKINS-8711 * */ private MavenEmbedder createEmbedder(TaskListener listener, AbstractBuild<?,?> build) throws MavenEmbedderException, IOException, InterruptedException { MavenInstallation m=null; File settingsLoc = null; String profiles = null; Properties systemProperties = null; String privateRepository = null; File tmpSettings = File.createTempFile( "jenkins", "temp-settings.xml" ); try { AbstractProject project = build.getProject(); // don't care here as it's executed in the master //if (project instanceof ProjectWithMaven) { // m = ((ProjectWithMaven) project).inferMavenInstallation().forNode(Hudson.getInstance(),listener); //} if (project instanceof MavenModuleSet) { profiles = ((MavenModuleSet) project).getProfiles(); systemProperties = ((MavenModuleSet) project).getMavenProperties(); // olamy see // we have to take about the settings use for the project // order tru configuration // TODO maybe in goals with -s,--settings last wins but not done in during pom parsing // or -Dmaven.repo.local // if not we must get ~/.m2/settings.xml then $M2_HOME/conf/settings.xml // TODO check if the remoteSettings has a localRepository configured and disabled it String altSettingsPath = ((MavenModuleSet) project).getAlternateSettings(); - Node buildNode = Hudson.getInstance().getNode( build.getBuiltOnStr() ); + Node buildNode = build.getBuiltOn(); if (StringUtils.isBlank( altSettingsPath ) ) { // get userHome from the node where job has been executed String remoteUserHome = build.getWorkspace().act( new GetUserHome() ); altSettingsPath = remoteUserHome + "/.m2/settings.xml"; } // we copy this file in the master in a temporary file FilePath filePath = new FilePath( tmpSettings ); FilePath remoteSettings = build.getWorkspace().child( altSettingsPath ); if (!remoteSettings.exists()) { // JENKINS-9084 we finally use $M2_HOME/conf/settings.xml as maven do String mavenHome = ((MavenModuleSet) project).getMaven().forNode(buildNode, listener ).getHome(); String settingsPath = mavenHome + "/conf/settings.xml"; remoteSettings = build.getWorkspace().child( settingsPath); } listener.getLogger().println( "Maven RedeployPublished use remote " + (buildNode != null ? buildNode.getNodeName() : "local" ) + " maven settings from : " + remoteSettings.getRemote() ); remoteSettings.copyTo( filePath ); settingsLoc = tmpSettings; } return MavenUtil.createEmbedder(new MavenEmbedderRequest(listener, m!=null?m.getHomeDir():null, profiles, systemProperties, privateRepository, settingsLoc )); } finally { tmpSettings.delete(); } } private static final class GetUserHome implements Callable<String,IOException> { public String call() throws IOException { return System.getProperty("user.home"); } } /** * Obtains the {@link MavenAbstractArtifactRecord} that we'll work on. * <p> * This allows promoted-builds plugin to reuse the code for delayed deployment. */ protected MavenAbstractArtifactRecord getAction(AbstractBuild<?, ?> build) { return build.getAction(MavenAbstractArtifactRecord.class); } protected List<MavenAbstractArtifactRecord> getActions(AbstractBuild<?, ?> build, BuildListener listener) { List<MavenAbstractArtifactRecord> actions = new ArrayList<MavenAbstractArtifactRecord>(); if (!(build instanceof MavenModuleSetBuild)) { return actions; } for (Entry<MavenModule, MavenBuild> e : ((MavenModuleSetBuild)build).getModuleLastBuilds().entrySet()) { MavenAbstractArtifactRecord a = e.getValue().getAction( MavenAbstractArtifactRecord.class ); if (a == null) { listener.getLogger().println("No artifacts are recorded for module" + e.getKey().getName() + ". Is this a Maven project?"); } else { actions.add( a ); } } return actions; } public BuildStepMonitor getRequiredMonitorService() { return BuildStepMonitor.NONE; } protected Result getTreshold() { if (evenIfUnstable) { return Result.UNSTABLE; } else { return Result.SUCCESS; } } @Extension public static class DescriptorImpl extends BuildStepDescriptor<Publisher> { public DescriptorImpl() { } /** * @deprecated as of 1.290 * Use the default constructor. */ protected DescriptorImpl(Class<? extends Publisher> clazz) { super(clazz); } public boolean isApplicable(Class<? extends AbstractProject> jobType) { return jobType==MavenModuleSet.class; } public RedeployPublisher newInstance(StaplerRequest req, JSONObject formData) throws FormException { return req.bindJSON(RedeployPublisher.class,formData); } public String getDisplayName() { return Messages.RedeployPublisher_getDisplayName(); } public boolean showEvenIfUnstableOption() { // little hack to avoid showing this option on the redeploy action's screen return true; } public FormValidation doCheckUrl(@QueryParameter String url) { String fixedUrl = hudson.Util.fixEmptyAndTrim(url); if (fixedUrl==null) return FormValidation.error(Messages.RedeployPublisher_RepositoryURL_Mandatory()); return FormValidation.ok(); } } //--------------------------------------------- public static class WrappedArtifactRepository implements ArtifactRepository { private ArtifactRepository artifactRepository; private boolean uniqueVersion; public WrappedArtifactRepository (ArtifactRepository artifactRepository, boolean uniqueVersion) { this.artifactRepository = artifactRepository; this.uniqueVersion = uniqueVersion; } public String pathOf( Artifact artifact ) { return artifactRepository.pathOf( artifact ); } public String pathOfRemoteRepositoryMetadata( ArtifactMetadata artifactMetadata ) { return artifactRepository.pathOfRemoteRepositoryMetadata( artifactMetadata ); } public String pathOfLocalRepositoryMetadata( ArtifactMetadata metadata, ArtifactRepository repository ) { return artifactRepository.pathOfLocalRepositoryMetadata( metadata, repository ); } public String getUrl() { return artifactRepository.getUrl(); } public void setUrl( String url ) { artifactRepository.setUrl( url ); } public String getBasedir() { return artifactRepository.getBasedir(); } public String getProtocol() { return artifactRepository.getProtocol(); } public String getId() { return artifactRepository.getId(); } public void setId( String id ) { artifactRepository.setId( id ); } public ArtifactRepositoryPolicy getSnapshots() { return artifactRepository.getSnapshots(); } public void setSnapshotUpdatePolicy( ArtifactRepositoryPolicy policy ) { artifactRepository.setSnapshotUpdatePolicy( policy ); } public ArtifactRepositoryPolicy getReleases() { return artifactRepository.getReleases(); } public void setReleaseUpdatePolicy( ArtifactRepositoryPolicy policy ) { artifactRepository.setReleaseUpdatePolicy( policy ); } public ArtifactRepositoryLayout getLayout() { return artifactRepository.getLayout(); } public void setLayout( ArtifactRepositoryLayout layout ) { artifactRepository.setLayout( layout ); } public String getKey() { return artifactRepository.getKey(); } public boolean isUniqueVersion() { return this.uniqueVersion; } public void setUniqueVersion(boolean uniqueVersion) { this.uniqueVersion = uniqueVersion; } public boolean isBlacklisted() { return artifactRepository.isBlacklisted(); } public void setBlacklisted( boolean blackListed ) { artifactRepository.setBlacklisted( blackListed ); } public Artifact find( Artifact artifact ) { return artifactRepository.find( artifact ); } public List<String> findVersions( Artifact artifact ) { return artifactRepository.findVersions( artifact ); } public boolean isProjectAware() { return artifactRepository.isProjectAware(); } public void setAuthentication( Authentication authentication ) { artifactRepository.setAuthentication( authentication ); } public Authentication getAuthentication() { return artifactRepository.getAuthentication(); } public void setProxy( Proxy proxy ) { artifactRepository.setProxy( proxy ); } public Proxy getProxy() { return artifactRepository.getProxy(); } public List<ArtifactRepository> getMirroredRepositories() { return Collections.emptyList(); } public void setMirroredRepositories( List<ArtifactRepository> arg0 ) { // noop } } }
true
true
private MavenEmbedder createEmbedder(TaskListener listener, AbstractBuild<?,?> build) throws MavenEmbedderException, IOException, InterruptedException { MavenInstallation m=null; File settingsLoc = null; String profiles = null; Properties systemProperties = null; String privateRepository = null; File tmpSettings = File.createTempFile( "jenkins", "temp-settings.xml" ); try { AbstractProject project = build.getProject(); // don't care here as it's executed in the master //if (project instanceof ProjectWithMaven) { // m = ((ProjectWithMaven) project).inferMavenInstallation().forNode(Hudson.getInstance(),listener); //} if (project instanceof MavenModuleSet) { profiles = ((MavenModuleSet) project).getProfiles(); systemProperties = ((MavenModuleSet) project).getMavenProperties(); // olamy see // we have to take about the settings use for the project // order tru configuration // TODO maybe in goals with -s,--settings last wins but not done in during pom parsing // or -Dmaven.repo.local // if not we must get ~/.m2/settings.xml then $M2_HOME/conf/settings.xml // TODO check if the remoteSettings has a localRepository configured and disabled it String altSettingsPath = ((MavenModuleSet) project).getAlternateSettings(); Node buildNode = Hudson.getInstance().getNode( build.getBuiltOnStr() ); if (StringUtils.isBlank( altSettingsPath ) ) { // get userHome from the node where job has been executed String remoteUserHome = build.getWorkspace().act( new GetUserHome() ); altSettingsPath = remoteUserHome + "/.m2/settings.xml"; } // we copy this file in the master in a temporary file FilePath filePath = new FilePath( tmpSettings ); FilePath remoteSettings = build.getWorkspace().child( altSettingsPath ); if (!remoteSettings.exists()) { // JENKINS-9084 we finally use $M2_HOME/conf/settings.xml as maven do String mavenHome = ((MavenModuleSet) project).getMaven().forNode(buildNode, listener ).getHome(); String settingsPath = mavenHome + "/conf/settings.xml"; remoteSettings = build.getWorkspace().child( settingsPath); } listener.getLogger().println( "Maven RedeployPublished use remote " + (buildNode != null ? buildNode.getNodeName() : "local" ) + " maven settings from : " + remoteSettings.getRemote() ); remoteSettings.copyTo( filePath ); settingsLoc = tmpSettings; } return MavenUtil.createEmbedder(new MavenEmbedderRequest(listener, m!=null?m.getHomeDir():null, profiles, systemProperties, privateRepository, settingsLoc )); } finally { tmpSettings.delete(); } }
private MavenEmbedder createEmbedder(TaskListener listener, AbstractBuild<?,?> build) throws MavenEmbedderException, IOException, InterruptedException { MavenInstallation m=null; File settingsLoc = null; String profiles = null; Properties systemProperties = null; String privateRepository = null; File tmpSettings = File.createTempFile( "jenkins", "temp-settings.xml" ); try { AbstractProject project = build.getProject(); // don't care here as it's executed in the master //if (project instanceof ProjectWithMaven) { // m = ((ProjectWithMaven) project).inferMavenInstallation().forNode(Hudson.getInstance(),listener); //} if (project instanceof MavenModuleSet) { profiles = ((MavenModuleSet) project).getProfiles(); systemProperties = ((MavenModuleSet) project).getMavenProperties(); // olamy see // we have to take about the settings use for the project // order tru configuration // TODO maybe in goals with -s,--settings last wins but not done in during pom parsing // or -Dmaven.repo.local // if not we must get ~/.m2/settings.xml then $M2_HOME/conf/settings.xml // TODO check if the remoteSettings has a localRepository configured and disabled it String altSettingsPath = ((MavenModuleSet) project).getAlternateSettings(); Node buildNode = build.getBuiltOn(); if (StringUtils.isBlank( altSettingsPath ) ) { // get userHome from the node where job has been executed String remoteUserHome = build.getWorkspace().act( new GetUserHome() ); altSettingsPath = remoteUserHome + "/.m2/settings.xml"; } // we copy this file in the master in a temporary file FilePath filePath = new FilePath( tmpSettings ); FilePath remoteSettings = build.getWorkspace().child( altSettingsPath ); if (!remoteSettings.exists()) { // JENKINS-9084 we finally use $M2_HOME/conf/settings.xml as maven do String mavenHome = ((MavenModuleSet) project).getMaven().forNode(buildNode, listener ).getHome(); String settingsPath = mavenHome + "/conf/settings.xml"; remoteSettings = build.getWorkspace().child( settingsPath); } listener.getLogger().println( "Maven RedeployPublished use remote " + (buildNode != null ? buildNode.getNodeName() : "local" ) + " maven settings from : " + remoteSettings.getRemote() ); remoteSettings.copyTo( filePath ); settingsLoc = tmpSettings; } return MavenUtil.createEmbedder(new MavenEmbedderRequest(listener, m!=null?m.getHomeDir():null, profiles, systemProperties, privateRepository, settingsLoc )); } finally { tmpSettings.delete(); } }
diff --git a/bte-io/src/main/java/gr/ekt/bteio/loaders/ExcelDataLoader.java b/bte-io/src/main/java/gr/ekt/bteio/loaders/ExcelDataLoader.java index 3bbfc2a..11a1024 100644 --- a/bte-io/src/main/java/gr/ekt/bteio/loaders/ExcelDataLoader.java +++ b/bte-io/src/main/java/gr/ekt/bteio/loaders/ExcelDataLoader.java @@ -1,214 +1,214 @@ /** * Copyright (c) 2007-2013, National Documentation Centre (EKT, www.ekt.gr) * 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 the National Documentation Centre 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 * HOLDER 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 gr.ekt.bteio.loaders; import gr.ekt.bte.core.DataLoadingSpec; import gr.ekt.bte.core.RecordSet; import gr.ekt.bte.core.StringValue; import gr.ekt.bte.dataloader.FileDataLoader; import gr.ekt.bte.exceptions.MalformedSourceException; import gr.ekt.bte.record.MapRecord; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Map; import org.apache.log4j.Logger; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; public class ExcelDataLoader extends FileDataLoader { private static Logger logger = Logger.getLogger(ExcelDataLoader.class); private Workbook wb; private Map<Integer, String> fieldMap; //Ignore the lines before line number skipLines private int skipLines; //If the ignoreLines == 0 then we read all the lines (respecting skipLines) private int ignoreLinesAfter; private boolean isRead; public ExcelDataLoader(String filename, Map<Integer, String> fieldMap) { super(filename); new File(filename); this.fieldMap = fieldMap; this.skipLines = 0; this.ignoreLinesAfter = 0; wb = null; isRead = false; } @Override public RecordSet getRecords() throws MalformedSourceException { try { openReader(); } catch (IOException e) { logger.info("Problem loading file: " + filename + " (" + e.getMessage() + ")"); throw new MalformedSourceException("Problem loading file: " + filename + " (" + e.getMessage() + ")"); } catch (InvalidFormatException e) { logger.info("Problem loading file: " + filename + " (" + e.getMessage() + ")"); throw new MalformedSourceException("Problem loading file: " + filename + " (" + e.getMessage() + ")"); } RecordSet ret = new RecordSet(); //Currently we need this flag in order for //TransformationEngine not to go into an infinite loop. if (!isRead) { logger.info("Opening file: " + filename); int nSheets = wb.getNumberOfSheets(); logger.info("number of sheets: " + nSheets); for(int i = 0; i < nSheets; i++) { Sheet cSheet = wb.getSheetAt(i); String cSheetName = cSheet.getSheetName(); - for(int j = skipLines; j < cSheet.getLastRowNum(); j++) { + for(int j = skipLines; j <= cSheet.getLastRowNum(); j++) { if (ignoreLinesAfter != 0 && j >= ignoreLinesAfter) { break; } Row row = cSheet.getRow(j); MapRecord rec = new MapRecord(); for(int k = 0; k < row.getLastCellNum(); k++) { if (!fieldMap.keySet().contains(k)) { continue; } StringValue val; Cell cCell = row.getCell(k); if (cCell == null) { continue; } int cellType = cCell.getCellType(); switch (cellType) { case Cell.CELL_TYPE_STRING: val = new StringValue( cCell.getStringCellValue()); break; case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(cCell)) { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); val = new StringValue(sdf.format(cCell.getDateCellValue())); } else { val = new StringValue(String.valueOf(cCell .getNumericCellValue())); } break; case Cell.CELL_TYPE_BLANK: val = new StringValue(""); break; case Cell.CELL_TYPE_BOOLEAN: val = new StringValue(String.valueOf(cCell .getBooleanCellValue())); break; default: val = new StringValue("Unsupported cell type"); } rec.addValue(fieldMap.get(k), val); } //TODO remove the hardcoded value rec.addValue("ExcelSheetName", new StringValue(cSheetName)); ret.addRecord(rec); } } isRead = true; } return ret; } @Override public RecordSet getRecords(DataLoadingSpec spec) throws MalformedSourceException { return getRecords(); } private void openReader() throws IOException, InvalidFormatException { wb = WorkbookFactory.create(new File(filename)); } /** * @return the fieldMap */ public Map<Integer, String> getFieldMap() { return fieldMap; } /** * @param fieldMap the fieldMap to set */ public void setFieldMap(Map<Integer, String> fieldMap) { this.fieldMap = fieldMap; } /** * @return the skipLines */ public int getSkipLines() { return skipLines; } /** * @param skipLines the skipLines to set */ public void setSkipLines(int skipLines) { this.skipLines = skipLines; } /** * @return the ignoreLinesAfter */ public int getIgnoreLinesAfter () { return ignoreLinesAfter; } /** * @param ignoreLinesAfter the ignoreLinesAfter to set */ public void setIgnoreLinesAfter (int ignoreLinesAfter) { this.ignoreLinesAfter = ignoreLinesAfter; } }
true
true
public RecordSet getRecords() throws MalformedSourceException { try { openReader(); } catch (IOException e) { logger.info("Problem loading file: " + filename + " (" + e.getMessage() + ")"); throw new MalformedSourceException("Problem loading file: " + filename + " (" + e.getMessage() + ")"); } catch (InvalidFormatException e) { logger.info("Problem loading file: " + filename + " (" + e.getMessage() + ")"); throw new MalformedSourceException("Problem loading file: " + filename + " (" + e.getMessage() + ")"); } RecordSet ret = new RecordSet(); //Currently we need this flag in order for //TransformationEngine not to go into an infinite loop. if (!isRead) { logger.info("Opening file: " + filename); int nSheets = wb.getNumberOfSheets(); logger.info("number of sheets: " + nSheets); for(int i = 0; i < nSheets; i++) { Sheet cSheet = wb.getSheetAt(i); String cSheetName = cSheet.getSheetName(); for(int j = skipLines; j < cSheet.getLastRowNum(); j++) { if (ignoreLinesAfter != 0 && j >= ignoreLinesAfter) { break; } Row row = cSheet.getRow(j); MapRecord rec = new MapRecord(); for(int k = 0; k < row.getLastCellNum(); k++) { if (!fieldMap.keySet().contains(k)) { continue; } StringValue val; Cell cCell = row.getCell(k); if (cCell == null) { continue; } int cellType = cCell.getCellType(); switch (cellType) { case Cell.CELL_TYPE_STRING: val = new StringValue( cCell.getStringCellValue()); break; case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(cCell)) { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); val = new StringValue(sdf.format(cCell.getDateCellValue())); } else { val = new StringValue(String.valueOf(cCell .getNumericCellValue())); } break; case Cell.CELL_TYPE_BLANK: val = new StringValue(""); break; case Cell.CELL_TYPE_BOOLEAN: val = new StringValue(String.valueOf(cCell .getBooleanCellValue())); break; default: val = new StringValue("Unsupported cell type"); } rec.addValue(fieldMap.get(k), val); } //TODO remove the hardcoded value rec.addValue("ExcelSheetName", new StringValue(cSheetName)); ret.addRecord(rec); } } isRead = true; } return ret; }
public RecordSet getRecords() throws MalformedSourceException { try { openReader(); } catch (IOException e) { logger.info("Problem loading file: " + filename + " (" + e.getMessage() + ")"); throw new MalformedSourceException("Problem loading file: " + filename + " (" + e.getMessage() + ")"); } catch (InvalidFormatException e) { logger.info("Problem loading file: " + filename + " (" + e.getMessage() + ")"); throw new MalformedSourceException("Problem loading file: " + filename + " (" + e.getMessage() + ")"); } RecordSet ret = new RecordSet(); //Currently we need this flag in order for //TransformationEngine not to go into an infinite loop. if (!isRead) { logger.info("Opening file: " + filename); int nSheets = wb.getNumberOfSheets(); logger.info("number of sheets: " + nSheets); for(int i = 0; i < nSheets; i++) { Sheet cSheet = wb.getSheetAt(i); String cSheetName = cSheet.getSheetName(); for(int j = skipLines; j <= cSheet.getLastRowNum(); j++) { if (ignoreLinesAfter != 0 && j >= ignoreLinesAfter) { break; } Row row = cSheet.getRow(j); MapRecord rec = new MapRecord(); for(int k = 0; k < row.getLastCellNum(); k++) { if (!fieldMap.keySet().contains(k)) { continue; } StringValue val; Cell cCell = row.getCell(k); if (cCell == null) { continue; } int cellType = cCell.getCellType(); switch (cellType) { case Cell.CELL_TYPE_STRING: val = new StringValue( cCell.getStringCellValue()); break; case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(cCell)) { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); val = new StringValue(sdf.format(cCell.getDateCellValue())); } else { val = new StringValue(String.valueOf(cCell .getNumericCellValue())); } break; case Cell.CELL_TYPE_BLANK: val = new StringValue(""); break; case Cell.CELL_TYPE_BOOLEAN: val = new StringValue(String.valueOf(cCell .getBooleanCellValue())); break; default: val = new StringValue("Unsupported cell type"); } rec.addValue(fieldMap.get(k), val); } //TODO remove the hardcoded value rec.addValue("ExcelSheetName", new StringValue(cSheetName)); ret.addRecord(rec); } } isRead = true; } return ret; }
diff --git a/comet/service/src/test/java/org/exoplatform/ws/frameworks/cometd/CargoContainer.java b/comet/service/src/test/java/org/exoplatform/ws/frameworks/cometd/CargoContainer.java index 55e2fe80..4dde2547 100644 --- a/comet/service/src/test/java/org/exoplatform/ws/frameworks/cometd/CargoContainer.java +++ b/comet/service/src/test/java/org/exoplatform/ws/frameworks/cometd/CargoContainer.java @@ -1,180 +1,180 @@ /* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program 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. * 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.exoplatform.ws.frameworks.cometd; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.exoplatform.services.log.Log; import org.codehaus.cargo.container.ContainerType; import org.codehaus.cargo.container.EmbeddedLocalContainer; import org.codehaus.cargo.container.InstalledLocalContainer; import org.codehaus.cargo.container.LocalContainer; import org.codehaus.cargo.container.configuration.ConfigurationType; import org.codehaus.cargo.container.configuration.ExistingLocalConfiguration; import org.codehaus.cargo.container.configuration.LocalConfiguration; import org.codehaus.cargo.container.configuration.StandaloneLocalConfiguration; import org.codehaus.cargo.container.deployable.WAR; import org.codehaus.cargo.container.installer.Installer; import org.codehaus.cargo.container.installer.ZipURLInstaller; import org.codehaus.cargo.container.jetty.Jetty6xEmbeddedLocalContainer; import org.codehaus.cargo.container.jetty.Jetty6xEmbeddedStandaloneLocalConfiguration; import org.codehaus.cargo.container.jetty.internal.Jetty6xStandaloneLocalConfigurationCapability; import org.codehaus.cargo.container.property.ServletPropertySet; import org.codehaus.cargo.generic.DefaultContainerFactory; import org.codehaus.cargo.generic.configuration.DefaultConfigurationFactory; import org.codehaus.cargo.util.FileHandler; import org.codehaus.cargo.util.log.LogLevel; import org.codehaus.cargo.util.log.SimpleLogger; import org.exoplatform.services.log.ExoLogger; /** * Created by The eXo Platform SAS. * * @author <a href="mailto:[email protected]">Vitaly Parfonov</a> * @version $Id: $ */ public class CargoContainer { /** * Class logger. */ private final Log log = ExoLogger.getLogger("ws.CargoContainer"); // private static InstalledLocalContainer container; protected static final String TEST_PATH = (System.getProperty("testPath") == null ? "." : System.getProperty("testPath")); protected static final String TEST_LIB_PATH = TEST_PATH + "/target/test"; // public static InstalledLocalContainer cargoContainertStart() { // return cargoContainerStart(null, null); // } // // public static InstalledLocalContainer cargoContainerStart(String port){ // return cargoContainerStart(port, null); // } public static InstalledLocalContainer cargoContainerStart(String port, String home) { try { if (port == null || port == "") { // Default port port = "8080"; } if (home == null || home == "") { // Default home home = System.getProperty("java.io.tmpdir"); } Installer installer = new ZipURLInstaller(new java.net.URL( - "http://www.apache.org/dist/tomcat/tomcat-6/v6.0.18/bin/apache-tomcat-6.0.18.zip"), home); + "http://www.apache.org/dist/tomcat/tomcat-6/v6.0.35/bin/apache-tomcat-6.0.35.zip"), home); installer.install(); // Installer installer = // new ZipURLInstaller(new java.net.URL( // "http://www.apache.org/dist/tomcat/tomcat-5/v5.5.25/bin/apache-tomcat-5.5.25.zip" // ), home); // installer.install(); LocalConfiguration configuration = (LocalConfiguration) new DefaultConfigurationFactory().createConfiguration("tomcat5x", ContainerType.INSTALLED, ConfigurationType.STANDALONE);// , // "/home/vetal/eXo/" // + // id // + // "/conf" // ) // ; configuration.setProperty(ServletPropertySet.PORT, port); // configuration.addDeployable(new WAR(TEST_PATH + // "/target/test/war/portal.war")); // configuration.addDeployable(new WAR(TEST_PATH + "/target/test/war/cometd.war")); configuration.addDeployable(new WAR(TEST_PATH + "/target/test/war/rest.war")); InstalledLocalContainer container = (InstalledLocalContainer) new DefaultContainerFactory().createContainer("tomcat5x", ContainerType.INSTALLED, configuration); container.setHome(installer.getHome()); String[] arr; List<String> lst = new ArrayList<String>(); File dir = new File(TEST_LIB_PATH); arr = dir.list(new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(".jar"); } }); for (String name : arr) { lst.add(TEST_LIB_PATH + "/" + name); } String[] arr2 = new String[lst.size()]; lst.toArray(arr2); container.setExtraClasspath(arr2); container.setOutput("target/logs/tomcat.log"); SimpleLogger logger = new SimpleLogger(); LogLevel level = LogLevel.WARN; logger.setLevel(level); container.setLogger(logger); File inputFile = new File(TEST_PATH + "/src/test/resources/tomcat/exo-configuration.xml"); File outputFile = new File(container.getHome() + "/exo-configuration.xml"); System.out.println("CargoContainer.cargoContainerStart()" + container.getHome()); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); container.start(); System.out.println("CargoContainer.containerStart() : " + container.getState().isStarted()); return container; } catch (Exception e) { e.printStackTrace(); return null; } } public static void cargoContainerStop(InstalledLocalContainer container) { container.stop(); } }
true
true
public static InstalledLocalContainer cargoContainerStart(String port, String home) { try { if (port == null || port == "") { // Default port port = "8080"; } if (home == null || home == "") { // Default home home = System.getProperty("java.io.tmpdir"); } Installer installer = new ZipURLInstaller(new java.net.URL( "http://www.apache.org/dist/tomcat/tomcat-6/v6.0.18/bin/apache-tomcat-6.0.18.zip"), home); installer.install(); // Installer installer = // new ZipURLInstaller(new java.net.URL( // "http://www.apache.org/dist/tomcat/tomcat-5/v5.5.25/bin/apache-tomcat-5.5.25.zip" // ), home); // installer.install(); LocalConfiguration configuration = (LocalConfiguration) new DefaultConfigurationFactory().createConfiguration("tomcat5x", ContainerType.INSTALLED, ConfigurationType.STANDALONE);// , // "/home/vetal/eXo/" // + // id // + // "/conf" // ) // ; configuration.setProperty(ServletPropertySet.PORT, port); // configuration.addDeployable(new WAR(TEST_PATH + // "/target/test/war/portal.war")); // configuration.addDeployable(new WAR(TEST_PATH + "/target/test/war/cometd.war")); configuration.addDeployable(new WAR(TEST_PATH + "/target/test/war/rest.war")); InstalledLocalContainer container = (InstalledLocalContainer) new DefaultContainerFactory().createContainer("tomcat5x", ContainerType.INSTALLED, configuration); container.setHome(installer.getHome()); String[] arr; List<String> lst = new ArrayList<String>(); File dir = new File(TEST_LIB_PATH); arr = dir.list(new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(".jar"); } }); for (String name : arr) { lst.add(TEST_LIB_PATH + "/" + name); } String[] arr2 = new String[lst.size()]; lst.toArray(arr2); container.setExtraClasspath(arr2); container.setOutput("target/logs/tomcat.log"); SimpleLogger logger = new SimpleLogger(); LogLevel level = LogLevel.WARN; logger.setLevel(level); container.setLogger(logger); File inputFile = new File(TEST_PATH + "/src/test/resources/tomcat/exo-configuration.xml"); File outputFile = new File(container.getHome() + "/exo-configuration.xml"); System.out.println("CargoContainer.cargoContainerStart()" + container.getHome()); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); container.start(); System.out.println("CargoContainer.containerStart() : " + container.getState().isStarted()); return container; } catch (Exception e) { e.printStackTrace(); return null; } }
public static InstalledLocalContainer cargoContainerStart(String port, String home) { try { if (port == null || port == "") { // Default port port = "8080"; } if (home == null || home == "") { // Default home home = System.getProperty("java.io.tmpdir"); } Installer installer = new ZipURLInstaller(new java.net.URL( "http://www.apache.org/dist/tomcat/tomcat-6/v6.0.35/bin/apache-tomcat-6.0.35.zip"), home); installer.install(); // Installer installer = // new ZipURLInstaller(new java.net.URL( // "http://www.apache.org/dist/tomcat/tomcat-5/v5.5.25/bin/apache-tomcat-5.5.25.zip" // ), home); // installer.install(); LocalConfiguration configuration = (LocalConfiguration) new DefaultConfigurationFactory().createConfiguration("tomcat5x", ContainerType.INSTALLED, ConfigurationType.STANDALONE);// , // "/home/vetal/eXo/" // + // id // + // "/conf" // ) // ; configuration.setProperty(ServletPropertySet.PORT, port); // configuration.addDeployable(new WAR(TEST_PATH + // "/target/test/war/portal.war")); // configuration.addDeployable(new WAR(TEST_PATH + "/target/test/war/cometd.war")); configuration.addDeployable(new WAR(TEST_PATH + "/target/test/war/rest.war")); InstalledLocalContainer container = (InstalledLocalContainer) new DefaultContainerFactory().createContainer("tomcat5x", ContainerType.INSTALLED, configuration); container.setHome(installer.getHome()); String[] arr; List<String> lst = new ArrayList<String>(); File dir = new File(TEST_LIB_PATH); arr = dir.list(new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(".jar"); } }); for (String name : arr) { lst.add(TEST_LIB_PATH + "/" + name); } String[] arr2 = new String[lst.size()]; lst.toArray(arr2); container.setExtraClasspath(arr2); container.setOutput("target/logs/tomcat.log"); SimpleLogger logger = new SimpleLogger(); LogLevel level = LogLevel.WARN; logger.setLevel(level); container.setLogger(logger); File inputFile = new File(TEST_PATH + "/src/test/resources/tomcat/exo-configuration.xml"); File outputFile = new File(container.getHome() + "/exo-configuration.xml"); System.out.println("CargoContainer.cargoContainerStart()" + container.getHome()); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); container.start(); System.out.println("CargoContainer.containerStart() : " + container.getState().isStarted()); return container; } catch (Exception e) { e.printStackTrace(); return null; } }
diff --git a/modules/org.restlet/src/org/restlet/Finder.java b/modules/org.restlet/src/org/restlet/Finder.java index 7cd1509ba..272e396a0 100644 --- a/modules/org.restlet/src/org/restlet/Finder.java +++ b/modules/org.restlet/src/org/restlet/Finder.java @@ -1,372 +1,372 @@ /* * Copyright 2005-2007 Noelios Consulting. * * The contents of this file are subject to the terms of the Common Development * and Distribution License (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.opensource.org/licenses/cddl1.txt 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 http://www.opensource.org/licenses/cddl1.txt 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] */ package org.restlet; import java.lang.reflect.Constructor; import java.util.Set; import java.util.logging.Level; import org.restlet.data.Method; import org.restlet.data.Request; import org.restlet.data.Response; import org.restlet.data.Status; import org.restlet.resource.Resource; /** * Restlet that can find the target resource that will concretely handle a call. * Based on a given resource class, it is also capable of instantiating the * resource with the call's context, request and response without requiring the * usage of a subclass. It will use either the constructor with three arguments: * context, request, response; or it will invoke the default constructor then * invoke the init() method with the same arguments.<br> * <br> * Once the target resource has been found, the call is automatically dispatched * to the appropriate handle*() method (where the '*' character corresponds to * the method name) if the corresponding allow*() method returns true.<br> * <br> * For example, if you want to support a MOVE method for a WebDAV server, you * just have to add a handleMove() method in your subclass of Resource and it * will be automatically be used by the Finder instance at runtime.<br> * <br> * If no matching handle*() method is found, then a * Status.CLIENT_ERROR_METHOD_NOT_ALLOWED is returned. * * @see <a href="http://www.restlet.org/tutorial#part12">Tutorial: Reaching * target Resources</a> * @author Jerome Louvel ([email protected]) */ public class Finder extends Restlet { /** Target resource class. */ private Class<? extends Resource> targetClass; /** * Constructor. */ public Finder() { this(null); } /** * Constructor. * * @param context * The context. */ public Finder(Context context) { this(context, null); } /** * Constructor. * * @param context * The context. * @param targetClass * The target resource class. */ public Finder(Context context, Class<? extends Resource> targetClass) { super(context); this.targetClass = targetClass; } /** * Indicates if a method is allowed on a target resource. * * @param method * The method to test. * @param target * The target resource. * @return True if a method is allowed on a target resource. */ private boolean allowMethod(Method method, Resource target) { boolean result = false; if (target != null) { if (method.equals(Method.GET) || method.equals(Method.HEAD)) { result = target.allowGet(); } else if (method.equals(Method.POST)) { result = target.allowPost(); } else if (method.equals(Method.PUT)) { result = target.allowPut(); } else if (method.equals(Method.DELETE)) { result = target.allowDelete(); } else if (method.equals(Method.OPTIONS)) { result = true; } else { // Dynamically introspect the target resource to detect a // matching "allow" method. java.lang.reflect.Method allowMethod = getAllowMethod(method, target); if (allowMethod != null) { result = (Boolean) invoke(target, allowMethod); } } } return result; } /** * Finds the target Resource if available. The default behavior is to invoke * the {@link #createResource(Request, Response)} method. * * @param request * The request to handle. * @param response * The response to update. * @return The target resource if available or null. */ public Resource findTarget(Request request, Response response) { return createResource(request, response); } /** * Creates a new instance of the resource class designated by the * "targetClass" property. * * @param request * The request to handle. * @param response * The response to update. * @return The created resource or null. */ public Resource createResource(Request request, Response response) { Resource result = null; if (getTargetClass() != null) { try { Constructor constructor; try { // Invoke the constructor with Context, Request and Response // parameters constructor = getTargetClass().getConstructor( Context.class, Request.class, Response.class); result = (Resource) constructor.newInstance(getContext(), request, response); } catch (NoSuchMethodException nsme) { // Invoke the default constructor then the init(Context, // Request, Response) method. constructor = getTargetClass().getConstructor(); if (constructor != null) { result = (Resource) constructor.newInstance(); result.init(getContext(), request, response); } } } catch (Exception e) { getLogger() .log( Level.WARNING, "Exception while instantiating the target resource.", e); } } return result; } /** * Returns the allow method matching the given method name. * * @param method * The method to match. * @param target * The target resource. * @return The allow method matching the given method name. */ private java.lang.reflect.Method getAllowMethod(Method method, Resource target) { return getMethod("allow", method, target); } /** * Returns the handle method matching the given method name. * * @param method * The method to match. * @return The handle method matching the given method name. */ private java.lang.reflect.Method getHandleMethod(Resource target, Method method) { return getMethod("handle", method, target); } /** * Returns the method matching the given prefix and method name. * * @param prefix * The method prefix to match (ex: "allow" or "handle"). * @param method * The method to match. * @return The method matching the given prefix and method name. */ private java.lang.reflect.Method getMethod(String prefix, Method method, Object target, Class... classes) { java.lang.reflect.Method result = null; StringBuilder sb = new StringBuilder(); String methodName = method.getName().toLowerCase(); if ((methodName != null) && (methodName.length() > 0)) { sb.append(prefix); sb.append(Character.toUpperCase(methodName.charAt(0))); sb.append(methodName.substring(1)); } try { result = target.getClass().getMethod(sb.toString(), classes); } catch (SecurityException e) { getLogger().log( Level.WARNING, "Couldn't access the " + prefix + " method for \"" + method + "\"", e); } catch (NoSuchMethodException e) { getLogger().log( Level.WARNING, "Couldn't find the " + prefix + " method for \"" + method + "\"", e); } return result; } /** * Returns the target Resource class. * * @return the target Resource class. */ public Class<? extends Resource> getTargetClass() { return this.targetClass; } /** * Handles a call. * * @param request * The request to handle. * @param response * The response to update. */ public void handle(Request request, Response response) { init(request, response); if (isStarted()) { Resource target = findTarget(request, response); if (!response.getStatus().equals(Status.SUCCESS_OK)) { // Probably during the instantiation of the target resource, or // earlier the status was changed from the default one. Don't go // further. } else if (target == null) { // If the currrent status is a success but we couldn't find the // target resource for the request's resource URI, then we set // the response status to 404 (Not Found). response.setStatus(Status.CLIENT_ERROR_NOT_FOUND); } else { Method method = request.getMethod(); if (method == null) { response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST, "No method specified"); } else { if (!allowMethod(method, target)) { response .setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); updateAllowedMethods(response, target); } else { if (method.equals(Method.GET)) { target.handleGet(); } else if (method.equals(Method.HEAD)) { target.handleHead(); } else if (method.equals(Method.POST)) { target.handlePost(); } else if (method.equals(Method.PUT)) { target.handlePut(); } else if (method.equals(Method.DELETE)) { target.handleDelete(); } else if (method.equals(Method.OPTIONS)) { target.handleOptions(); } else { java.lang.reflect.Method handleMethod = getHandleMethod( target, method); if (handleMethod != null) { - invoke(this, handleMethod, request, response); + invoke(target, handleMethod); } else { response .setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); } } } } } } } /** * Invokes a method with the given arguments. * * @param target * The target object. * @param method * The method to invoke. * @param args * The arguments to pass. * @return Invocation result. */ private Object invoke(Object target, java.lang.reflect.Method method, Object... args) { Object result = null; if (method != null) { try { result = method.invoke(target, args); } catch (Exception e) { getLogger().log( Level.WARNING, "Couldn't invoke the handle method for \"" + method + "\"", e); } } return result; } /** * Updates the set of allowed methods on the response based on a target * resource. * * @param response * The response to update. * @param target * The target resource. */ private void updateAllowedMethods(Response response, Resource target) { Set<Method> allowedMethods = response.getAllowedMethods(); for (java.lang.reflect.Method classMethod : target.getClass() .getMethods()) { if (classMethod.getName().startsWith("allow") && (classMethod.getParameterTypes().length == 0)) { if ((Boolean) invoke(target, classMethod)) { Method allowedMethod = Method.valueOf(classMethod.getName() .substring(5)); allowedMethods.add(allowedMethod); } } } } }
true
true
public void handle(Request request, Response response) { init(request, response); if (isStarted()) { Resource target = findTarget(request, response); if (!response.getStatus().equals(Status.SUCCESS_OK)) { // Probably during the instantiation of the target resource, or // earlier the status was changed from the default one. Don't go // further. } else if (target == null) { // If the currrent status is a success but we couldn't find the // target resource for the request's resource URI, then we set // the response status to 404 (Not Found). response.setStatus(Status.CLIENT_ERROR_NOT_FOUND); } else { Method method = request.getMethod(); if (method == null) { response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST, "No method specified"); } else { if (!allowMethod(method, target)) { response .setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); updateAllowedMethods(response, target); } else { if (method.equals(Method.GET)) { target.handleGet(); } else if (method.equals(Method.HEAD)) { target.handleHead(); } else if (method.equals(Method.POST)) { target.handlePost(); } else if (method.equals(Method.PUT)) { target.handlePut(); } else if (method.equals(Method.DELETE)) { target.handleDelete(); } else if (method.equals(Method.OPTIONS)) { target.handleOptions(); } else { java.lang.reflect.Method handleMethod = getHandleMethod( target, method); if (handleMethod != null) { invoke(this, handleMethod, request, response); } else { response .setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); } } } } } } }
public void handle(Request request, Response response) { init(request, response); if (isStarted()) { Resource target = findTarget(request, response); if (!response.getStatus().equals(Status.SUCCESS_OK)) { // Probably during the instantiation of the target resource, or // earlier the status was changed from the default one. Don't go // further. } else if (target == null) { // If the currrent status is a success but we couldn't find the // target resource for the request's resource URI, then we set // the response status to 404 (Not Found). response.setStatus(Status.CLIENT_ERROR_NOT_FOUND); } else { Method method = request.getMethod(); if (method == null) { response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST, "No method specified"); } else { if (!allowMethod(method, target)) { response .setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); updateAllowedMethods(response, target); } else { if (method.equals(Method.GET)) { target.handleGet(); } else if (method.equals(Method.HEAD)) { target.handleHead(); } else if (method.equals(Method.POST)) { target.handlePost(); } else if (method.equals(Method.PUT)) { target.handlePut(); } else if (method.equals(Method.DELETE)) { target.handleDelete(); } else if (method.equals(Method.OPTIONS)) { target.handleOptions(); } else { java.lang.reflect.Method handleMethod = getHandleMethod( target, method); if (handleMethod != null) { invoke(target, handleMethod); } else { response .setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); } } } } } } }
diff --git a/src/com/wolvencraft/prison/mines/util/Message.java b/src/com/wolvencraft/prison/mines/util/Message.java index cf350da..74ac0b7 100644 --- a/src/com/wolvencraft/prison/mines/util/Message.java +++ b/src/com/wolvencraft/prison/mines/util/Message.java @@ -1,110 +1,110 @@ package com.wolvencraft.prison.mines.util; import java.util.logging.Level; import java.util.logging.Logger; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import com.wolvencraft.prison.mines.CommandManager; import com.wolvencraft.prison.mines.PrisonMine; public class Message extends com.wolvencraft.prison.util.Message { private static Logger logger = Logger.getLogger("PrisonMine"); public static void send(String message) { CommandSender sender = CommandManager.getSender(); if(sender instanceof Player) send((Player) sender, message); else Bukkit.getConsoleSender().sendMessage(message); } public static void sendSuccess(Player player, String message) { message = PrisonMine.getLanguage().GENERAL_SUCCESS + " " + ChatColor.WHITE + message; send(player, message); } public static void sendSuccess(String message) { CommandSender sender = CommandManager.getSender(); if(sender instanceof Player) sendSuccess((Player) sender, message); else Bukkit.getConsoleSender().sendMessage(message); } public static void sendError(Player player, String message) { message = PrisonMine.getLanguage().GENERAL_ERROR + " " + ChatColor.WHITE + message; send(player, message); } public static void sendError(String message) { CommandSender sender = CommandManager.getSender(); if(sender instanceof Player) sendError((Player) sender, message); else Bukkit.getConsoleSender().sendMessage(message); } public static void sendCustom(String title, String message) { CommandSender sender = CommandManager.getSender(); if(sender instanceof Player) send((Player) sender, ChatColor.GOLD + "[" + title + "] " + ChatColor.WHITE + message); else Bukkit.getConsoleSender().sendMessage(message); } /** * Broadcasts a message to all players on the server * @param message Message to be sent */ public static void broadcast(String message) { if(message == null) message = ""; message = PrisonMine.getLanguage().GENERAL_SUCCESS + " " + ChatColor.WHITE + message; for (Player p : Bukkit.getServer().getOnlinePlayers()) { - p.sendMessage(Util.parseColors(message)); + if(p.hasPermission("mcprison.mine.reset.broadcast")) p.sendMessage(Util.parseColors(message)); } } /** * Sends a message into the server log if debug is enabled * @param message Message to be sent */ public static void debug(String message) { if (PrisonMine.getSettings().DEBUG) log(message); } /** * Sends a message into the server log * @param message Message to be sent */ public static void log(String message) { logger.info("[PrisonMine] " + message); } /** * Sends a message into the server log * @param level Severity level * @param message Message to be sent */ public static void log(Level level, String message) { logger.log(level, "[PrisonMine] " + message); } public static void formatHelp(String command, String arguments, String description, String node) { if(!arguments.equalsIgnoreCase("")) arguments = " " + arguments; if(Util.hasPermission(node) || node.equals("")) send(ChatColor.GOLD + "/mine " + command + ChatColor.GRAY + arguments + ChatColor.WHITE + " " + description); } public static void formatMessage(String message) { send(" " + message); } public static void formatHelp(String command, String arguments, String description) { formatHelp(command, arguments, description, ""); return; } public static void formatHeader(int padding, String name) { CommandSender sender = CommandManager.getSender(); String spaces = ""; for(int i = 0; i < padding; i++) { spaces = spaces + " "; } sender.sendMessage(spaces + "-=[ " + ChatColor.BLUE + name + ChatColor.WHITE + " ]=-"); } }
true
true
public static void broadcast(String message) { if(message == null) message = ""; message = PrisonMine.getLanguage().GENERAL_SUCCESS + " " + ChatColor.WHITE + message; for (Player p : Bukkit.getServer().getOnlinePlayers()) { p.sendMessage(Util.parseColors(message)); } }
public static void broadcast(String message) { if(message == null) message = ""; message = PrisonMine.getLanguage().GENERAL_SUCCESS + " " + ChatColor.WHITE + message; for (Player p : Bukkit.getServer().getOnlinePlayers()) { if(p.hasPermission("mcprison.mine.reset.broadcast")) p.sendMessage(Util.parseColors(message)); } }
diff --git a/SeriesGuide/src/com/battlelancer/seriesguide/ui/BaseNavDrawerActivity.java b/SeriesGuide/src/com/battlelancer/seriesguide/ui/BaseNavDrawerActivity.java index 4fc6f69d2..b7d81b5f4 100644 --- a/SeriesGuide/src/com/battlelancer/seriesguide/ui/BaseNavDrawerActivity.java +++ b/SeriesGuide/src/com/battlelancer/seriesguide/ui/BaseNavDrawerActivity.java @@ -1,105 +1,105 @@ /* * Copyright 2012 Uwe Trottmann * * 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.battlelancer.seriesguide.ui; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import com.uwetrottmann.seriesguide.R; import net.simonvt.menudrawer.MenuDrawer; import net.simonvt.menudrawer.MenuDrawer.OnDrawerStateChangeListener; /** * Adds onto {@link BaseActivity} by attaching a navigation drawer. */ public abstract class BaseNavDrawerActivity extends BaseActivity { private MenuDrawer mMenuDrawer; @Override protected void onCreate(Bundle arg0) { // set a theme based on user preference setTheme(SeriesGuidePreferences.THEME); super.onCreate(arg0); setupNavDrawer(); } /** * Attaches the {@link MenuDrawer}. */ private void setupNavDrawer() { mMenuDrawer = getAttachedMenuDrawer(); mMenuDrawer.setTouchMode(MenuDrawer.TOUCH_MODE_BEZEL); // setting size in pixels, oh come on... int menuSize = (int) getResources().getDimension(R.dimen.slidingmenu_width); mMenuDrawer.setMenuSize(menuSize); mMenuDrawer.setOnDrawerStateChangeListener(new OnDrawerStateChangeListener() { @Override public void onDrawerStateChange(int oldState, int newState) { // helps hiding actions when the drawer is open if (newState == MenuDrawer.STATE_CLOSED || newState == MenuDrawer.STATE_OPEN) { supportInvalidateOptionsMenu(); } } @Override public void onDrawerSlide(float openRatio, int offsetPixels) { } }); FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); Fragment f = new SlidingMenuFragment(); - ft.replace(R.id.menu_frame, f); + ft.add(R.id.menu_frame, f); ft.commit(); } /* * Creates an {@link MenuDrawer} attached to this activity as an overlay. * Subclasses may override this to set their own layout and drawer type. */ protected MenuDrawer getAttachedMenuDrawer() { MenuDrawer menuDrawer = MenuDrawer.attach(this, MenuDrawer.Type.OVERLAY); menuDrawer.setMenuView(R.layout.menu_frame); return menuDrawer; } @Override public void onBackPressed() { // close an open menu first final int drawerState = mMenuDrawer.getDrawerState(); if (drawerState == MenuDrawer.STATE_OPEN || drawerState == MenuDrawer.STATE_OPENING) { mMenuDrawer.closeMenu(); return; } super.onBackPressed(); } protected MenuDrawer getMenu() { return mMenuDrawer; } protected void toggleMenu() { mMenuDrawer.toggleMenu(); } }
true
true
private void setupNavDrawer() { mMenuDrawer = getAttachedMenuDrawer(); mMenuDrawer.setTouchMode(MenuDrawer.TOUCH_MODE_BEZEL); // setting size in pixels, oh come on... int menuSize = (int) getResources().getDimension(R.dimen.slidingmenu_width); mMenuDrawer.setMenuSize(menuSize); mMenuDrawer.setOnDrawerStateChangeListener(new OnDrawerStateChangeListener() { @Override public void onDrawerStateChange(int oldState, int newState) { // helps hiding actions when the drawer is open if (newState == MenuDrawer.STATE_CLOSED || newState == MenuDrawer.STATE_OPEN) { supportInvalidateOptionsMenu(); } } @Override public void onDrawerSlide(float openRatio, int offsetPixels) { } }); FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); Fragment f = new SlidingMenuFragment(); ft.replace(R.id.menu_frame, f); ft.commit(); }
private void setupNavDrawer() { mMenuDrawer = getAttachedMenuDrawer(); mMenuDrawer.setTouchMode(MenuDrawer.TOUCH_MODE_BEZEL); // setting size in pixels, oh come on... int menuSize = (int) getResources().getDimension(R.dimen.slidingmenu_width); mMenuDrawer.setMenuSize(menuSize); mMenuDrawer.setOnDrawerStateChangeListener(new OnDrawerStateChangeListener() { @Override public void onDrawerStateChange(int oldState, int newState) { // helps hiding actions when the drawer is open if (newState == MenuDrawer.STATE_CLOSED || newState == MenuDrawer.STATE_OPEN) { supportInvalidateOptionsMenu(); } } @Override public void onDrawerSlide(float openRatio, int offsetPixels) { } }); FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); Fragment f = new SlidingMenuFragment(); ft.add(R.id.menu_frame, f); ft.commit(); }
diff --git a/org.dawnsci.plotting.tools/src/org/dawnsci/plotting/tools/InfoPixelLabelProvider.java b/org.dawnsci.plotting.tools/src/org/dawnsci/plotting/tools/InfoPixelLabelProvider.java index 088a73162..699cfdf87 100644 --- a/org.dawnsci.plotting.tools/src/org/dawnsci/plotting/tools/InfoPixelLabelProvider.java +++ b/org.dawnsci.plotting.tools/src/org/dawnsci/plotting/tools/InfoPixelLabelProvider.java @@ -1,201 +1,201 @@ /* * Copyright 2012 Diamond Light Source Ltd. * * 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. */ /* * Copyright 2012 Diamond Light Source Ltd. * * 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.dawnsci.plotting.tools; import org.dawnsci.plotting.api.region.IRegion; import org.dawnsci.plotting.api.region.IRegion.RegionType; import org.dawnsci.plotting.api.tool.IToolPage.ToolPageRole; import org.dawnsci.plotting.api.trace.IImageTrace; import org.dawnsci.plotting.api.trace.TraceUtils; import org.eclipse.jface.viewers.ColumnLabelProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.ac.diamond.scisoft.analysis.dataset.AbstractDataset; import uk.ac.diamond.scisoft.analysis.diffraction.DetectorProperties; import uk.ac.diamond.scisoft.analysis.diffraction.DiffractionCrystalEnvironment; import uk.ac.diamond.scisoft.analysis.diffraction.QSpace; import uk.ac.diamond.scisoft.analysis.io.IDiffractionMetadata; import uk.ac.diamond.scisoft.analysis.io.IMetaData; import uk.ac.diamond.scisoft.analysis.roi.PointROI; public class InfoPixelLabelProvider extends ColumnLabelProvider { private final int column; private final InfoPixelTool tool; private static final Logger logger = LoggerFactory.getLogger(InfoPixelLabelProvider.class); public InfoPixelLabelProvider(InfoPixelTool tool, int i) { this.column = i; this.tool = tool; } @Override public String getText(Object element) { //TODO could use ToolPageRole on the tool to separate 1D and 2D cases better double xIndex = 0.0; double yIndex = 0.0; double xLabel = Double.NaN; double yLabel = Double.NaN; final IImageTrace trace = tool.getImageTrace(); try { if (element instanceof IRegion){ final IRegion region = (IRegion)element; if (region.getRegionType()==RegionType.POINT) { PointROI pr = (PointROI)tool.getBounds(region); xIndex = pr.getPointX(); yIndex = pr.getPointY(); // Sometimes the image can have axes set. In this case we need the point // ROI in the axes coordinates if (trace!=null) { try { pr = (PointROI)trace.getRegionInAxisCoordinates(pr); xLabel = pr.getPointX(); yLabel = pr.getPointY(); } catch (Exception aie) { return "-"; } } } else { xIndex = tool.getXValues()[0]; yIndex = tool.getYValues()[0]; - final double[] dp = new double[]{tool.getXValues()[0], tool.getXValues()[0]}; + final double[] dp = new double[]{xIndex, yIndex}; try { if (trace!=null) trace.getPointInAxisCoordinates(dp); xLabel = dp[0]; yLabel = dp[1]; } catch (Exception aie) { return "-"; } } }else { return null; } if (Double.isNaN(xLabel)) xLabel = xIndex; if (Double.isNaN(yLabel)) yLabel = yIndex; IDiffractionMetadata dmeta = null; AbstractDataset set = null; if (trace!=null) { set = (AbstractDataset)trace.getData(); final IMetaData meta = set.getMetadata(); if (meta instanceof IDiffractionMetadata) { dmeta = (IDiffractionMetadata)meta; } } QSpace qSpace = null; Vector3dutil vectorUtil= null; if (dmeta != null) { try { DetectorProperties detector2dProperties = dmeta.getDetector2DProperties(); DiffractionCrystalEnvironment diffractionCrystalEnvironment = dmeta.getDiffractionCrystalEnvironment(); if (!(detector2dProperties == null)){ qSpace = new QSpace(detector2dProperties, diffractionCrystalEnvironment); vectorUtil = new Vector3dutil(qSpace, xIndex, yIndex); } } catch (Exception e) { logger.error("Could not create a detector properties object from metadata", e); } } final boolean isCustom = TraceUtils.isCustomAxes(trace) || tool.getToolPageRole() == ToolPageRole.ROLE_1D; switch(column) { case 0: // "Point Id" return ( ( (IRegion)element).getRegionType() == RegionType.POINT) ? ((IRegion)element).getName(): ""; case 1: // "X position" return isCustom ? String.format("% 4.4f", xLabel) : String.format("% 4d", (int)Math.floor(xLabel)); case 2: // "Y position" return isCustom ? String.format("% 4.4f", yLabel) : String.format("% 4d", (int)Math.floor(yLabel)); case 3: // "Data value" //if (set == null || vectorUtil==null || vectorUtil.getQMask(qSpace, x, y) == null) return "-"; if (set == null) return "-"; return String.format("% 4.4f", set.getDouble((int)Math.floor(yIndex), (int) Math.floor(xIndex))); case 4: // q X //if (vectorUtil==null || vectorUtil.getQMask(qSpace, x, y) == null) return "-"; if (vectorUtil==null ) return "-"; return String.format("% 4.4f", vectorUtil.getQx()); case 5: // q Y //if (vectorUtil==null ||vectorUtil.getQMask(qSpace, x, y) == null) return "-"; if (vectorUtil==null) return "-"; return String.format("% 4.4f", vectorUtil.getQy()); case 6: // q Z //if (vectorUtil==null ||vectorUtil.getQMask(qSpace, x, y) == null) return "-"; if (vectorUtil==null) return "-"; return String.format("% 4.4f", vectorUtil.getQz()); case 7: // 20 if (vectorUtil==null || qSpace == null) return "-"; return String.format("% 3.3f", Math.toDegrees(vectorUtil.getQScatteringAngle(qSpace))); case 8: // resolution //if (vectorUtil==null ||vectorUtil.getQMask(qSpace, x, y) == null) return "-"; if (vectorUtil==null ) return "-"; return String.format("% 4.4f", (2*Math.PI)/vectorUtil.getQlength()); case 9: // Dataset name if (set == null) return "-"; return set.getName(); default: return "Not found"; } } catch (Throwable ne) { // Must not throw anything from this method - user sees millions of messages! logger.error("Cannot get label!", ne); return ""; } } @Override public String getToolTipText(Object element) { return "Any selection region can be used in information box tool."; } }
true
true
public String getText(Object element) { //TODO could use ToolPageRole on the tool to separate 1D and 2D cases better double xIndex = 0.0; double yIndex = 0.0; double xLabel = Double.NaN; double yLabel = Double.NaN; final IImageTrace trace = tool.getImageTrace(); try { if (element instanceof IRegion){ final IRegion region = (IRegion)element; if (region.getRegionType()==RegionType.POINT) { PointROI pr = (PointROI)tool.getBounds(region); xIndex = pr.getPointX(); yIndex = pr.getPointY(); // Sometimes the image can have axes set. In this case we need the point // ROI in the axes coordinates if (trace!=null) { try { pr = (PointROI)trace.getRegionInAxisCoordinates(pr); xLabel = pr.getPointX(); yLabel = pr.getPointY(); } catch (Exception aie) { return "-"; } } } else { xIndex = tool.getXValues()[0]; yIndex = tool.getYValues()[0]; final double[] dp = new double[]{tool.getXValues()[0], tool.getXValues()[0]}; try { if (trace!=null) trace.getPointInAxisCoordinates(dp); xLabel = dp[0]; yLabel = dp[1]; } catch (Exception aie) { return "-"; } } }else { return null; } if (Double.isNaN(xLabel)) xLabel = xIndex; if (Double.isNaN(yLabel)) yLabel = yIndex; IDiffractionMetadata dmeta = null; AbstractDataset set = null; if (trace!=null) { set = (AbstractDataset)trace.getData(); final IMetaData meta = set.getMetadata(); if (meta instanceof IDiffractionMetadata) { dmeta = (IDiffractionMetadata)meta; } } QSpace qSpace = null; Vector3dutil vectorUtil= null; if (dmeta != null) { try { DetectorProperties detector2dProperties = dmeta.getDetector2DProperties(); DiffractionCrystalEnvironment diffractionCrystalEnvironment = dmeta.getDiffractionCrystalEnvironment(); if (!(detector2dProperties == null)){ qSpace = new QSpace(detector2dProperties, diffractionCrystalEnvironment); vectorUtil = new Vector3dutil(qSpace, xIndex, yIndex); } } catch (Exception e) { logger.error("Could not create a detector properties object from metadata", e); } } final boolean isCustom = TraceUtils.isCustomAxes(trace) || tool.getToolPageRole() == ToolPageRole.ROLE_1D; switch(column) { case 0: // "Point Id" return ( ( (IRegion)element).getRegionType() == RegionType.POINT) ? ((IRegion)element).getName(): ""; case 1: // "X position" return isCustom ? String.format("% 4.4f", xLabel) : String.format("% 4d", (int)Math.floor(xLabel)); case 2: // "Y position" return isCustom ? String.format("% 4.4f", yLabel) : String.format("% 4d", (int)Math.floor(yLabel)); case 3: // "Data value" //if (set == null || vectorUtil==null || vectorUtil.getQMask(qSpace, x, y) == null) return "-"; if (set == null) return "-"; return String.format("% 4.4f", set.getDouble((int)Math.floor(yIndex), (int) Math.floor(xIndex))); case 4: // q X //if (vectorUtil==null || vectorUtil.getQMask(qSpace, x, y) == null) return "-"; if (vectorUtil==null ) return "-"; return String.format("% 4.4f", vectorUtil.getQx()); case 5: // q Y //if (vectorUtil==null ||vectorUtil.getQMask(qSpace, x, y) == null) return "-"; if (vectorUtil==null) return "-"; return String.format("% 4.4f", vectorUtil.getQy()); case 6: // q Z //if (vectorUtil==null ||vectorUtil.getQMask(qSpace, x, y) == null) return "-"; if (vectorUtil==null) return "-"; return String.format("% 4.4f", vectorUtil.getQz()); case 7: // 20 if (vectorUtil==null || qSpace == null) return "-"; return String.format("% 3.3f", Math.toDegrees(vectorUtil.getQScatteringAngle(qSpace))); case 8: // resolution //if (vectorUtil==null ||vectorUtil.getQMask(qSpace, x, y) == null) return "-"; if (vectorUtil==null ) return "-"; return String.format("% 4.4f", (2*Math.PI)/vectorUtil.getQlength()); case 9: // Dataset name if (set == null) return "-"; return set.getName(); default: return "Not found"; } } catch (Throwable ne) { // Must not throw anything from this method - user sees millions of messages! logger.error("Cannot get label!", ne); return ""; } }
public String getText(Object element) { //TODO could use ToolPageRole on the tool to separate 1D and 2D cases better double xIndex = 0.0; double yIndex = 0.0; double xLabel = Double.NaN; double yLabel = Double.NaN; final IImageTrace trace = tool.getImageTrace(); try { if (element instanceof IRegion){ final IRegion region = (IRegion)element; if (region.getRegionType()==RegionType.POINT) { PointROI pr = (PointROI)tool.getBounds(region); xIndex = pr.getPointX(); yIndex = pr.getPointY(); // Sometimes the image can have axes set. In this case we need the point // ROI in the axes coordinates if (trace!=null) { try { pr = (PointROI)trace.getRegionInAxisCoordinates(pr); xLabel = pr.getPointX(); yLabel = pr.getPointY(); } catch (Exception aie) { return "-"; } } } else { xIndex = tool.getXValues()[0]; yIndex = tool.getYValues()[0]; final double[] dp = new double[]{xIndex, yIndex}; try { if (trace!=null) trace.getPointInAxisCoordinates(dp); xLabel = dp[0]; yLabel = dp[1]; } catch (Exception aie) { return "-"; } } }else { return null; } if (Double.isNaN(xLabel)) xLabel = xIndex; if (Double.isNaN(yLabel)) yLabel = yIndex; IDiffractionMetadata dmeta = null; AbstractDataset set = null; if (trace!=null) { set = (AbstractDataset)trace.getData(); final IMetaData meta = set.getMetadata(); if (meta instanceof IDiffractionMetadata) { dmeta = (IDiffractionMetadata)meta; } } QSpace qSpace = null; Vector3dutil vectorUtil= null; if (dmeta != null) { try { DetectorProperties detector2dProperties = dmeta.getDetector2DProperties(); DiffractionCrystalEnvironment diffractionCrystalEnvironment = dmeta.getDiffractionCrystalEnvironment(); if (!(detector2dProperties == null)){ qSpace = new QSpace(detector2dProperties, diffractionCrystalEnvironment); vectorUtil = new Vector3dutil(qSpace, xIndex, yIndex); } } catch (Exception e) { logger.error("Could not create a detector properties object from metadata", e); } } final boolean isCustom = TraceUtils.isCustomAxes(trace) || tool.getToolPageRole() == ToolPageRole.ROLE_1D; switch(column) { case 0: // "Point Id" return ( ( (IRegion)element).getRegionType() == RegionType.POINT) ? ((IRegion)element).getName(): ""; case 1: // "X position" return isCustom ? String.format("% 4.4f", xLabel) : String.format("% 4d", (int)Math.floor(xLabel)); case 2: // "Y position" return isCustom ? String.format("% 4.4f", yLabel) : String.format("% 4d", (int)Math.floor(yLabel)); case 3: // "Data value" //if (set == null || vectorUtil==null || vectorUtil.getQMask(qSpace, x, y) == null) return "-"; if (set == null) return "-"; return String.format("% 4.4f", set.getDouble((int)Math.floor(yIndex), (int) Math.floor(xIndex))); case 4: // q X //if (vectorUtil==null || vectorUtil.getQMask(qSpace, x, y) == null) return "-"; if (vectorUtil==null ) return "-"; return String.format("% 4.4f", vectorUtil.getQx()); case 5: // q Y //if (vectorUtil==null ||vectorUtil.getQMask(qSpace, x, y) == null) return "-"; if (vectorUtil==null) return "-"; return String.format("% 4.4f", vectorUtil.getQy()); case 6: // q Z //if (vectorUtil==null ||vectorUtil.getQMask(qSpace, x, y) == null) return "-"; if (vectorUtil==null) return "-"; return String.format("% 4.4f", vectorUtil.getQz()); case 7: // 20 if (vectorUtil==null || qSpace == null) return "-"; return String.format("% 3.3f", Math.toDegrees(vectorUtil.getQScatteringAngle(qSpace))); case 8: // resolution //if (vectorUtil==null ||vectorUtil.getQMask(qSpace, x, y) == null) return "-"; if (vectorUtil==null ) return "-"; return String.format("% 4.4f", (2*Math.PI)/vectorUtil.getQlength()); case 9: // Dataset name if (set == null) return "-"; return set.getName(); default: return "Not found"; } } catch (Throwable ne) { // Must not throw anything from this method - user sees millions of messages! logger.error("Cannot get label!", ne); return ""; } }
diff --git a/war-core/src/main/java/com/silverpeas/portlets/portal/SPDesktopServlet.java b/war-core/src/main/java/com/silverpeas/portlets/portal/SPDesktopServlet.java index ab53b62cde..ed3d6d56fc 100644 --- a/war-core/src/main/java/com/silverpeas/portlets/portal/SPDesktopServlet.java +++ b/war-core/src/main/java/com/silverpeas/portlets/portal/SPDesktopServlet.java @@ -1,773 +1,777 @@ /** * Copyright (C) 2000 - 2009 Silverpeas * * This program 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. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "http://repository.silverpeas.com/legal/licensing" * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.silverpeas.portlets.portal; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import javax.servlet.RequestDispatcher; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.silverpeas.util.StringUtil; import com.stratelia.silverpeas.peasCore.MainSessionController; import com.stratelia.silverpeas.peasCore.URLManager; import com.stratelia.silverpeas.silvertrace.SilverTrace; import com.stratelia.webactiv.beans.admin.OrganizationController; import com.stratelia.webactiv.beans.admin.SpaceInst; import com.stratelia.webactiv.util.GeneralPropertiesManager; import com.stratelia.webactiv.util.viewGenerator.html.GraphicElementFactory; import com.sun.portal.container.ChannelMode; import com.sun.portal.container.ChannelState; import com.sun.portal.container.PortletType; import com.sun.portal.portletcontainer.admin.PortletRegistryCache; import com.sun.portal.portletcontainer.admin.registry.PortletRegistryConstants; import com.sun.portal.portletcontainer.context.ServletContextThreadLocalizer; import com.sun.portal.portletcontainer.context.registry.PortletRegistryContext; import com.sun.portal.portletcontainer.context.registry.PortletRegistryException; import com.sun.portal.portletcontainer.invoker.InvokerException; import com.sun.portal.portletcontainer.invoker.WindowInvokerConstants; import com.sun.portal.portletcontainer.invoker.util.InvokerUtil; public class SPDesktopServlet extends HttpServlet { private static final long serialVersionUID = -3241648887903159985L; ServletContext context; String spContext; private static final Logger logger = Logger.getLogger("com.silverpeas.portlets.portal", "com.silverpeas.portlets.PCDLogMessages"); /** * Reads the DriverConfig.properties file. Initializes the Portlet Registry files. * @param config the ServletConfig Object * @throws javax.servlet.ServletException */ @Override public void init(ServletConfig config) throws ServletException { super.init(config); context = config.getServletContext(); PortletRegistryCache.init(); } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { doGetPost(request, response); } catch (Exception e) { logger.log(Level.SEVERE, e.getMessage(), e); } } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGetPost(request, response); } private void doGetPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String spaceHomePage = null; String spaceId = request.getParameter("SpaceId"); if (StringUtil.isDefined(spaceId)) { request.getSession().setAttribute("Silverpeas_Portlet_SpaceId", spaceId); spaceHomePage = getSpaceHomepage(spaceId, request); } if (StringUtil.isDefined(spaceHomePage)) { if (spaceHomePage.startsWith("/")) { // case of forward inside application /silverpeas + String applicationContext = GeneralPropertiesManager.getGeneralResourceLocator().getString("ApplicationURL"); + if (spaceHomePage.startsWith(applicationContext)) { + spaceHomePage = spaceHomePage.substring(applicationContext.length()); + } RequestDispatcher rd = context.getRequestDispatcher(spaceHomePage); rd.forward(request, response); } else { if (spaceHomePage.startsWith("$")) { // case of redirection to another webapp (/weblib for example) String sRequestURL = request.getRequestURL().toString(); String m_sAbsolute = sRequestURL.substring(0, sRequestURL.length() - request.getRequestURI().length()); String baseURL = GeneralPropertiesManager.getGeneralResourceLocator().getString("httpServerBase", m_sAbsolute); spaceHomePage = baseURL + spaceHomePage.substring(1); } response.sendRedirect(spaceHomePage); } } else { spContext = getUserIdOrSpaceId(request, false); setUserIdAndSpaceIdInRequest(request); DesktopMessages.init(request); SilverTrace.debug("portlet", "SPDesktopServlet.doGetPost", "root.MSG_GEN_PARAM_VALUE", "DesktopMessages initialized !"); DriverUtil.init(request); SilverTrace.debug("portlet", "SPDesktopServlet.doGetPost", "root.MSG_GEN_PARAM_VALUE", "DriverUtil initialized !"); response.setContentType("text/html;charset=UTF-8"); // Get the list of visible portlets(sorted by the row number) try { ServletContextThreadLocalizer.set(context); PortletRegistryContext portletRegistryContext = DriverUtil.getPortletRegistryContext(spContext); SilverTrace.debug("portlet", "SPDesktopServlet.doGetPost", "root.MSG_GEN_PARAM_VALUE", "portletRegistryContext retrieved !"); PortletContent portletContent = getPortletContentObject(context, request, response); String portletWindowName = DriverUtil.getPortletWindowFromRequest(request); String portletRemove = DriverUtil.getPortletRemove(request); if (portletRemove != null && portletWindowName != null) { portletRegistryContext.removePortletWindow(portletWindowName); // portletRegistryContext.showPortletWindow(portletWindowName, false); portletWindowName = null; // re-render all portlets } Map portletContents = null; if (portletWindowName == null) { portletContents = getAllPortletContents(request, portletContent, portletRegistryContext); } else { String driverAction = DriverUtil.getDriverAction(request); if (WindowInvokerConstants.ACTION.equals(driverAction)) { URL url = executeProcessAction(request, portletContent); try { if (url != null) { response.sendRedirect(url.toString()); } else { response.sendRedirect(request.getRequestURL().toString()); } } catch (IOException ioe) { throw new InvokerException("Failed during sendRedirect", ioe); } } else if (WindowInvokerConstants.RENDER.equals(driverAction)) { portletContents = getAllPortletContents(request, portletContent, portletRegistryContext); } else if (WindowInvokerConstants.RESOURCE.equals(driverAction)) { portletContent.setPortletWindowName(portletWindowName); ChannelMode portletWindowMode = getCurrentPortletWindowMode(request, portletWindowName); ChannelState portletWindowState = getCurrentPortletWindowState(request, portletWindowName); portletContent.setPortletWindowState(portletWindowState); portletContent.setPortletWindowMode(portletWindowMode); portletContent.getResources(); } } if (portletContents != null) { Map<String, SortedSet<PortletWindowData>> portletWindowContents = getPortletWindowContents(request, portletContents, portletRegistryContext); setPortletWindowData(request, portletWindowContents); InvokerUtil.setResponseProperties(request, response, portletContent .getResponseProperties()); RequestDispatcher rd = context.getRequestDispatcher(getPresentationURI(request)); rd.forward(request, response); InvokerUtil.clearResponseProperties(portletContent.getResponseProperties()); } } catch (Exception e) { SilverTrace.error("portlet", "SPDesktopServlet.doGetPost", "root.MSG_GEN_PARAM_VALUE", "Portlets exception !", e); } finally { ServletContextThreadLocalizer.set(null); } } } /** * Returns the PortletWindowData object for the portlet window. A Set of PortletWindowData for all * portlet windows is stored in the Session. * @param request the HttpServletRequest Object * @param portletWindowName the name of the portlet window * @return the PortletWindowData object for the portlet window. */ private PortletWindowData getPortletWindowData(HttpServletRequest request, String portletWindowName) { HttpSession session = request.getSession(true); PortletWindowData portletWindowData = null; @SuppressWarnings("unchecked") Map<String, SortedSet<PortletWindowData>> portletWindowContents = (Map<String, SortedSet<PortletWindowData>>) session.getAttribute( DesktopConstants.PORTLET_WINDOWS); boolean found = false; if (portletWindowContents != null) { Set<Map.Entry<String, SortedSet<PortletWindowData>>> set = portletWindowContents.entrySet(); Iterator<Map.Entry<String, SortedSet<PortletWindowData>>> setItr = set.iterator(); while (setItr.hasNext()) { Map.Entry<String, SortedSet<PortletWindowData>> mapEntry = setItr.next(); SortedSet<PortletWindowData> portletWindowDataSet = mapEntry.getValue(); for (Iterator<PortletWindowData> itr = portletWindowDataSet.iterator(); itr.hasNext();) { portletWindowData = itr.next(); if (portletWindowName.equals(portletWindowData.getPortletWindowName())) { found = true; break; } } if (found) { break; } } } if (found) { return portletWindowData; } else { return null; } } private void setPortletWindowData(HttpServletRequest request, Map<String, SortedSet<PortletWindowData>> portletWindowContents) { HttpSession session = request.getSession(true); session.removeAttribute(DesktopConstants.PORTLET_WINDOWS); session.setAttribute(DesktopConstants.PORTLET_WINDOWS, portletWindowContents); } /** * Returns a Map of portlet data and title for all portlet windows. In the portlet window is * maximized, only the data and title for that portlet is displayed. For any portlet window that * is minimized , only the title is shown. * @param request the HttpServletRequest Object * @param portletContent the PortletContent Object * @param portletRegistryContext the PortletRegistryContext Object * @return a Map of portlet data and title for all portlet windows. */ private Map getAllPortletContents(HttpServletRequest request, PortletContent portletContent, PortletRegistryContext portletRegistryContext) throws InvokerException { String portletWindowName = DriverUtil.getPortletWindowFromRequest(request); ChannelState portletWindowState = getCurrentPortletWindowState(request, portletWindowName); Map portletContents; if (portletWindowState.equals(ChannelState.MAXIMIZED)) { portletContent.setPortletWindowState(ChannelState.MAXIMIZED); portletContents = getPortletContent(request, portletContent, portletWindowName); } else { List visiblePortletWindows = getVisiblePortletWindows(portletRegistryContext); int numPortletWindows = visiblePortletWindows.size(); List portletList = new ArrayList(); List portletMinimizedList = new ArrayList(); for (int i = 0; i < numPortletWindows; i++) { portletWindowName = (String) visiblePortletWindows.get(i); portletWindowState = getCurrentPortletWindowState(request, portletWindowName); if (portletWindowState.equals(ChannelState.MINIMIZED)) { portletMinimizedList.add(portletWindowName); } else { portletList.add(portletWindowName); } } portletContents = getPortletContents(request, portletContent, portletList); if (!portletMinimizedList.isEmpty()) { Map portletTitles = getPortletTitles(request, portletContent, portletMinimizedList); portletContents.putAll(portletTitles); } } return portletContents; } /** * Returns a Map of portlet data and title for a portlet window. * @param request the HttpServletRequest Object * @param portletContent the PortletContent Object * @param portletWindowName the name of the portlet window * @return a Map of portlet data and title for a portlet window. */ private Map getPortletContent(HttpServletRequest request, PortletContent portletContent, String portletWindowName) throws InvokerException { portletContent.setPortletWindowName(portletWindowName); ChannelMode portletWindowMode = getCurrentPortletWindowMode(request, portletWindowName); portletContent.setPortletWindowMode(portletWindowMode); StringBuffer buffer = portletContent.getContent(); String title = portletContent.getTitle(); Map portletContents = new HashMap(); portletContents.put(DesktopConstants.PORTLET_CONTENT, buffer); portletContents.put(DesktopConstants.PORTLET_TITLE, title); Map portletContentMap = new HashMap(); portletContentMap.put(portletWindowName, portletContents); return portletContentMap; } /** * Returns a Map of portlet data and title for the portlet windows specified in the portletList * @param request the HttpServletRequest Object * @param portletContent the PortletContent Cobject * @param portletList the List of portlet windows * @return a Map of portlet data and title for the portlet windows specified in the portletList */ private Map getPortletContents(HttpServletRequest request, PortletContent portletContent, List portletList) throws InvokerException { String portletWindowName; int numPortletWindows = portletList.size(); Map portletContentMap = new HashMap(); for (int i = 0; i < numPortletWindows; i++) { portletWindowName = (String) portletList.get(i); portletContent.setPortletWindowName(portletWindowName); portletContent.setPortletWindowMode(getCurrentPortletWindowMode(request, portletWindowName)); portletContent .setPortletWindowState(getCurrentPortletWindowState(request, portletWindowName)); StringBuffer buffer; try { buffer = portletContent.getContent(); } catch (InvokerException ie) { buffer = new StringBuffer(ie.getMessage()); } String title = null; try { title = portletContent.getTitle(); } catch (InvokerException iex) { // Just logging if (logger.isLoggable(Level.SEVERE)) { LogRecord logRecord = new LogRecord(Level.SEVERE, "PSPCD_CSPPD0048"); logRecord.setLoggerName(logger.getName()); logRecord.setThrown(iex); logRecord.setParameters(new String[] { portletWindowName }); logger.log(logRecord); } title = ""; } Map portletContents = new HashMap(); portletContents.put(DesktopConstants.PORTLET_CONTENT, buffer); portletContents.put(DesktopConstants.PORTLET_TITLE, title); portletContentMap.put(portletWindowName, portletContents); } return portletContentMap; } /** * Returns a Map of portlet title for the portlet windows specified in the portletMinimizedList * @param request the HttpServletRequest Object * @param portletContent the PortletContent Cobject * @param portletMinimizedList the List of portlet windows that are minimized * @return a Map of portlet title for the portlet windows that are minimized. */ private Map getPortletTitles(HttpServletRequest request, PortletContent portletContent, List portletMinimizedList) throws InvokerException { String portletWindowName; int numPortletWindows = portletMinimizedList.size(); Map portletTitlesMap = new HashMap(); for (int i = 0; i < numPortletWindows; i++) { portletWindowName = (String) portletMinimizedList.get(i); portletContent.setPortletWindowName(portletWindowName); portletContent.setPortletWindowMode(getCurrentPortletWindowMode(request, portletWindowName)); portletContent .setPortletWindowState(getCurrentPortletWindowState(request, portletWindowName)); String title = portletContent.getDefaultTitle(); Map portletContents = new HashMap(); portletContents.put(DesktopConstants.PORTLET_CONTENT, null); portletContents.put(DesktopConstants.PORTLET_TITLE, title); portletTitlesMap.put(portletWindowName, portletContents); } return portletTitlesMap; } /** * Returns a Map of PortletWindowData for the portlet windows for both thick and think widths. * @param request the HttpServletRequest Object * @param portletContents a Map of portlet data and title for the portlet windows * @param portletRegistryContext the PortletRegistryContext Object * @return a Map of PortletWindowData for the portlet windows */ private Map<String, SortedSet<PortletWindowData>> getPortletWindowContents( HttpServletRequest request, Map portletContents, PortletRegistryContext portletRegistryContext) { Iterator itr = portletContents.keySet().iterator(); String portletWindowName; SortedSet<PortletWindowData> portletWindowContentsThin = new TreeSet<PortletWindowData>(); SortedSet<PortletWindowData> portletWindowContentsThick = new TreeSet<PortletWindowData>(); int thinCount = 0; int thickCount = 0; while (itr.hasNext()) { portletWindowName = (String) itr.next(); try { PortletWindowData portletWindowData = getPortletWindowDataObject(request, portletContents, portletRegistryContext, portletWindowName); if (portletWindowData.isThin()) { portletWindowContentsThin.add(portletWindowData); thinCount++; } else if (portletWindowData.isThick()) { portletWindowContentsThick.add(portletWindowData); thickCount++; } else { throw new PortletRegistryException(portletWindowName + " is neither thick or thin!!"); } } catch (PortletRegistryException pre) { logger.log(Level.SEVERE, pre.getMessage(), pre); } } Map portletWindowContents = new HashMap(); portletWindowContents.put(PortletRegistryConstants.WIDTH_THICK, portletWindowContentsThick); portletWindowContents.put(PortletRegistryConstants.WIDTH_THIN, portletWindowContentsThin); logger.log(Level.INFO, "PSPCD_CSPPD0022", new String[] { String.valueOf(thinCount), String.valueOf(thickCount) }); return portletWindowContents; } private URL executeProcessAction(HttpServletRequest request, PortletContent portletContent) throws InvokerException { String portletWindowName = DriverUtil.getPortletWindowFromRequest(request); ChannelMode portletWindowMode = DriverUtil.getPortletWindowModeOfPortletWindow(request, portletWindowName); ChannelState portletWindowState = DriverUtil.getPortletWindowStateOfPortletWindow(request, portletWindowName); portletContent.setPortletWindowName(portletWindowName); portletContent.setPortletWindowMode(portletWindowMode); portletContent.setPortletWindowState(portletWindowState); URL url = portletContent.executeAction(); return url; } /** * Returns the list of visible portlet windows from the portlet registry. * @param portletRegistryContext the PortletRegistryContext Object * @return the list of visible portlet windows from the portlet registry. */ protected List getVisiblePortletWindows(PortletRegistryContext portletRegistryContext) throws InvokerException { List visiblePortletWindows = null; try { visiblePortletWindows = portletRegistryContext.getVisiblePortletWindows(PortletType.LOCAL); } catch (PortletRegistryException pre) { visiblePortletWindows = Collections.EMPTY_LIST; throw new InvokerException("Cannot get Portlet List", pre); } return visiblePortletWindows; } /** * Returns the current portlet window state for the portlet window. First it checks in the request * and then checks in the session. * @param request the HttpServletRequest Object * @param portletWindowName the name of the portlet window * @return the current portlet window state for the portlet window. */ protected ChannelState getCurrentPortletWindowState(HttpServletRequest request, String portletWindowName) { ChannelState portletWindowState = ChannelState.NORMAL; if (portletWindowName != null) { portletWindowState = DriverUtil.getPortletWindowStateOfPortletWindow(request, portletWindowName); if (portletWindowState == null) { portletWindowState = getPortletWindowStateFromSavedData(request, portletWindowName); } } return portletWindowState; } /** * Returns the current portlet window mode for the portlet window. First it checks in the request * and then checks in the session. * @param request the HttpServletRequest Object * @param portletWindowName the name of the portlet window * @return the current portlet window mode for the portlet window. */ protected ChannelMode getCurrentPortletWindowMode(HttpServletRequest request, String portletWindowName) { ChannelMode portletWindowMode = ChannelMode.VIEW; if (portletWindowName != null) { portletWindowMode = DriverUtil.getPortletWindowModeOfPortletWindow(request, portletWindowName); if (portletWindowMode == null) { portletWindowMode = getPortletWindowModeFromSavedData(request, portletWindowName); } } return portletWindowMode; } /** * Returns the portlet window state for the portlet window from the PortletWindowData that is in * the session. * @param request the HttpServletRequest Object * @param portletWindowName the name of the portlet window * @return the portlet window state for the portlet window from session. */ protected ChannelState getPortletWindowStateFromSavedData(HttpServletRequest request, String portletWindowName) { PortletWindowData portletWindowContent = getPortletWindowData(request, portletWindowName); ChannelState portletWindowState = ChannelState.NORMAL; if (portletWindowContent != null) { String currentPortletWindowState = portletWindowContent.getCurrentWindowState(); if (currentPortletWindowState != null) { portletWindowState = new ChannelState(currentPortletWindowState); } } return portletWindowState; } /** * Returns the portlet window mode for the portlet window from the PortletWindowData that is in * the session. * @param request the HttpServletRequest Object * @param portletWindowName the name of the portlet window * @return the portlet window mode for the portlet window from session. */ protected ChannelMode getPortletWindowModeFromSavedData(HttpServletRequest request, String portletWindowName) { PortletWindowData portletWindowContent = getPortletWindowData(request, portletWindowName); ChannelMode portletWindowMode = ChannelMode.VIEW; if (portletWindowContent != null) { String currentPortletWindowMode = portletWindowContent.getCurrentMode(); if (currentPortletWindowMode != null) { portletWindowMode = new ChannelMode(currentPortletWindowMode); } } return portletWindowMode; } protected PortletContent getPortletContentObject(ServletContext context, HttpServletRequest request, HttpServletResponse response) throws InvokerException { return new PortletContent(context, request, response); } protected PortletWindowData getPortletWindowDataObject(HttpServletRequest request, Map portletContents, PortletRegistryContext portletRegistryContext, String portletWindowName) throws PortletRegistryException { PortletWindowDataImpl portletWindowData = new PortletWindowDataImpl(); Map portletContentMap = (Map) portletContents.get(portletWindowName); portletWindowData.init(request, portletRegistryContext, portletWindowName); portletWindowData.setContent((StringBuffer) portletContentMap .get(DesktopConstants.PORTLET_CONTENT)); portletWindowData.setTitle((String) portletContentMap.get(DesktopConstants.PORTLET_TITLE)); portletWindowData.setCurrentMode(getCurrentPortletWindowMode(request, portletWindowName)); portletWindowData .setCurrentWindowState(getCurrentPortletWindowState(request, portletWindowName)); if (spContext.startsWith("space")) portletWindowData.setSpaceId(getUserIdOrSpaceId(request, true)); if (isSpaceFrontOffice(request) || isAnonymousUser(request)) { portletWindowData.setEdit(false); portletWindowData.setHelp(false); portletWindowData.setRemove(false); portletWindowData.setRole(null); } else { portletWindowData.setRole("admin"); } return portletWindowData; } protected String getPresentationURI(HttpServletRequest request) { String spaceId = getSpaceId(request); if (!StringUtil.isDefined(spaceId) || isSpaceBackOffice(request)) { request.setAttribute("SpaceId", spaceId); if (isAnonymousUser(request)) request.setAttribute("DisableMove", Boolean.TRUE); return "/portlet/jsp/jsr/desktop.jsp"; } else { request.setAttribute("DisableMove", Boolean.TRUE); return "/portlet/jsp/jsr/spaceDesktop.jsp"; } } private boolean isAnonymousUser(HttpServletRequest request) { HttpSession session = request.getSession(); MainSessionController m_MainSessionCtrl = (MainSessionController) session.getAttribute("SilverSessionController"); GraphicElementFactory gef = (GraphicElementFactory) session.getAttribute("SessionGraphicElementFactory"); return m_MainSessionCtrl.getUserId().equals(gef.getFavoriteLookSettings().getString("guestId")); } private void setUserIdAndSpaceIdInRequest(HttpServletRequest request) { String spaceId = getSpaceId(request); request.setAttribute("SpaceId", spaceId); request.setAttribute("UserId", getMainSessionController(request).getUserId()); SilverTrace.debug("portlet", "SPDesktopServlet.setUserIdAndSpaceIdInRequest", "userId = " + getMainSessionController(request).getUserId()); } private String getUserIdOrSpaceId(HttpServletRequest request, boolean getSpaceIdOnly) { String spaceId = getSpaceId(request); if (StringUtil.isDefined(spaceId)) return spaceId; return getMainSessionController(request).getUserId(); } private String prefixSpaceId(String spaceId) { if (StringUtil.isDefined(spaceId)) { // Display the space homepage if (spaceId.startsWith("WA")) spaceId = spaceId.substring("WA".length()); if (!spaceId.startsWith("space")) spaceId = "space" + spaceId; } return spaceId; } private String unprefixSpaceId(String spaceId) { if (StringUtil.isDefined(spaceId)) { spaceId = spaceId.substring("space".length()); } return spaceId; } private String getSpaceId(HttpServletRequest request) { String spaceId = request.getParameter(WindowInvokerConstants.DRIVER_SPACEID); if (!StringUtil.isDefined(spaceId)) { spaceId = request.getParameter("SpaceId"); if (StringUtil.isDefined(spaceId)) { MainSessionController m_MainSessionCtrl = getMainSessionController(request); SpaceInst spaceStruct = m_MainSessionCtrl.getOrganizationController().getSpaceInstById(spaceId); // Page d'accueil de l'espace = Portlet ? if (spaceStruct == null || spaceStruct.getFirstPageType() != SpaceInst.FP_TYPE_PORTLET) spaceId = null; } } return prefixSpaceId(spaceId); } private MainSessionController getMainSessionController(HttpServletRequest request) { HttpSession session = request.getSession(); MainSessionController m_MainSessionCtrl = (MainSessionController) session.getAttribute("SilverSessionController"); return m_MainSessionCtrl; } private OrganizationController getOrganizationController(HttpServletRequest request) { return getMainSessionController(request).getOrganizationController(); } private boolean isSpaceBackOffice(HttpServletRequest request) { return (StringUtil.isDefined(getSpaceId(request)) && "admin".equalsIgnoreCase(request .getParameter(WindowInvokerConstants.DRIVER_ROLE))); } private boolean isSpaceFrontOffice(HttpServletRequest request) { return (StringUtil.isDefined(getSpaceId(request)) && !StringUtil.isDefined(request .getParameter(WindowInvokerConstants.DRIVER_ROLE))); } private String getSpaceHomepage(String spaceId, HttpServletRequest request) throws UnsupportedEncodingException { OrganizationController organizationCtrl = getOrganizationController(request); SpaceInst spaceStruct = organizationCtrl.getSpaceInstById(spaceId); if (spaceStruct != null) { MainSessionController m_MainSessionCtrl = getMainSessionController(request); String userId = m_MainSessionCtrl.getUserId(); // Maintenance Mode if (m_MainSessionCtrl.isSpaceInMaintenance(spaceId) && m_MainSessionCtrl.getUserAccessLevel().equals("U")) return GeneralPropertiesManager.getGeneralResourceLocator().getString("ApplicationURL") + "/admin/jsp/spaceInMaintenance.jsp"; // Page d'accueil de l'espace = Composant if (spaceStruct.getFirstPageType() == SpaceInst.FP_TYPE_COMPONENT_INST && StringUtil.isDefined(spaceStruct.getFirstPageExtraParam())) { String componentId = spaceStruct.getFirstPageExtraParam(); if (organizationCtrl.isComponentAvailable(componentId, userId)) { return GeneralPropertiesManager.getGeneralResourceLocator().getString("ApplicationURL") + URLManager.getURL("useless", componentId) + "Main"; } } // Page d'accueil de l'espace = URL if (spaceStruct.getFirstPageType() == SpaceInst.FP_TYPE_HTML_PAGE && StringUtil.isDefined(spaceStruct.getFirstPageExtraParam())) { String s_sUserLogin = "%ST_USER_LOGIN%"; String s_sUserPassword = "%ST_USER_PASSWORD%"; String s_sUserEmail = "%ST_USER_EMAIL%"; String s_sUserFirstName = "%ST_USER_FIRSTNAME%"; String s_sUserLastName = "%ST_USER_LASTNAME%"; String s_sUserFullName = "%ST_USER_FULLNAME%"; String s_sUserId = "%ST_USER_ID%"; String s_sSessionId = "%ST_SESSION_ID%"; String destination = spaceStruct.getFirstPageExtraParam(); destination = getParsedDestination(destination, s_sUserLogin, m_MainSessionCtrl .getCurrentUserDetail().getLogin()); destination = getParsedDestination(destination, s_sUserFullName, URLEncoder.encode(m_MainSessionCtrl .getCurrentUserDetail().getDisplayedName(), "UTF-8")); destination = getParsedDestination(destination, s_sUserId, URLEncoder.encode(m_MainSessionCtrl .getUserId(), "UTF-8")); destination = getParsedDestination(destination, s_sSessionId, URLEncoder.encode(request.getSession() .getId(), "UTF-8")); destination = getParsedDestination(destination, s_sUserEmail, m_MainSessionCtrl .getCurrentUserDetail().geteMail()); destination = getParsedDestination(destination, s_sUserFirstName, URLEncoder.encode(m_MainSessionCtrl .getCurrentUserDetail().getFirstName(), "UTF-8")); destination = getParsedDestination(destination, s_sUserLastName, URLEncoder.encode(m_MainSessionCtrl .getCurrentUserDetail().getLastName(), "UTF-8")); // !!!! Add the password : this is an uggly patch that use a session variable set in the // "AuthenticationServlet" servlet destination = this.getParsedDestination(destination, s_sUserPassword, (String) request.getSession() .getAttribute("Silverpeas_pwdForHyperlink")); return destination; } } return null; } private String getParsedDestination(String sDestination, String sKeyword, String sValue) { int nLoginIndex = sDestination.indexOf(sKeyword); if (nLoginIndex != -1) { // Replace the keyword with the actual value String sParsed = sDestination.substring(0, nLoginIndex); sParsed += sValue; if (sDestination.length() > nLoginIndex + sKeyword.length()) sParsed += sDestination.substring( nLoginIndex + sKeyword.length(), sDestination.length()); sDestination = sParsed; } return sDestination; } }
true
true
private void doGetPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String spaceHomePage = null; String spaceId = request.getParameter("SpaceId"); if (StringUtil.isDefined(spaceId)) { request.getSession().setAttribute("Silverpeas_Portlet_SpaceId", spaceId); spaceHomePage = getSpaceHomepage(spaceId, request); } if (StringUtil.isDefined(spaceHomePage)) { if (spaceHomePage.startsWith("/")) { // case of forward inside application /silverpeas RequestDispatcher rd = context.getRequestDispatcher(spaceHomePage); rd.forward(request, response); } else { if (spaceHomePage.startsWith("$")) { // case of redirection to another webapp (/weblib for example) String sRequestURL = request.getRequestURL().toString(); String m_sAbsolute = sRequestURL.substring(0, sRequestURL.length() - request.getRequestURI().length()); String baseURL = GeneralPropertiesManager.getGeneralResourceLocator().getString("httpServerBase", m_sAbsolute); spaceHomePage = baseURL + spaceHomePage.substring(1); } response.sendRedirect(spaceHomePage); } } else { spContext = getUserIdOrSpaceId(request, false); setUserIdAndSpaceIdInRequest(request); DesktopMessages.init(request); SilverTrace.debug("portlet", "SPDesktopServlet.doGetPost", "root.MSG_GEN_PARAM_VALUE", "DesktopMessages initialized !"); DriverUtil.init(request); SilverTrace.debug("portlet", "SPDesktopServlet.doGetPost", "root.MSG_GEN_PARAM_VALUE", "DriverUtil initialized !"); response.setContentType("text/html;charset=UTF-8"); // Get the list of visible portlets(sorted by the row number) try { ServletContextThreadLocalizer.set(context); PortletRegistryContext portletRegistryContext = DriverUtil.getPortletRegistryContext(spContext); SilverTrace.debug("portlet", "SPDesktopServlet.doGetPost", "root.MSG_GEN_PARAM_VALUE", "portletRegistryContext retrieved !"); PortletContent portletContent = getPortletContentObject(context, request, response); String portletWindowName = DriverUtil.getPortletWindowFromRequest(request); String portletRemove = DriverUtil.getPortletRemove(request); if (portletRemove != null && portletWindowName != null) { portletRegistryContext.removePortletWindow(portletWindowName); // portletRegistryContext.showPortletWindow(portletWindowName, false); portletWindowName = null; // re-render all portlets } Map portletContents = null; if (portletWindowName == null) { portletContents = getAllPortletContents(request, portletContent, portletRegistryContext); } else { String driverAction = DriverUtil.getDriverAction(request); if (WindowInvokerConstants.ACTION.equals(driverAction)) { URL url = executeProcessAction(request, portletContent); try { if (url != null) { response.sendRedirect(url.toString()); } else { response.sendRedirect(request.getRequestURL().toString()); } } catch (IOException ioe) { throw new InvokerException("Failed during sendRedirect", ioe); } } else if (WindowInvokerConstants.RENDER.equals(driverAction)) { portletContents = getAllPortletContents(request, portletContent, portletRegistryContext); } else if (WindowInvokerConstants.RESOURCE.equals(driverAction)) { portletContent.setPortletWindowName(portletWindowName); ChannelMode portletWindowMode = getCurrentPortletWindowMode(request, portletWindowName); ChannelState portletWindowState = getCurrentPortletWindowState(request, portletWindowName); portletContent.setPortletWindowState(portletWindowState); portletContent.setPortletWindowMode(portletWindowMode); portletContent.getResources(); } } if (portletContents != null) { Map<String, SortedSet<PortletWindowData>> portletWindowContents = getPortletWindowContents(request, portletContents, portletRegistryContext); setPortletWindowData(request, portletWindowContents); InvokerUtil.setResponseProperties(request, response, portletContent .getResponseProperties()); RequestDispatcher rd = context.getRequestDispatcher(getPresentationURI(request)); rd.forward(request, response); InvokerUtil.clearResponseProperties(portletContent.getResponseProperties()); } } catch (Exception e) { SilverTrace.error("portlet", "SPDesktopServlet.doGetPost", "root.MSG_GEN_PARAM_VALUE", "Portlets exception !", e); } finally { ServletContextThreadLocalizer.set(null); } } }
private void doGetPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String spaceHomePage = null; String spaceId = request.getParameter("SpaceId"); if (StringUtil.isDefined(spaceId)) { request.getSession().setAttribute("Silverpeas_Portlet_SpaceId", spaceId); spaceHomePage = getSpaceHomepage(spaceId, request); } if (StringUtil.isDefined(spaceHomePage)) { if (spaceHomePage.startsWith("/")) { // case of forward inside application /silverpeas String applicationContext = GeneralPropertiesManager.getGeneralResourceLocator().getString("ApplicationURL"); if (spaceHomePage.startsWith(applicationContext)) { spaceHomePage = spaceHomePage.substring(applicationContext.length()); } RequestDispatcher rd = context.getRequestDispatcher(spaceHomePage); rd.forward(request, response); } else { if (spaceHomePage.startsWith("$")) { // case of redirection to another webapp (/weblib for example) String sRequestURL = request.getRequestURL().toString(); String m_sAbsolute = sRequestURL.substring(0, sRequestURL.length() - request.getRequestURI().length()); String baseURL = GeneralPropertiesManager.getGeneralResourceLocator().getString("httpServerBase", m_sAbsolute); spaceHomePage = baseURL + spaceHomePage.substring(1); } response.sendRedirect(spaceHomePage); } } else { spContext = getUserIdOrSpaceId(request, false); setUserIdAndSpaceIdInRequest(request); DesktopMessages.init(request); SilverTrace.debug("portlet", "SPDesktopServlet.doGetPost", "root.MSG_GEN_PARAM_VALUE", "DesktopMessages initialized !"); DriverUtil.init(request); SilverTrace.debug("portlet", "SPDesktopServlet.doGetPost", "root.MSG_GEN_PARAM_VALUE", "DriverUtil initialized !"); response.setContentType("text/html;charset=UTF-8"); // Get the list of visible portlets(sorted by the row number) try { ServletContextThreadLocalizer.set(context); PortletRegistryContext portletRegistryContext = DriverUtil.getPortletRegistryContext(spContext); SilverTrace.debug("portlet", "SPDesktopServlet.doGetPost", "root.MSG_GEN_PARAM_VALUE", "portletRegistryContext retrieved !"); PortletContent portletContent = getPortletContentObject(context, request, response); String portletWindowName = DriverUtil.getPortletWindowFromRequest(request); String portletRemove = DriverUtil.getPortletRemove(request); if (portletRemove != null && portletWindowName != null) { portletRegistryContext.removePortletWindow(portletWindowName); // portletRegistryContext.showPortletWindow(portletWindowName, false); portletWindowName = null; // re-render all portlets } Map portletContents = null; if (portletWindowName == null) { portletContents = getAllPortletContents(request, portletContent, portletRegistryContext); } else { String driverAction = DriverUtil.getDriverAction(request); if (WindowInvokerConstants.ACTION.equals(driverAction)) { URL url = executeProcessAction(request, portletContent); try { if (url != null) { response.sendRedirect(url.toString()); } else { response.sendRedirect(request.getRequestURL().toString()); } } catch (IOException ioe) { throw new InvokerException("Failed during sendRedirect", ioe); } } else if (WindowInvokerConstants.RENDER.equals(driverAction)) { portletContents = getAllPortletContents(request, portletContent, portletRegistryContext); } else if (WindowInvokerConstants.RESOURCE.equals(driverAction)) { portletContent.setPortletWindowName(portletWindowName); ChannelMode portletWindowMode = getCurrentPortletWindowMode(request, portletWindowName); ChannelState portletWindowState = getCurrentPortletWindowState(request, portletWindowName); portletContent.setPortletWindowState(portletWindowState); portletContent.setPortletWindowMode(portletWindowMode); portletContent.getResources(); } } if (portletContents != null) { Map<String, SortedSet<PortletWindowData>> portletWindowContents = getPortletWindowContents(request, portletContents, portletRegistryContext); setPortletWindowData(request, portletWindowContents); InvokerUtil.setResponseProperties(request, response, portletContent .getResponseProperties()); RequestDispatcher rd = context.getRequestDispatcher(getPresentationURI(request)); rd.forward(request, response); InvokerUtil.clearResponseProperties(portletContent.getResponseProperties()); } } catch (Exception e) { SilverTrace.error("portlet", "SPDesktopServlet.doGetPost", "root.MSG_GEN_PARAM_VALUE", "Portlets exception !", e); } finally { ServletContextThreadLocalizer.set(null); } } }
diff --git a/src/me/ashconnell/Fight/Fight.java b/src/me/ashconnell/Fight/Fight.java index bc3f964..1ba8d18 100644 --- a/src/me/ashconnell/Fight/Fight.java +++ b/src/me/ashconnell/Fight/Fight.java @@ -1,444 +1,447 @@ package me.ashconnell.Fight; import java.io.File; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Logger; import org.bukkit.ChatColor; import org.bukkit.block.Sign; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.util.config.Configuration; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.Location; import com.nijiko.permissions.PermissionHandler; import com.nijikokun.bukkit.Permissions.Permissions; import org.bukkit.plugin.Plugin; public class Fight extends JavaPlugin { private static final Logger log = Logger.getLogger("Minecraft"); public static PermissionHandler permissionHandler; private final FightSignListener signListener = new FightSignListener(this); private final FightReadyListener readyListener = new FightReadyListener(this); private final FightRespawnListener respawnListener = new FightRespawnListener(this); private final FightDeathListener deathListener = new FightDeathListener(this); public final Map<String, String> fightUsersTeam = new HashMap<String, String>(); public final Map<String, String> fightUsersClass = new HashMap<String, String>(); public final Map<String, String> fightClasses = new HashMap<String, String>(); public final Map<String, Sign> fightSigns = new HashMap<String, Sign>(); int redTeam = 0; int blueTeam = 0; boolean fightInProgress = false; public void onEnable() { setupPermissions(); // Event Registration PluginManager pm = getServer().getPluginManager(); pm.registerEvent(Event.Type.PLAYER_INTERACT, signListener, Event.Priority.Normal, this); pm.registerEvent(Event.Type.PLAYER_INTERACT, readyListener, Event.Priority.Normal, this); pm.registerEvent(Event.Type.PLAYER_RESPAWN, respawnListener, Event.Priority.Highest, this); pm.registerEvent(Event.Type.ENTITY_DEATH, deathListener, Event.Priority.Highest, this); log.info("[Fight] Plugin Started. (version 1.0)"); // Create Config if Non-Existant new File("plugins/Fight").mkdir(); File configFile = new File("plugins/Fight/config.yml"); if(!configFile.exists()){ try { configFile.createNewFile(); } catch(Exception e){ log.info("[Fight] Error when creating config file."); } } // Load Classes From Config Configuration config = new Configuration(configFile); config.load(); List<String> classes; classes = config.getKeys("classes"); log.info("[Fight] Loaded " + classes.size() + " Classes."); // Load Classes for(int i=0; i < classes.size(); i++){ String className = classes.get(i); fightClasses.put(className, config.getString("classes." + className + ".items", null)); } } public void onDisable() { log.info("[Fight] Plugin Stopped."); cleanSigns(); } public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){ String[] fightCmd = args; if(commandLabel.equalsIgnoreCase("Fight")){ Player player = (Player) sender; // Command: /Fight if(args.length < 1 && this.isSetup() && !fightInProgress && hasPermissions(player, "user")){ // Check For Empty Inventory ItemStack[] invContents = player.getInventory().getContents(); ItemStack[] armContents = player.getInventory().getArmorContents(); boolean emptyInventory = false; int invNullCounter = 0; int armNullCounter = 0; for(int i=0; i < invContents.length; i++){ if(invContents[i]==null){ invNullCounter++; } } for(int i=0; i < armContents.length; i++){ if(armContents[i].getType()==Material.AIR){ armNullCounter++; } } if(invNullCounter == invContents.length && armNullCounter == armContents.length){ emptyInventory = true; } if(emptyInventory == true){ // Add New Users To Map if(!this.fightUsersTeam.containsKey(player.getName())){ this.fightUsersTeam.put(player.getName(), "none"); } // Pick Team and Teleport To Lounge if(fightUsersTeam.get(player.getName()) == "none"){ if(blueTeam > redTeam){ fightUsersTeam.put(player.getName(), "red"); sender.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "Welcome! You are on team " + ChatColor.RED + "<Red>"); redTeam++; player.teleport(getCoords("redlounge")); } else { fightUsersTeam.put(player.getName(), "blue"); blueTeam++; sender.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "Welcome! You are on team " + ChatColor.BLUE + "<Blue>"); player.teleport(getCoords("bluelounge")); } } // If In Team, Teleport To Lounge else { String team = fightUsersTeam.get(player.getName()); player.teleport(getCoords(team + "lounge")); } } else { sender.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "You must have an empty inventory to join a Fight!"); } } // Command: /Fight <argument> if(args.length == 1){ // Command: /Fight RedLounge if(fightCmd[0].equalsIgnoreCase("redlounge") && hasPermissions(player, "admin")){ setCoords(player, "redlounge"); sender.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "Red Lounge Set."); } // Command: /Fight RedSpawn else if(fightCmd[0].equalsIgnoreCase("redspawn") && hasPermissions(player, "admin")){ setCoords(player, "redspawn"); sender.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "Red Spawn Set."); } // Command: /Fight BlueLounge else if(fightCmd[0].equalsIgnoreCase("bluelounge") && hasPermissions(player, "admin")){ setCoords(player, "bluelounge"); sender.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "Blue Lounge Set."); } // Command: /Fight BlueSpawn else if(fightCmd[0].equalsIgnoreCase("bluespawn") && hasPermissions(player, "admin")){ setCoords(player, "bluespawn"); sender.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "Blue Spawn Set."); } // Command: /Fight Spectator else if(fightCmd[0].equalsIgnoreCase("spectator") && hasPermissions(player, "admin")){ setCoords(player, "spectator"); sender.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "Spectator Area Set."); } // Command: /Fight Watch else if(fightCmd[0].equalsIgnoreCase("watch") && this.isSetup() && hasPermissions(player, "user")){ // Teleport To Spectator Area player.teleport(getCoords("spectator")); sender.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "Welcome to the spectator's area!"); if(fightUsersTeam.containsKey(player.getName())){ if(fightUsersTeam.get(player.getName()) == "red"){ redTeam = redTeam - 1; log.info("red:" + redTeam + " blue:" + blueTeam); } if(fightUsersTeam.get(player.getName()) == "blue"){ blueTeam = blueTeam - 1; log.info("red:" + redTeam + " blue:" + blueTeam); } fightUsersTeam.remove(player.getName()); fightUsersClass.remove(player.getName()); cleanSigns(player.getName()); } } // Command: /Fight Leave else if(fightCmd[0].equalsIgnoreCase("leave") && hasPermissions(player, "user")){ if(fightUsersTeam.containsKey(player.getName())){ if(fightUsersTeam.get(player.getName()) == "red"){ redTeam = redTeam - 1; } if(fightUsersTeam.get(player.getName()) == "blue"){ blueTeam = blueTeam - 1; } player.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "You have left the fight."); fightUsersTeam.remove(player.getName()); fightUsersClass.remove(player.getName()); cleanSigns(player.getName()); + player.getInventory().clear(); + clearArmorSlots(player); + player.teleport(getCoords("spectator")); } else { player.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "You are not in a team."); } } // Invalid Command else { sender.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "Invalid Command. (503)"); } } // Waypoints have not been setup else if(!this.isSetup()){ sender.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "All Waypoints must be set up first."); } // Command: /Fight <argument> <argument> cont... if(args.length > 1){ sender.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "Invalid Command. (504)"); } return true; } return false; } // Set Coords (to config.yml) public void setCoords(Player player, String place) { Location location = player.getLocation(); File configFile = new File("plugins/Fight/config.yml"); Configuration config = new Configuration(configFile); config.load(); config.setProperty("coords." + place + ".world", location.getWorld().getName()); config.setProperty("coords." + place + ".x", location.getX()); config.setProperty("coords." + place + ".y", location.getY()); config.setProperty("coords." + place + ".z", location.getZ()); config.setProperty("coords." + place + ".yaw", location.getYaw()); config.setProperty("coords." + place + ".pitch", location.getPitch()); config.save(); } // Get Coords (from config.yml) public Location getCoords(String place){ File configFile = new File("plugins/Fight/config.yml"); Configuration config = new Configuration(configFile); config.load(); Double x = config.getDouble("coords." + place + ".x", 0); Double y = config.getDouble("coords." + place + ".y", 0); Double z = config.getDouble("coords." + place + ".z", 0); Float yaw = new Float(config.getString("coords." + place + ".yaw")); Float pitch = new Float(config.getString("coords." + place + ".pitch")); World world = Bukkit.getServer().getWorld(config.getString("coords." + place + ".world")); return new Location(world, x, y, z, yaw, pitch); } // Check if all Waypoints have been set. public Boolean isSetup(){ File configFile = new File("plugins/Fight/config.yml"); Configuration config = new Configuration(configFile); config.load(); List<String> list = config.getKeys("coords"); if(list.size() == 5){ return true; } else { return false; } } // Give Player Class Items public void giveItems(Player player){ String playerClass = fightUsersClass.get(player.getName()); String rawItems = fightClasses.get(playerClass); String[] items; items = rawItems.split(","); for(int i=0; i < items.length; i++){ String item = items[i]; String[] itemDetail = item.split(":"); if(itemDetail.length == 2){ int x = Integer.parseInt(itemDetail[0]); int y = Integer.parseInt(itemDetail[1]); ItemStack stack = new ItemStack (x, y); player.getInventory().setItem(i, stack); } else{ int x = Integer.parseInt(itemDetail[0]); ItemStack stack = new ItemStack (x, 1); player.getInventory().setItem(i, stack); } } } // Permissions Support private void setupPermissions() { Plugin permissionsPlugin = this.getServer().getPluginManager().getPlugin("Permissions"); if (Fight.permissionHandler == null) { if (permissionsPlugin != null) { Fight.permissionHandler = ((Permissions) permissionsPlugin).getHandler(); } else { log.info("Permission system not detected, defaulting to OP"); } } } // Return True If Player Has Permissions private boolean hasPermissions(Player player, String type){ if(type == "admin"){ if(Fight.permissionHandler.has(player, "fight.admin")){ return true; } else { return false; } } else if(type == "user"){ if(Fight.permissionHandler.has(player, "fight.user")){ return true; } else { return false; } } else { return false; } } // Clean Up All Signs People Have Used For Classes public void cleanSigns(){ Set<String> set = fightSigns.keySet(); Iterator<String> iter = set.iterator(); while(iter.hasNext()){ Object o = iter.next(); Sign sign = fightSigns.get(o.toString()); sign.setLine(2, ""); sign.setLine(3, ""); sign.update(); } } // Clean Up Signs Specific Player Has Used For Classes public void cleanSigns(String player){ Set<String> set = fightSigns.keySet(); Iterator<String> iter = set.iterator(); while(iter.hasNext()){ Object o = iter.next(); Sign sign = fightSigns.get(o.toString()); if(sign.getLine(2) == player){ sign.setLine(2, ""); sign.update(); } if(sign.getLine(3) == player){ sign.setLine(3, ""); sign.update(); } } } // Check If Team Has All Chosen A Class public boolean teamReady(String color){ int members = 0; int membersReady = 0; Set<String> set = fightUsersTeam.keySet(); Iterator<String> iter = set.iterator(); while(iter.hasNext()){ Object o = iter.next(); if(fightUsersTeam.get(o.toString()) == color){ members++; if(fightUsersClass.containsKey(o.toString())){ membersReady++; } } } if(members == membersReady && members > 0){ return true; } else{ return false; } } // Tell All Fight Players public void tellEveryone(String msg){ Set<String> set = fightUsersTeam.keySet(); Iterator<String> iter = set.iterator(); while(iter.hasNext()){ Object o = iter.next(); Player z = getServer().getPlayer(o.toString()); z.sendMessage(ChatColor.YELLOW + "[Fight] " + msg); } } // Tell Fight Team Mates public void tellTeam(String color, String msg){ Set<String> set = fightUsersTeam.keySet(); Iterator<String> iter = set.iterator(); while(iter.hasNext()){ Object o = iter.next(); if(fightUsersTeam.get(o.toString()) == color){ Player z = getServer().getPlayer(o.toString()); z.sendMessage(ChatColor.YELLOW + "[Fight] " + msg); } } } // Teleport All Fight Players To Spawn public void teleportAllToSpawn(){ Set<String> set = fightUsersTeam.keySet(); Iterator<String> iter = set.iterator(); while(iter.hasNext()){ Object o = iter.next(); if(fightUsersTeam.get(o.toString()) == "red"){ Player z = getServer().getPlayer(o.toString()); z.teleport(getCoords("redspawn")); } if(fightUsersTeam.get(o.toString()) == "blue"){ Player z = getServer().getPlayer(o.toString()); z.teleport(getCoords("bluespawn")); } } } public void clearArmorSlots(Player player){ player.getInventory().setHelmet(null); player.getInventory().setBoots(null); player.getInventory().setChestplate(null); player.getInventory().setLeggings(null); } }
true
true
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){ String[] fightCmd = args; if(commandLabel.equalsIgnoreCase("Fight")){ Player player = (Player) sender; // Command: /Fight if(args.length < 1 && this.isSetup() && !fightInProgress && hasPermissions(player, "user")){ // Check For Empty Inventory ItemStack[] invContents = player.getInventory().getContents(); ItemStack[] armContents = player.getInventory().getArmorContents(); boolean emptyInventory = false; int invNullCounter = 0; int armNullCounter = 0; for(int i=0; i < invContents.length; i++){ if(invContents[i]==null){ invNullCounter++; } } for(int i=0; i < armContents.length; i++){ if(armContents[i].getType()==Material.AIR){ armNullCounter++; } } if(invNullCounter == invContents.length && armNullCounter == armContents.length){ emptyInventory = true; } if(emptyInventory == true){ // Add New Users To Map if(!this.fightUsersTeam.containsKey(player.getName())){ this.fightUsersTeam.put(player.getName(), "none"); } // Pick Team and Teleport To Lounge if(fightUsersTeam.get(player.getName()) == "none"){ if(blueTeam > redTeam){ fightUsersTeam.put(player.getName(), "red"); sender.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "Welcome! You are on team " + ChatColor.RED + "<Red>"); redTeam++; player.teleport(getCoords("redlounge")); } else { fightUsersTeam.put(player.getName(), "blue"); blueTeam++; sender.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "Welcome! You are on team " + ChatColor.BLUE + "<Blue>"); player.teleport(getCoords("bluelounge")); } } // If In Team, Teleport To Lounge else { String team = fightUsersTeam.get(player.getName()); player.teleport(getCoords(team + "lounge")); } } else { sender.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "You must have an empty inventory to join a Fight!"); } } // Command: /Fight <argument> if(args.length == 1){ // Command: /Fight RedLounge if(fightCmd[0].equalsIgnoreCase("redlounge") && hasPermissions(player, "admin")){ setCoords(player, "redlounge"); sender.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "Red Lounge Set."); } // Command: /Fight RedSpawn else if(fightCmd[0].equalsIgnoreCase("redspawn") && hasPermissions(player, "admin")){ setCoords(player, "redspawn"); sender.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "Red Spawn Set."); } // Command: /Fight BlueLounge else if(fightCmd[0].equalsIgnoreCase("bluelounge") && hasPermissions(player, "admin")){ setCoords(player, "bluelounge"); sender.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "Blue Lounge Set."); } // Command: /Fight BlueSpawn else if(fightCmd[0].equalsIgnoreCase("bluespawn") && hasPermissions(player, "admin")){ setCoords(player, "bluespawn"); sender.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "Blue Spawn Set."); } // Command: /Fight Spectator else if(fightCmd[0].equalsIgnoreCase("spectator") && hasPermissions(player, "admin")){ setCoords(player, "spectator"); sender.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "Spectator Area Set."); } // Command: /Fight Watch else if(fightCmd[0].equalsIgnoreCase("watch") && this.isSetup() && hasPermissions(player, "user")){ // Teleport To Spectator Area player.teleport(getCoords("spectator")); sender.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "Welcome to the spectator's area!"); if(fightUsersTeam.containsKey(player.getName())){ if(fightUsersTeam.get(player.getName()) == "red"){ redTeam = redTeam - 1; log.info("red:" + redTeam + " blue:" + blueTeam); } if(fightUsersTeam.get(player.getName()) == "blue"){ blueTeam = blueTeam - 1; log.info("red:" + redTeam + " blue:" + blueTeam); } fightUsersTeam.remove(player.getName()); fightUsersClass.remove(player.getName()); cleanSigns(player.getName()); } } // Command: /Fight Leave else if(fightCmd[0].equalsIgnoreCase("leave") && hasPermissions(player, "user")){ if(fightUsersTeam.containsKey(player.getName())){ if(fightUsersTeam.get(player.getName()) == "red"){ redTeam = redTeam - 1; } if(fightUsersTeam.get(player.getName()) == "blue"){ blueTeam = blueTeam - 1; } player.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "You have left the fight."); fightUsersTeam.remove(player.getName()); fightUsersClass.remove(player.getName()); cleanSigns(player.getName()); } else { player.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "You are not in a team."); } } // Invalid Command else { sender.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "Invalid Command. (503)"); } } // Waypoints have not been setup else if(!this.isSetup()){ sender.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "All Waypoints must be set up first."); } // Command: /Fight <argument> <argument> cont... if(args.length > 1){ sender.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "Invalid Command. (504)"); } return true; } return false; }
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){ String[] fightCmd = args; if(commandLabel.equalsIgnoreCase("Fight")){ Player player = (Player) sender; // Command: /Fight if(args.length < 1 && this.isSetup() && !fightInProgress && hasPermissions(player, "user")){ // Check For Empty Inventory ItemStack[] invContents = player.getInventory().getContents(); ItemStack[] armContents = player.getInventory().getArmorContents(); boolean emptyInventory = false; int invNullCounter = 0; int armNullCounter = 0; for(int i=0; i < invContents.length; i++){ if(invContents[i]==null){ invNullCounter++; } } for(int i=0; i < armContents.length; i++){ if(armContents[i].getType()==Material.AIR){ armNullCounter++; } } if(invNullCounter == invContents.length && armNullCounter == armContents.length){ emptyInventory = true; } if(emptyInventory == true){ // Add New Users To Map if(!this.fightUsersTeam.containsKey(player.getName())){ this.fightUsersTeam.put(player.getName(), "none"); } // Pick Team and Teleport To Lounge if(fightUsersTeam.get(player.getName()) == "none"){ if(blueTeam > redTeam){ fightUsersTeam.put(player.getName(), "red"); sender.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "Welcome! You are on team " + ChatColor.RED + "<Red>"); redTeam++; player.teleport(getCoords("redlounge")); } else { fightUsersTeam.put(player.getName(), "blue"); blueTeam++; sender.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "Welcome! You are on team " + ChatColor.BLUE + "<Blue>"); player.teleport(getCoords("bluelounge")); } } // If In Team, Teleport To Lounge else { String team = fightUsersTeam.get(player.getName()); player.teleport(getCoords(team + "lounge")); } } else { sender.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "You must have an empty inventory to join a Fight!"); } } // Command: /Fight <argument> if(args.length == 1){ // Command: /Fight RedLounge if(fightCmd[0].equalsIgnoreCase("redlounge") && hasPermissions(player, "admin")){ setCoords(player, "redlounge"); sender.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "Red Lounge Set."); } // Command: /Fight RedSpawn else if(fightCmd[0].equalsIgnoreCase("redspawn") && hasPermissions(player, "admin")){ setCoords(player, "redspawn"); sender.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "Red Spawn Set."); } // Command: /Fight BlueLounge else if(fightCmd[0].equalsIgnoreCase("bluelounge") && hasPermissions(player, "admin")){ setCoords(player, "bluelounge"); sender.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "Blue Lounge Set."); } // Command: /Fight BlueSpawn else if(fightCmd[0].equalsIgnoreCase("bluespawn") && hasPermissions(player, "admin")){ setCoords(player, "bluespawn"); sender.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "Blue Spawn Set."); } // Command: /Fight Spectator else if(fightCmd[0].equalsIgnoreCase("spectator") && hasPermissions(player, "admin")){ setCoords(player, "spectator"); sender.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "Spectator Area Set."); } // Command: /Fight Watch else if(fightCmd[0].equalsIgnoreCase("watch") && this.isSetup() && hasPermissions(player, "user")){ // Teleport To Spectator Area player.teleport(getCoords("spectator")); sender.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "Welcome to the spectator's area!"); if(fightUsersTeam.containsKey(player.getName())){ if(fightUsersTeam.get(player.getName()) == "red"){ redTeam = redTeam - 1; log.info("red:" + redTeam + " blue:" + blueTeam); } if(fightUsersTeam.get(player.getName()) == "blue"){ blueTeam = blueTeam - 1; log.info("red:" + redTeam + " blue:" + blueTeam); } fightUsersTeam.remove(player.getName()); fightUsersClass.remove(player.getName()); cleanSigns(player.getName()); } } // Command: /Fight Leave else if(fightCmd[0].equalsIgnoreCase("leave") && hasPermissions(player, "user")){ if(fightUsersTeam.containsKey(player.getName())){ if(fightUsersTeam.get(player.getName()) == "red"){ redTeam = redTeam - 1; } if(fightUsersTeam.get(player.getName()) == "blue"){ blueTeam = blueTeam - 1; } player.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "You have left the fight."); fightUsersTeam.remove(player.getName()); fightUsersClass.remove(player.getName()); cleanSigns(player.getName()); player.getInventory().clear(); clearArmorSlots(player); player.teleport(getCoords("spectator")); } else { player.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "You are not in a team."); } } // Invalid Command else { sender.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "Invalid Command. (503)"); } } // Waypoints have not been setup else if(!this.isSetup()){ sender.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "All Waypoints must be set up first."); } // Command: /Fight <argument> <argument> cont... if(args.length > 1){ sender.sendMessage(ChatColor.YELLOW + "[Fight] " + ChatColor.WHITE + "Invalid Command. (504)"); } return true; } return false; }
diff --git a/src/distributedRedditAnalyser/spout/RawRedditSpout.java b/src/distributedRedditAnalyser/spout/RawRedditSpout.java index 814437e..d8a0563 100644 --- a/src/distributedRedditAnalyser/spout/RawRedditSpout.java +++ b/src/distributedRedditAnalyser/spout/RawRedditSpout.java @@ -1,178 +1,178 @@ package distributedRedditAnalyser.spout; import java.io.IOException; import java.util.Map; import java.util.concurrent.ArrayBlockingQueue; import org.apache.http.HttpVersion; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.cookie.BasicClientCookie2; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.params.HttpParams; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import distributedRedditAnalyser.reddit.Post; import backtype.storm.spout.SpoutOutputCollector; import backtype.storm.task.TopologyContext; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.topology.base.BaseRichSpout; import backtype.storm.tuple.Fields; import backtype.storm.tuple.Values; import backtype.storm.utils.Utils; public class RawRedditSpout extends BaseRichSpout { private SpoutOutputCollector collector; private Boolean initialPull = true; private long latestTimestamp = Long.MIN_VALUE; private final String SUBREDDIT; private final String URL; private final ArrayBlockingQueue<Post> QUEUE; //The number of pages to fetch on the initial scrape private final int INITIAL_PAGE_COUNT = 1; /** * Creates a new raw reddit spout for the provided sub-reddit * @param subReddit The sub-reddit to use for the spout */ public RawRedditSpout(String subReddit){ SUBREDDIT = subReddit; URL = "http://www.reddit.com/r/" + SUBREDDIT + "/new/.json?sort=new"; QUEUE = new ArrayBlockingQueue<Post>(10000); } @Override public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) { this.collector = collector; } @Override public void nextTuple() { Utils.sleep(50); Post nextPost = getNextPost(); if(nextPost != null) collector.emit(new Values(nextPost)); } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { declarer.declare(new Fields("redditPost")); } private Post getNextPost(){ if(QUEUE.size() < 1){ HttpParams parameters = new BasicHttpParams(); parameters.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); parameters.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "ISO-8859-1"); parameters.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true); parameters.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8192); parameters.setParameter(CoreProtocolPNames.USER_AGENT, "DistributedRedditAnalyser /u/Technicolour/"); DefaultHttpClient httpClient = new DefaultHttpClient(parameters); //Reddit user: DistributedRedditAna //TODO Work out how to get the cookie installed to get more than 25 at a time //httpClient.getCookieStore().addCookie(new BasicClientCookie2("", "")); try { if(initialPull){ String lastItemId = ""; for(int i = 0; i < INITIAL_PAGE_COUNT; i++){ HttpGet getRequest = new HttpGet(URL + "&after=" + lastItemId); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpClient.execute(getRequest, responseHandler); JSONParser parser= new JSONParser(); JSONObject wrappingObject = (JSONObject) parser.parse(responseBody); JSONObject wrappingObjectData = (JSONObject) wrappingObject.get("data"); JSONArray children = (JSONArray) wrappingObjectData.get("children"); System.out.printf("There are %d children in %s\r\n", children.size(), getRequest.getURI().toString()); if(children.size() == 0) break; for(Object c : children){ JSONObject childData = (JSONObject) ((JSONObject) c).get("data"); QUEUE.add(new Post((String) childData.get("title"), SUBREDDIT)); } - lastItemId = (String) ((JSONObject) ((JSONObject) children.get(children.size() - 1)).get("data")).get("subreddit_id"); + lastItemId = (String) wrappingObjectData.get("after"); if(i == 0){ latestTimestamp = ((Double) ((JSONObject)((JSONObject) children.get(0)).get("data")).get("created")).longValue(); } //Rate limit if(i != INITIAL_PAGE_COUNT - 1) Utils.sleep(1000); } initialPull = false; }else{ //Rate limit for the API (pages are cached for 30 seconds) Utils.sleep(30000); HttpGet getRequest = new HttpGet(URL); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpClient.execute(getRequest, responseHandler); JSONParser parser= new JSONParser(); JSONObject wrappingObject = (JSONObject) parser.parse(responseBody); JSONObject wrappingObjectData = (JSONObject) wrappingObject.get("data"); JSONArray children = (JSONArray) wrappingObjectData.get("children"); if(children.size() > 0){ for(Object c : children){ JSONObject childData = (JSONObject) ((JSONObject) c).get("data"); if(latestTimestamp < ((Double) childData.get("created")).longValue()) QUEUE.add(new Post((String) childData.get("title"), SUBREDDIT)); else break; //We may as well break at this point as they are sorted } latestTimestamp = ((Double) ((JSONObject)((JSONObject) children.get(0)).get("data")).get("created")).longValue(); } } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { httpClient.getConnectionManager().shutdown(); } } return QUEUE.poll(); } @Override public void close() { } }
true
true
private Post getNextPost(){ if(QUEUE.size() < 1){ HttpParams parameters = new BasicHttpParams(); parameters.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); parameters.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "ISO-8859-1"); parameters.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true); parameters.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8192); parameters.setParameter(CoreProtocolPNames.USER_AGENT, "DistributedRedditAnalyser /u/Technicolour/"); DefaultHttpClient httpClient = new DefaultHttpClient(parameters); //Reddit user: DistributedRedditAna //TODO Work out how to get the cookie installed to get more than 25 at a time //httpClient.getCookieStore().addCookie(new BasicClientCookie2("", "")); try { if(initialPull){ String lastItemId = ""; for(int i = 0; i < INITIAL_PAGE_COUNT; i++){ HttpGet getRequest = new HttpGet(URL + "&after=" + lastItemId); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpClient.execute(getRequest, responseHandler); JSONParser parser= new JSONParser(); JSONObject wrappingObject = (JSONObject) parser.parse(responseBody); JSONObject wrappingObjectData = (JSONObject) wrappingObject.get("data"); JSONArray children = (JSONArray) wrappingObjectData.get("children"); System.out.printf("There are %d children in %s\r\n", children.size(), getRequest.getURI().toString()); if(children.size() == 0) break; for(Object c : children){ JSONObject childData = (JSONObject) ((JSONObject) c).get("data"); QUEUE.add(new Post((String) childData.get("title"), SUBREDDIT)); } lastItemId = (String) ((JSONObject) ((JSONObject) children.get(children.size() - 1)).get("data")).get("subreddit_id"); if(i == 0){ latestTimestamp = ((Double) ((JSONObject)((JSONObject) children.get(0)).get("data")).get("created")).longValue(); } //Rate limit if(i != INITIAL_PAGE_COUNT - 1) Utils.sleep(1000); } initialPull = false; }else{ //Rate limit for the API (pages are cached for 30 seconds) Utils.sleep(30000); HttpGet getRequest = new HttpGet(URL); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpClient.execute(getRequest, responseHandler); JSONParser parser= new JSONParser(); JSONObject wrappingObject = (JSONObject) parser.parse(responseBody); JSONObject wrappingObjectData = (JSONObject) wrappingObject.get("data"); JSONArray children = (JSONArray) wrappingObjectData.get("children"); if(children.size() > 0){ for(Object c : children){ JSONObject childData = (JSONObject) ((JSONObject) c).get("data"); if(latestTimestamp < ((Double) childData.get("created")).longValue()) QUEUE.add(new Post((String) childData.get("title"), SUBREDDIT)); else break; //We may as well break at this point as they are sorted } latestTimestamp = ((Double) ((JSONObject)((JSONObject) children.get(0)).get("data")).get("created")).longValue(); } } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { httpClient.getConnectionManager().shutdown(); } } return QUEUE.poll(); }
private Post getNextPost(){ if(QUEUE.size() < 1){ HttpParams parameters = new BasicHttpParams(); parameters.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); parameters.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "ISO-8859-1"); parameters.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true); parameters.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8192); parameters.setParameter(CoreProtocolPNames.USER_AGENT, "DistributedRedditAnalyser /u/Technicolour/"); DefaultHttpClient httpClient = new DefaultHttpClient(parameters); //Reddit user: DistributedRedditAna //TODO Work out how to get the cookie installed to get more than 25 at a time //httpClient.getCookieStore().addCookie(new BasicClientCookie2("", "")); try { if(initialPull){ String lastItemId = ""; for(int i = 0; i < INITIAL_PAGE_COUNT; i++){ HttpGet getRequest = new HttpGet(URL + "&after=" + lastItemId); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpClient.execute(getRequest, responseHandler); JSONParser parser= new JSONParser(); JSONObject wrappingObject = (JSONObject) parser.parse(responseBody); JSONObject wrappingObjectData = (JSONObject) wrappingObject.get("data"); JSONArray children = (JSONArray) wrappingObjectData.get("children"); System.out.printf("There are %d children in %s\r\n", children.size(), getRequest.getURI().toString()); if(children.size() == 0) break; for(Object c : children){ JSONObject childData = (JSONObject) ((JSONObject) c).get("data"); QUEUE.add(new Post((String) childData.get("title"), SUBREDDIT)); } lastItemId = (String) wrappingObjectData.get("after"); if(i == 0){ latestTimestamp = ((Double) ((JSONObject)((JSONObject) children.get(0)).get("data")).get("created")).longValue(); } //Rate limit if(i != INITIAL_PAGE_COUNT - 1) Utils.sleep(1000); } initialPull = false; }else{ //Rate limit for the API (pages are cached for 30 seconds) Utils.sleep(30000); HttpGet getRequest = new HttpGet(URL); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpClient.execute(getRequest, responseHandler); JSONParser parser= new JSONParser(); JSONObject wrappingObject = (JSONObject) parser.parse(responseBody); JSONObject wrappingObjectData = (JSONObject) wrappingObject.get("data"); JSONArray children = (JSONArray) wrappingObjectData.get("children"); if(children.size() > 0){ for(Object c : children){ JSONObject childData = (JSONObject) ((JSONObject) c).get("data"); if(latestTimestamp < ((Double) childData.get("created")).longValue()) QUEUE.add(new Post((String) childData.get("title"), SUBREDDIT)); else break; //We may as well break at this point as they are sorted } latestTimestamp = ((Double) ((JSONObject)((JSONObject) children.get(0)).get("data")).get("created")).longValue(); } } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { httpClient.getConnectionManager().shutdown(); } } return QUEUE.poll(); }
diff --git a/src/Developer.java b/src/Developer.java index cf03327..d4423ba 100644 --- a/src/Developer.java +++ b/src/Developer.java @@ -1,100 +1,98 @@ import java.util.Calendar; import java.util.Random; /** * This model describes the Developer. It extends Programmer. * * @author Yin * @author Shawn * @author Peter */ public class Developer extends Employee { /** * The Developer's Team Leader. */ private TeamLeader leader; /** * Default Constructor. * * @param leader * - Assigned Team Leader */ public Developer(Calendar time, String name) { this.startTime = time; this.arrived = false; this.name = name; } /** * Ask Team Leader or Project Manager question. Question will first go to * Team Leader if he/she is available; otherwise, it will go to the Project * Manager. */ public void askQuestion() { leader.answerQuestion(); } /** * Set the leader. */ public void setLeader(TeamLeader leader) { this.leader = leader; } /** * Override for the run method in the Thread class. */ @Override public void run() { Random ran = new Random(); Boolean hasGoneToLunch = false; Boolean hasGoneToMeeting = false; try { leader.notifyArrival(this); } catch (InterruptedException e) { } - long begin = System.currentTimeMillis(); - while (System.currentTimeMillis() - begin < 4800 || !hasGoneToMeeting) { + while (System.currentTimeMillis() - startTime.getTimeInMillis() < 4800 || !hasGoneToMeeting) { // Ask team leader a question. int askQuestion = ran.nextInt(100); if (askQuestion == 1) { System.out.println(name + " has asked leader a question"); leader.answerQuestion(); } // Lunch if (!hasGoneToLunch) { int goToLunch = ran.nextInt(100); if (goToLunch <= 50) { System.out.println(name + " has gone to lunch"); int lunchTime = ran.nextInt(300) + 300; try { sleep(lunchTime); } catch (InterruptedException e) { } finally { hasGoneToLunch = true; } } } // Project Status meeting - if (getTime().get(Calendar.HOUR_OF_DAY) >= 16 - && !hasGoneToMeeting) { + if (getTime()>= 16 && !hasGoneToMeeting) { try { System.out.println(name + " is going to project status meeting"); Calendar fourThirty = Calendar.getInstance(); fourThirty.set(Calendar.YEAR, Calendar.MONTH, Calendar.DATE, 16, 30); - while (getTime().get(Calendar.MINUTE) < 30) { + while (getTime()< 4.5) { sleep(10); } hasGoneToMeeting = true; } catch (InterruptedException e) { } } } } }
false
true
public void run() { Random ran = new Random(); Boolean hasGoneToLunch = false; Boolean hasGoneToMeeting = false; try { leader.notifyArrival(this); } catch (InterruptedException e) { } long begin = System.currentTimeMillis(); while (System.currentTimeMillis() - begin < 4800 || !hasGoneToMeeting) { // Ask team leader a question. int askQuestion = ran.nextInt(100); if (askQuestion == 1) { System.out.println(name + " has asked leader a question"); leader.answerQuestion(); } // Lunch if (!hasGoneToLunch) { int goToLunch = ran.nextInt(100); if (goToLunch <= 50) { System.out.println(name + " has gone to lunch"); int lunchTime = ran.nextInt(300) + 300; try { sleep(lunchTime); } catch (InterruptedException e) { } finally { hasGoneToLunch = true; } } } // Project Status meeting if (getTime().get(Calendar.HOUR_OF_DAY) >= 16 && !hasGoneToMeeting) { try { System.out.println(name + " is going to project status meeting"); Calendar fourThirty = Calendar.getInstance(); fourThirty.set(Calendar.YEAR, Calendar.MONTH, Calendar.DATE, 16, 30); while (getTime().get(Calendar.MINUTE) < 30) { sleep(10); } hasGoneToMeeting = true; } catch (InterruptedException e) { } } } }
public void run() { Random ran = new Random(); Boolean hasGoneToLunch = false; Boolean hasGoneToMeeting = false; try { leader.notifyArrival(this); } catch (InterruptedException e) { } while (System.currentTimeMillis() - startTime.getTimeInMillis() < 4800 || !hasGoneToMeeting) { // Ask team leader a question. int askQuestion = ran.nextInt(100); if (askQuestion == 1) { System.out.println(name + " has asked leader a question"); leader.answerQuestion(); } // Lunch if (!hasGoneToLunch) { int goToLunch = ran.nextInt(100); if (goToLunch <= 50) { System.out.println(name + " has gone to lunch"); int lunchTime = ran.nextInt(300) + 300; try { sleep(lunchTime); } catch (InterruptedException e) { } finally { hasGoneToLunch = true; } } } // Project Status meeting if (getTime()>= 16 && !hasGoneToMeeting) { try { System.out.println(name + " is going to project status meeting"); Calendar fourThirty = Calendar.getInstance(); fourThirty.set(Calendar.YEAR, Calendar.MONTH, Calendar.DATE, 16, 30); while (getTime()< 4.5) { sleep(10); } hasGoneToMeeting = true; } catch (InterruptedException e) { } } } }
diff --git a/org.eclipse.riena.tests/src/org/eclipse/riena/navigation/ui/controllers/ModuleControllerTest.java b/org.eclipse.riena.tests/src/org/eclipse/riena/navigation/ui/controllers/ModuleControllerTest.java index aa06b5d34..3cf8b85b8 100644 --- a/org.eclipse.riena.tests/src/org/eclipse/riena/navigation/ui/controllers/ModuleControllerTest.java +++ b/org.eclipse.riena.tests/src/org/eclipse/riena/navigation/ui/controllers/ModuleControllerTest.java @@ -1,42 +1,42 @@ /******************************************************************************* * Copyright (c) 2007, 2008 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.navigation.ui.controllers; import junit.framework.TestCase; import org.eclipse.riena.internal.ui.ridgets.swt.ShellRidget; import org.eclipse.riena.navigation.model.ModuleNode; import org.eclipse.swt.widgets.Shell; /** * Tests of the class <code>ModuleController</code>. */ public class ModuleControllerTest extends TestCase { public void testAfterBind() throws Exception { ModuleNode node = new ModuleNode(null); node.setCloseable(true); node.setLabel("Hello"); ModuleController controller = new ModuleController(node); ShellRidget shellRidget = new ShellRidget(); shellRidget.setUIControl(new Shell()); controller.setWindowRidget(shellRidget); controller.afterBind(); assertTrue(controller.isCloseable()); assertEquals("Hello", shellRidget.getTitle()); node.setCloseable(false); - controller.afterBind(); + controller.configureRidgets(); assertFalse(controller.isCloseable()); } }
true
true
public void testAfterBind() throws Exception { ModuleNode node = new ModuleNode(null); node.setCloseable(true); node.setLabel("Hello"); ModuleController controller = new ModuleController(node); ShellRidget shellRidget = new ShellRidget(); shellRidget.setUIControl(new Shell()); controller.setWindowRidget(shellRidget); controller.afterBind(); assertTrue(controller.isCloseable()); assertEquals("Hello", shellRidget.getTitle()); node.setCloseable(false); controller.afterBind(); assertFalse(controller.isCloseable()); }
public void testAfterBind() throws Exception { ModuleNode node = new ModuleNode(null); node.setCloseable(true); node.setLabel("Hello"); ModuleController controller = new ModuleController(node); ShellRidget shellRidget = new ShellRidget(); shellRidget.setUIControl(new Shell()); controller.setWindowRidget(shellRidget); controller.afterBind(); assertTrue(controller.isCloseable()); assertEquals("Hello", shellRidget.getTitle()); node.setCloseable(false); controller.configureRidgets(); assertFalse(controller.isCloseable()); }
diff --git a/src/com/archmageinc/RealStore/RSExecutor.java b/src/com/archmageinc/RealStore/RSExecutor.java index 242fca9..45379cf 100644 --- a/src/com/archmageinc/RealStore/RSExecutor.java +++ b/src/com/archmageinc/RealStore/RSExecutor.java @@ -1,202 +1,202 @@ package com.archmageinc.RealStore; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.material.MaterialData; public class RSExecutor implements CommandExecutor { private RealStore plugin; public RSExecutor(RealStore instance){ plugin = instance; } @Override public boolean onCommand(CommandSender sender, Command cmd, String label,String[] args){ if(cmd.getName().equalsIgnoreCase("rs") || cmd.getName().equalsIgnoreCase("RealStore")){ if(!(sender instanceof Player)){ plugin.logMessage("RealStore interactions may only be used by Players!"); return true; } Player player = (Player) sender; - if(!player.hasPermission("RealStore")){ + if(!player.hasPermission("RealStore.*")){ plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+"You do not have permission to do that."); return true; } if(args.length<1){ plugin.sendPlayerMessage(player,ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+"No RealStore command found! Please use '/rs help' for proper RealStore usage. "); return true; } String rsCommand = args[0].toLowerCase(); /************************************************************ * Getting Help ************************************************************/ if(rsCommand.equals("help")){ plugin.sendHelpInfo(player, (args.length<2 ? null : args[1]) ); return true; } /********************************************************** * Setting Stores **********************************************************/ if(rsCommand.equals("store")){ if(args.length<2){ plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+" Do you wish to add or remove a store? Use '/rs help store' for more information."); return true; } String storeCommand = args[1].toLowerCase(); /**************************** * Adding a store ****************************/ if(storeCommand.equals("add")){ if(!plugin.hasCoffer(player)){ plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+" You have no coffers! Use '/rs help coffer' for more information."); return true; } plugin.sendPlayerMessage(player, "Click on a chest to create a store."); plugin.getServer().getPluginManager().registerEvents(new StoreManagementListener(plugin, player),plugin); return true; } /***************************** * Removing a store *****************************/ if(storeCommand.equals("remove")){ plugin.getServer().getPluginManager().registerEvents(new StoreManagementListener(plugin,player,true), plugin); plugin.sendPlayerMessage(player, "Click on the chest store to remove the store."); return true; } plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+" Unknown store command! Use '/rs help store' for more information."); return true; } /************************************************************** * Setting Prices **************************************************************/ if(rsCommand.equals("price")){ if(args.length<2){ plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+" No price found. Use '/rs help price' for proper RealStore price setting usage."); return true; } if(!plugin.hasCoffer(player)){ plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+" You do not have any coffers. Create a coffer first. Use '/rs help coffer' for more."); return true; } if(!plugin.hasStore(player)){ plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+" You do not have any stores on which to set prices. Create a store first. Use '/rs help store' for more."); return true; } try{ Integer price = Integer.parseInt(args[1]); if(price<=0){ plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+" The price must be greater than zero!"); return true; } /******************************** * Command setting price ********************************/ if(args.length>2){ String type = args[2]; try{ Byte data = args.length>3 ? (byte) Integer.parseInt(args[3]) : (byte) 0; if(Material.matchMaterial(type)==null){ if(type.equalsIgnoreCase("default")){ /****************************** * Default setting price ******************************/ plugin.sendPlayerMessage(player, "Click on the chest store to set the default price to "+price+" gold nuggets"); plugin.getServer().getPluginManager().registerEvents(new PriceSetListener(plugin,player,price,true), plugin); return true; }else{ plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+" Unknown material used to set the price. Use '/rs help material' to list material names."); return true; } } MaterialData material = new MaterialData(Material.matchMaterial(type),data); plugin.sendPlayerMessage(player, "Click on the chest store to set the price of "+material.toString()+" to a price of "+price+" gold nuggets"); plugin.getServer().getPluginManager().registerEvents(new PriceSetListener(plugin,player,price,material), plugin); return true; }catch(NumberFormatException e){ plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+" Invalid material data. Use '/rs help material' to list material names and data values."); return true; } } /*************************** * Tap setting price ***************************/ plugin.getServer().getPluginManager().registerEvents(new PriceSetListener(plugin,player,price), plugin); plugin.sendPlayerMessage(player, "Click on the chest store with an item to set the price of that item to "+price+" gold nuggets."); return true; }catch(NumberFormatException e){ plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+" Improper price. Use '/rs help price' for proper RealStore price setting usage."); return true; } } /******************************************************** * Setting Coffers *******************************************************/ if(rsCommand.equals("coffer")){ if(args.length<2){ plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+" Do you wish to add or remove a coffer? Use '/rs help coffer' for more information."); return true; } String cofferCommand = args[1].toLowerCase(); /**************************** * Adding a coffer ****************************/ if(cofferCommand.equals("add")){ plugin.getServer().getPluginManager().registerEvents(new CofferManagementListener(plugin,player,false), plugin); plugin.sendPlayerMessage(player, "Click on a chest to add it to your coffers."); return true; } /***************************** * Removing a coffer *****************************/ if(cofferCommand.equals("remove")){ plugin.getServer().getPluginManager().registerEvents(new CofferManagementListener(plugin,player,true), plugin); plugin.sendPlayerMessage(player, "Click on a chest to remove it from your coffers."); return true; } plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+" Unknown coffer command! Use '/rs help coffer' for more information."); return true; } /** * TODO: Add a method for store owners to check prices */ /********************************************************** * Unknown RealStore Command **********************************************************/ plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+" Unknown RealStore command! Use '/rs help' for more information."); return true; } return false; } }
true
true
public boolean onCommand(CommandSender sender, Command cmd, String label,String[] args){ if(cmd.getName().equalsIgnoreCase("rs") || cmd.getName().equalsIgnoreCase("RealStore")){ if(!(sender instanceof Player)){ plugin.logMessage("RealStore interactions may only be used by Players!"); return true; } Player player = (Player) sender; if(!player.hasPermission("RealStore")){ plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+"You do not have permission to do that."); return true; } if(args.length<1){ plugin.sendPlayerMessage(player,ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+"No RealStore command found! Please use '/rs help' for proper RealStore usage. "); return true; } String rsCommand = args[0].toLowerCase(); /************************************************************ * Getting Help ************************************************************/ if(rsCommand.equals("help")){ plugin.sendHelpInfo(player, (args.length<2 ? null : args[1]) ); return true; } /********************************************************** * Setting Stores **********************************************************/ if(rsCommand.equals("store")){ if(args.length<2){ plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+" Do you wish to add or remove a store? Use '/rs help store' for more information."); return true; } String storeCommand = args[1].toLowerCase(); /**************************** * Adding a store ****************************/ if(storeCommand.equals("add")){ if(!plugin.hasCoffer(player)){ plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+" You have no coffers! Use '/rs help coffer' for more information."); return true; } plugin.sendPlayerMessage(player, "Click on a chest to create a store."); plugin.getServer().getPluginManager().registerEvents(new StoreManagementListener(plugin, player),plugin); return true; } /***************************** * Removing a store *****************************/ if(storeCommand.equals("remove")){ plugin.getServer().getPluginManager().registerEvents(new StoreManagementListener(plugin,player,true), plugin); plugin.sendPlayerMessage(player, "Click on the chest store to remove the store."); return true; } plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+" Unknown store command! Use '/rs help store' for more information."); return true; } /************************************************************** * Setting Prices **************************************************************/ if(rsCommand.equals("price")){ if(args.length<2){ plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+" No price found. Use '/rs help price' for proper RealStore price setting usage."); return true; } if(!plugin.hasCoffer(player)){ plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+" You do not have any coffers. Create a coffer first. Use '/rs help coffer' for more."); return true; } if(!plugin.hasStore(player)){ plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+" You do not have any stores on which to set prices. Create a store first. Use '/rs help store' for more."); return true; } try{ Integer price = Integer.parseInt(args[1]); if(price<=0){ plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+" The price must be greater than zero!"); return true; } /******************************** * Command setting price ********************************/ if(args.length>2){ String type = args[2]; try{ Byte data = args.length>3 ? (byte) Integer.parseInt(args[3]) : (byte) 0; if(Material.matchMaterial(type)==null){ if(type.equalsIgnoreCase("default")){ /****************************** * Default setting price ******************************/ plugin.sendPlayerMessage(player, "Click on the chest store to set the default price to "+price+" gold nuggets"); plugin.getServer().getPluginManager().registerEvents(new PriceSetListener(plugin,player,price,true), plugin); return true; }else{ plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+" Unknown material used to set the price. Use '/rs help material' to list material names."); return true; } } MaterialData material = new MaterialData(Material.matchMaterial(type),data); plugin.sendPlayerMessage(player, "Click on the chest store to set the price of "+material.toString()+" to a price of "+price+" gold nuggets"); plugin.getServer().getPluginManager().registerEvents(new PriceSetListener(plugin,player,price,material), plugin); return true; }catch(NumberFormatException e){ plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+" Invalid material data. Use '/rs help material' to list material names and data values."); return true; } } /*************************** * Tap setting price ***************************/ plugin.getServer().getPluginManager().registerEvents(new PriceSetListener(plugin,player,price), plugin); plugin.sendPlayerMessage(player, "Click on the chest store with an item to set the price of that item to "+price+" gold nuggets."); return true; }catch(NumberFormatException e){ plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+" Improper price. Use '/rs help price' for proper RealStore price setting usage."); return true; } } /******************************************************** * Setting Coffers *******************************************************/ if(rsCommand.equals("coffer")){ if(args.length<2){ plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+" Do you wish to add or remove a coffer? Use '/rs help coffer' for more information."); return true; } String cofferCommand = args[1].toLowerCase(); /**************************** * Adding a coffer ****************************/ if(cofferCommand.equals("add")){ plugin.getServer().getPluginManager().registerEvents(new CofferManagementListener(plugin,player,false), plugin); plugin.sendPlayerMessage(player, "Click on a chest to add it to your coffers."); return true; } /***************************** * Removing a coffer *****************************/ if(cofferCommand.equals("remove")){ plugin.getServer().getPluginManager().registerEvents(new CofferManagementListener(plugin,player,true), plugin); plugin.sendPlayerMessage(player, "Click on a chest to remove it from your coffers."); return true; } plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+" Unknown coffer command! Use '/rs help coffer' for more information."); return true; } /** * TODO: Add a method for store owners to check prices */ /********************************************************** * Unknown RealStore Command **********************************************************/ plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+" Unknown RealStore command! Use '/rs help' for more information."); return true; } return false; }
public boolean onCommand(CommandSender sender, Command cmd, String label,String[] args){ if(cmd.getName().equalsIgnoreCase("rs") || cmd.getName().equalsIgnoreCase("RealStore")){ if(!(sender instanceof Player)){ plugin.logMessage("RealStore interactions may only be used by Players!"); return true; } Player player = (Player) sender; if(!player.hasPermission("RealStore.*")){ plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+"You do not have permission to do that."); return true; } if(args.length<1){ plugin.sendPlayerMessage(player,ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+"No RealStore command found! Please use '/rs help' for proper RealStore usage. "); return true; } String rsCommand = args[0].toLowerCase(); /************************************************************ * Getting Help ************************************************************/ if(rsCommand.equals("help")){ plugin.sendHelpInfo(player, (args.length<2 ? null : args[1]) ); return true; } /********************************************************** * Setting Stores **********************************************************/ if(rsCommand.equals("store")){ if(args.length<2){ plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+" Do you wish to add or remove a store? Use '/rs help store' for more information."); return true; } String storeCommand = args[1].toLowerCase(); /**************************** * Adding a store ****************************/ if(storeCommand.equals("add")){ if(!plugin.hasCoffer(player)){ plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+" You have no coffers! Use '/rs help coffer' for more information."); return true; } plugin.sendPlayerMessage(player, "Click on a chest to create a store."); plugin.getServer().getPluginManager().registerEvents(new StoreManagementListener(plugin, player),plugin); return true; } /***************************** * Removing a store *****************************/ if(storeCommand.equals("remove")){ plugin.getServer().getPluginManager().registerEvents(new StoreManagementListener(plugin,player,true), plugin); plugin.sendPlayerMessage(player, "Click on the chest store to remove the store."); return true; } plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+" Unknown store command! Use '/rs help store' for more information."); return true; } /************************************************************** * Setting Prices **************************************************************/ if(rsCommand.equals("price")){ if(args.length<2){ plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+" No price found. Use '/rs help price' for proper RealStore price setting usage."); return true; } if(!plugin.hasCoffer(player)){ plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+" You do not have any coffers. Create a coffer first. Use '/rs help coffer' for more."); return true; } if(!plugin.hasStore(player)){ plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+" You do not have any stores on which to set prices. Create a store first. Use '/rs help store' for more."); return true; } try{ Integer price = Integer.parseInt(args[1]); if(price<=0){ plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+" The price must be greater than zero!"); return true; } /******************************** * Command setting price ********************************/ if(args.length>2){ String type = args[2]; try{ Byte data = args.length>3 ? (byte) Integer.parseInt(args[3]) : (byte) 0; if(Material.matchMaterial(type)==null){ if(type.equalsIgnoreCase("default")){ /****************************** * Default setting price ******************************/ plugin.sendPlayerMessage(player, "Click on the chest store to set the default price to "+price+" gold nuggets"); plugin.getServer().getPluginManager().registerEvents(new PriceSetListener(plugin,player,price,true), plugin); return true; }else{ plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+" Unknown material used to set the price. Use '/rs help material' to list material names."); return true; } } MaterialData material = new MaterialData(Material.matchMaterial(type),data); plugin.sendPlayerMessage(player, "Click on the chest store to set the price of "+material.toString()+" to a price of "+price+" gold nuggets"); plugin.getServer().getPluginManager().registerEvents(new PriceSetListener(plugin,player,price,material), plugin); return true; }catch(NumberFormatException e){ plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+" Invalid material data. Use '/rs help material' to list material names and data values."); return true; } } /*************************** * Tap setting price ***************************/ plugin.getServer().getPluginManager().registerEvents(new PriceSetListener(plugin,player,price), plugin); plugin.sendPlayerMessage(player, "Click on the chest store with an item to set the price of that item to "+price+" gold nuggets."); return true; }catch(NumberFormatException e){ plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+" Improper price. Use '/rs help price' for proper RealStore price setting usage."); return true; } } /******************************************************** * Setting Coffers *******************************************************/ if(rsCommand.equals("coffer")){ if(args.length<2){ plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+" Do you wish to add or remove a coffer? Use '/rs help coffer' for more information."); return true; } String cofferCommand = args[1].toLowerCase(); /**************************** * Adding a coffer ****************************/ if(cofferCommand.equals("add")){ plugin.getServer().getPluginManager().registerEvents(new CofferManagementListener(plugin,player,false), plugin); plugin.sendPlayerMessage(player, "Click on a chest to add it to your coffers."); return true; } /***************************** * Removing a coffer *****************************/ if(cofferCommand.equals("remove")){ plugin.getServer().getPluginManager().registerEvents(new CofferManagementListener(plugin,player,true), plugin); plugin.sendPlayerMessage(player, "Click on a chest to remove it from your coffers."); return true; } plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+" Unknown coffer command! Use '/rs help coffer' for more information."); return true; } /** * TODO: Add a method for store owners to check prices */ /********************************************************** * Unknown RealStore Command **********************************************************/ plugin.sendPlayerMessage(player, ChatColor.DARK_RED+"Error: "+ChatColor.WHITE+" Unknown RealStore command! Use '/rs help' for more information."); return true; } return false; }
diff --git a/src/main/java/org/elasticsearch/transport/couchbase/capi/ElasticSearchCAPIBehavior.java b/src/main/java/org/elasticsearch/transport/couchbase/capi/ElasticSearchCAPIBehavior.java index 5756b5a..b72ea3c 100644 --- a/src/main/java/org/elasticsearch/transport/couchbase/capi/ElasticSearchCAPIBehavior.java +++ b/src/main/java/org/elasticsearch/transport/couchbase/capi/ElasticSearchCAPIBehavior.java @@ -1,353 +1,353 @@ /** * Copyright (c) 2012 Couchbase, 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 org.elasticsearch.transport.couchbase.capi; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.UUID; import org.codehaus.jackson.map.ObjectMapper; import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequestBuilder; import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse; import org.elasticsearch.action.bulk.BulkItemResponse; import org.elasticsearch.action.bulk.BulkRequestBuilder; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.delete.DeleteRequest; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.get.MultiGetItemResponse; import org.elasticsearch.action.get.MultiGetResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.client.Client; import org.elasticsearch.common.Base64; import org.elasticsearch.common.logging.ESLogger; import com.couchbase.capi.CAPIBehavior; public class ElasticSearchCAPIBehavior implements CAPIBehavior { protected ObjectMapper mapper = new ObjectMapper(); protected Client client; protected ESLogger logger; protected String defaultDocumentType; protected String checkpointDocumentType; protected String dynamicTypePath; protected boolean resolveConflicts; public ElasticSearchCAPIBehavior(Client client, ESLogger logger, String defaultDocumentType, String checkpointDocumentType, String dynamicTypePath, boolean resolveConflicts) { this.client = client; this.logger = logger; this.defaultDocumentType = defaultDocumentType; this.checkpointDocumentType = checkpointDocumentType; this.dynamicTypePath = dynamicTypePath; this.resolveConflicts = resolveConflicts; } @Override public boolean databaseExists(String database) { String index = getElasticSearchIndexNameFromDatabase(database); IndicesExistsRequestBuilder existsBuilder = client.admin().indices().prepareExists(index); IndicesExistsResponse response = existsBuilder.execute().actionGet(); if(response.exists()) { return true; } return false; } @Override public Map<String, Object> getDatabaseDetails(String database) { if(databaseExists(database)) { Map<String, Object> responseMap = new HashMap<String, Object>(); responseMap.put("db_name", getDatabaseNameWithoutUUID(database)); return responseMap; } return null; } @Override public boolean createDatabase(String database) { throw new UnsupportedOperationException("Creating indexes is not supported"); } @Override public boolean deleteDatabase(String database) { throw new UnsupportedOperationException("Deleting indexes is not supported"); } @Override public boolean ensureFullCommit(String database) { return true; } @Override public Map<String, Object> revsDiff(String database, Map<String, Object> revsMap) { logger.trace("_revs_diff request for {} : {}", database, revsMap); // start with all entries in the response map Map<String, Object> responseMap = new HashMap<String, Object>(); for (Entry<String, Object> entry : revsMap.entrySet()) { String id = entry.getKey(); String revs = (String)entry.getValue(); Map<String, String> rev = new HashMap<String, String>(); rev.put("missing", revs); responseMap.put(id, rev); } logger.trace("_revs_diff response for {} is: {}", database, responseMap); // if resolve conflicts mode is enabled // perform a multi-get query to find information // about revisions we already have if (resolveConflicts) { String index = getElasticSearchIndexNameFromDatabase(database); MultiGetResponse response = client.prepareMultiGet().add(index, defaultDocumentType, responseMap.keySet()).execute().actionGet(); if(response != null) { Iterator<MultiGetItemResponse> iterator = response.iterator(); while(iterator.hasNext()) { MultiGetItemResponse item = iterator.next(); if(item.response().exists()) { String itemId = item.id(); Map<String, Object> source = item.response().sourceAsMap(); if(source != null) { Map<String, Object> meta = (Map<String, Object>)source.get("meta"); if(meta != null) { String rev = (String)meta.get("rev"); //retrieve the revision passed in from Couchbase Map<String, String> sourceRevMap = (Map<String, String>)responseMap.get(itemId); String sourceRev = sourceRevMap.get("missing"); if(rev.equals(sourceRev)) { // if our revision is the same as the source rev // remove it from the response map responseMap.remove(itemId); logger.trace("_revs_diff already have id: {} rev: {}", itemId, rev); } } } } } } logger.trace("_revs_diff response AFTER conflict resolution {}", responseMap); } return responseMap; } @Override public List<Object> bulkDocs(String database, List<Map<String, Object>> docs) { String index = getElasticSearchIndexNameFromDatabase(database); BulkRequestBuilder bulkBuilder = client.prepareBulk(); // keep a map of the id - rev for building the response Map<String,String> revisions = new HashMap<String, String>(); for (Map<String, Object> doc : docs) { logger.debug("Bulk doc entry is {}", docs); // these are the top-level elements that could be in the document sent by Couchbase Map<String, Object> meta = (Map<String, Object>)doc.get("meta"); Map<String, Object> json = (Map<String, Object>)doc.get("json"); String base64 = (String)doc.get("base64"); if(meta == null) { // if there is no meta-data section, there is nothing we can do logger.warn("Document without meta in bulk_docs, ignoring...."); continue; - } else if("non-JSON mode".equals(meta.get("attr_reason"))) { + } else if("non-JSON mode".equals(meta.get("att_reason"))) { // optimization, this tells us the body isn't json json = new HashMap<String, Object>(); } else if(json == null && base64 != null) { // no plain json, let's try parsing the base64 data try { byte[] decodedData = Base64.decode(base64); try { - // now try to parse the decoded data as json - json = (Map<String, Object>) mapper.readValue(decodedData, Map.class); + // now try to parse the decoded data as json + json = (Map<String, Object>) mapper.readValue(decodedData, Map.class); } catch(IOException e) { logger.error("Unable to parse decoded base64 data as JSON, indexing stub for id: {}", meta.get("id")); logger.error("Body was: {} Parse error was: {}", new String(decodedData), e); json = new HashMap<String, Object>(); } } catch (IOException e) { logger.error("Unable to decoded base64, indexing stub for id: {}", meta.get("id")); logger.error("Base64 was was: {} Parse error was: {}", base64, e); json = new HashMap<String, Object>(); } } // at this point we know we have the document meta-data // and the document contents to be indexed are in json Map<String, Object> toBeIndexed = new HashMap<String, Object>(); toBeIndexed.put("meta", meta); toBeIndexed.put("doc", json); String id = (String)meta.get("id"); String rev = (String)meta.get("rev"); revisions.put(id, rev); long ttl = 0; Integer expiration = (Integer)meta.get("expiration"); if(expiration != null) { ttl = (expiration.longValue() * 1000) - System.currentTimeMillis(); } String type = defaultDocumentType; if(id.startsWith("_local/")) { type = checkpointDocumentType; } boolean deleted = meta.containsKey("deleted") ? (Boolean)meta.get("deleted") : false; if(deleted) { DeleteRequest deleteRequest = client.prepareDelete(index, type, id).request(); bulkBuilder.add(deleteRequest); } else { IndexRequestBuilder indexBuilder = client.prepareIndex(index, type, id); indexBuilder.setSource(toBeIndexed); if(ttl > 0) { indexBuilder.setTTL(ttl); } IndexRequest indexRequest = indexBuilder.request(); bulkBuilder.add(indexRequest); } } List<Object> result = new ArrayList<Object>(); BulkResponse response = bulkBuilder.execute().actionGet(); if(response != null) { for (BulkItemResponse bulkItemResponse : response.items()) { Map<String, Object> itemResponse = new HashMap<String, Object>(); String itemId = bulkItemResponse.getId(); itemResponse.put("id", itemId); if(bulkItemResponse.failed()) { itemResponse.put("error", "failed"); itemResponse.put("reason", bulkItemResponse.failureMessage()); } else { itemResponse.put("rev", revisions.get(itemId)); } result.add(itemResponse); } } return result; } @Override public Map<String, Object> getDocument(String database, String docId) { return getDocumentElasticSearch(getElasticSearchIndexNameFromDatabase(database), docId, defaultDocumentType); } @Override public Map<String, Object> getLocalDocument(String database, String docId) { return getDocumentElasticSearch(getElasticSearchIndexNameFromDatabase(database), docId, checkpointDocumentType); } protected Map<String, Object> getDocumentElasticSearch(String index, String docId, String docType) { GetResponse response = client.prepareGet(index, docType, docId).execute().actionGet(); if(response != null && response.exists()) { Map<String,Object> esDocument = response.sourceAsMap(); return (Map<String, Object>)esDocument.get("doc"); } return null; } @Override public String storeDocument(String database, String docId, Map<String, Object> document) { return storeDocumentElasticSearch(getElasticSearchIndexNameFromDatabase(database), docId, document, defaultDocumentType); } @Override public String storeLocalDocument(String database, String docId, Map<String, Object> document) { return storeDocumentElasticSearch(getElasticSearchIndexNameFromDatabase(database), docId, document, checkpointDocumentType); } protected String storeDocumentElasticSearch(String index, String docId, Map<String, Object> document, String docType) { // normally we just use the revision number present in the document String documentRevision = (String)document.get("_rev"); if(documentRevision == null) { // if there isn't one we need to generate a revision number documentRevision = generateRevisionNumber(); document.put("_rev", documentRevision); } IndexRequestBuilder indexBuilder = client.prepareIndex(index, docType, docId); indexBuilder.setSource(document); IndexResponse response = indexBuilder.execute().actionGet(); if(response != null) { return documentRevision; } return null; } protected String generateRevisionNumber() { String documentRevision = "1-" + UUID.randomUUID().toString(); return documentRevision; } @Override public InputStream getAttachment(String database, String docId, String attachmentName) { throw new UnsupportedOperationException("Attachments are not supported"); } @Override public String storeAttachment(String database, String docId, String attachmentName, String contentType, InputStream input) { throw new UnsupportedOperationException("Attachments are not supported"); } @Override public InputStream getLocalAttachment(String databsae, String docId, String attachmentName) { throw new UnsupportedOperationException("Attachments are not supported"); } @Override public String storeLocalAttachment(String database, String docId, String attachmentName, String contentType, InputStream input) { throw new UnsupportedOperationException("Attachments are not supported"); } protected String getElasticSearchIndexNameFromDatabase(String database) { String[] pieces = database.split("/", 2); if(pieces.length < 2) { return database; } else { return pieces[0]; } } protected String getDatabaseNameWithoutUUID(String database) { int semicolonIndex = database.indexOf(';'); if(semicolonIndex >= 0) { return database.substring(0, semicolonIndex); } return database; } }
false
true
public List<Object> bulkDocs(String database, List<Map<String, Object>> docs) { String index = getElasticSearchIndexNameFromDatabase(database); BulkRequestBuilder bulkBuilder = client.prepareBulk(); // keep a map of the id - rev for building the response Map<String,String> revisions = new HashMap<String, String>(); for (Map<String, Object> doc : docs) { logger.debug("Bulk doc entry is {}", docs); // these are the top-level elements that could be in the document sent by Couchbase Map<String, Object> meta = (Map<String, Object>)doc.get("meta"); Map<String, Object> json = (Map<String, Object>)doc.get("json"); String base64 = (String)doc.get("base64"); if(meta == null) { // if there is no meta-data section, there is nothing we can do logger.warn("Document without meta in bulk_docs, ignoring...."); continue; } else if("non-JSON mode".equals(meta.get("attr_reason"))) { // optimization, this tells us the body isn't json json = new HashMap<String, Object>(); } else if(json == null && base64 != null) { // no plain json, let's try parsing the base64 data try { byte[] decodedData = Base64.decode(base64); try { // now try to parse the decoded data as json json = (Map<String, Object>) mapper.readValue(decodedData, Map.class); } catch(IOException e) { logger.error("Unable to parse decoded base64 data as JSON, indexing stub for id: {}", meta.get("id")); logger.error("Body was: {} Parse error was: {}", new String(decodedData), e); json = new HashMap<String, Object>(); } } catch (IOException e) { logger.error("Unable to decoded base64, indexing stub for id: {}", meta.get("id")); logger.error("Base64 was was: {} Parse error was: {}", base64, e); json = new HashMap<String, Object>(); } } // at this point we know we have the document meta-data // and the document contents to be indexed are in json Map<String, Object> toBeIndexed = new HashMap<String, Object>(); toBeIndexed.put("meta", meta); toBeIndexed.put("doc", json); String id = (String)meta.get("id"); String rev = (String)meta.get("rev"); revisions.put(id, rev); long ttl = 0; Integer expiration = (Integer)meta.get("expiration"); if(expiration != null) { ttl = (expiration.longValue() * 1000) - System.currentTimeMillis(); } String type = defaultDocumentType; if(id.startsWith("_local/")) { type = checkpointDocumentType; } boolean deleted = meta.containsKey("deleted") ? (Boolean)meta.get("deleted") : false; if(deleted) { DeleteRequest deleteRequest = client.prepareDelete(index, type, id).request(); bulkBuilder.add(deleteRequest); } else { IndexRequestBuilder indexBuilder = client.prepareIndex(index, type, id); indexBuilder.setSource(toBeIndexed); if(ttl > 0) { indexBuilder.setTTL(ttl); } IndexRequest indexRequest = indexBuilder.request(); bulkBuilder.add(indexRequest); } } List<Object> result = new ArrayList<Object>(); BulkResponse response = bulkBuilder.execute().actionGet(); if(response != null) { for (BulkItemResponse bulkItemResponse : response.items()) { Map<String, Object> itemResponse = new HashMap<String, Object>(); String itemId = bulkItemResponse.getId(); itemResponse.put("id", itemId); if(bulkItemResponse.failed()) { itemResponse.put("error", "failed"); itemResponse.put("reason", bulkItemResponse.failureMessage()); } else { itemResponse.put("rev", revisions.get(itemId)); } result.add(itemResponse); } } return result; }
public List<Object> bulkDocs(String database, List<Map<String, Object>> docs) { String index = getElasticSearchIndexNameFromDatabase(database); BulkRequestBuilder bulkBuilder = client.prepareBulk(); // keep a map of the id - rev for building the response Map<String,String> revisions = new HashMap<String, String>(); for (Map<String, Object> doc : docs) { logger.debug("Bulk doc entry is {}", docs); // these are the top-level elements that could be in the document sent by Couchbase Map<String, Object> meta = (Map<String, Object>)doc.get("meta"); Map<String, Object> json = (Map<String, Object>)doc.get("json"); String base64 = (String)doc.get("base64"); if(meta == null) { // if there is no meta-data section, there is nothing we can do logger.warn("Document without meta in bulk_docs, ignoring...."); continue; } else if("non-JSON mode".equals(meta.get("att_reason"))) { // optimization, this tells us the body isn't json json = new HashMap<String, Object>(); } else if(json == null && base64 != null) { // no plain json, let's try parsing the base64 data try { byte[] decodedData = Base64.decode(base64); try { // now try to parse the decoded data as json json = (Map<String, Object>) mapper.readValue(decodedData, Map.class); } catch(IOException e) { logger.error("Unable to parse decoded base64 data as JSON, indexing stub for id: {}", meta.get("id")); logger.error("Body was: {} Parse error was: {}", new String(decodedData), e); json = new HashMap<String, Object>(); } } catch (IOException e) { logger.error("Unable to decoded base64, indexing stub for id: {}", meta.get("id")); logger.error("Base64 was was: {} Parse error was: {}", base64, e); json = new HashMap<String, Object>(); } } // at this point we know we have the document meta-data // and the document contents to be indexed are in json Map<String, Object> toBeIndexed = new HashMap<String, Object>(); toBeIndexed.put("meta", meta); toBeIndexed.put("doc", json); String id = (String)meta.get("id"); String rev = (String)meta.get("rev"); revisions.put(id, rev); long ttl = 0; Integer expiration = (Integer)meta.get("expiration"); if(expiration != null) { ttl = (expiration.longValue() * 1000) - System.currentTimeMillis(); } String type = defaultDocumentType; if(id.startsWith("_local/")) { type = checkpointDocumentType; } boolean deleted = meta.containsKey("deleted") ? (Boolean)meta.get("deleted") : false; if(deleted) { DeleteRequest deleteRequest = client.prepareDelete(index, type, id).request(); bulkBuilder.add(deleteRequest); } else { IndexRequestBuilder indexBuilder = client.prepareIndex(index, type, id); indexBuilder.setSource(toBeIndexed); if(ttl > 0) { indexBuilder.setTTL(ttl); } IndexRequest indexRequest = indexBuilder.request(); bulkBuilder.add(indexRequest); } } List<Object> result = new ArrayList<Object>(); BulkResponse response = bulkBuilder.execute().actionGet(); if(response != null) { for (BulkItemResponse bulkItemResponse : response.items()) { Map<String, Object> itemResponse = new HashMap<String, Object>(); String itemId = bulkItemResponse.getId(); itemResponse.put("id", itemId); if(bulkItemResponse.failed()) { itemResponse.put("error", "failed"); itemResponse.put("reason", bulkItemResponse.failureMessage()); } else { itemResponse.put("rev", revisions.get(itemId)); } result.add(itemResponse); } } return result; }
diff --git a/src/com/github/mpotacon/chatgear/muteCommand.java b/src/com/github/mpotacon/chatgear/muteCommand.java index adc6fe6..12be064 100644 --- a/src/com/github/mpotacon/chatgear/muteCommand.java +++ b/src/com/github/mpotacon/chatgear/muteCommand.java @@ -1,41 +1,41 @@ package com.github.mpotacon.chatgear; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class muteCommand implements CommandExecutor { @Override public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){ if(commandLabel.equalsIgnoreCase("mute")){ if(sender.hasPermission("chatgear.mute")){ if(args.length == 1){ Player player = Bukkit.getServer().getPlayer(args[0]); if(player.isOnline()){ if(player.isOp()){ - sender.sendMessage("You can not mute " + player); + sender.sendMessage(ChatColor.RED + "You can not mute " + player); return false; } else if(chatListener.mutedPlayers.containsKey(player.getName())){ chatListener.mutedPlayers.remove(player.getName()); } else { chatListener.mutedPlayers.put(player.getName(), null); return true; } } - sender.sendMessage("Player not online."); + sender.sendMessage(ChatColor.RED + "Player is not online."); return false; } - sender.sendMessage("/mute <playername>"); + sender.sendMessage(ChatColor.RED +"/mute <playername>"); return false; } sender.sendMessage(ChatColor.RED + "You do not have permission to mute a player"); return false; } return false; } }
false
true
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){ if(commandLabel.equalsIgnoreCase("mute")){ if(sender.hasPermission("chatgear.mute")){ if(args.length == 1){ Player player = Bukkit.getServer().getPlayer(args[0]); if(player.isOnline()){ if(player.isOp()){ sender.sendMessage("You can not mute " + player); return false; } else if(chatListener.mutedPlayers.containsKey(player.getName())){ chatListener.mutedPlayers.remove(player.getName()); } else { chatListener.mutedPlayers.put(player.getName(), null); return true; } } sender.sendMessage("Player not online."); return false; } sender.sendMessage("/mute <playername>"); return false; } sender.sendMessage(ChatColor.RED + "You do not have permission to mute a player"); return false; } return false; }
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){ if(commandLabel.equalsIgnoreCase("mute")){ if(sender.hasPermission("chatgear.mute")){ if(args.length == 1){ Player player = Bukkit.getServer().getPlayer(args[0]); if(player.isOnline()){ if(player.isOp()){ sender.sendMessage(ChatColor.RED + "You can not mute " + player); return false; } else if(chatListener.mutedPlayers.containsKey(player.getName())){ chatListener.mutedPlayers.remove(player.getName()); } else { chatListener.mutedPlayers.put(player.getName(), null); return true; } } sender.sendMessage(ChatColor.RED + "Player is not online."); return false; } sender.sendMessage(ChatColor.RED +"/mute <playername>"); return false; } sender.sendMessage(ChatColor.RED + "You do not have permission to mute a player"); return false; } return false; }
diff --git a/xjc/test/com/sun/tools/xjc/OptionsJUTest.java b/xjc/test/com/sun/tools/xjc/OptionsJUTest.java index 79792f9f..190a94d1 100644 --- a/xjc/test/com/sun/tools/xjc/OptionsJUTest.java +++ b/xjc/test/com/sun/tools/xjc/OptionsJUTest.java @@ -1,139 +1,141 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright (c) 2011 Oracle and/or its affiliates. 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_1_1.html * or packager/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 packager/legal/LICENSE.txt. * * GPL Classpath Exception: * Oracle designates this particular file as subject to the "Classpath" * exception as provided by Oracle in the GPL Version 2 section of the License * file that accompanied this code. * * Modifications: * If applicable, add the following below the License Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyright [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.tools.xjc; import com.sun.codemodel.JClassAlreadyExistsException; import com.sun.codemodel.JCodeModel; import com.sun.codemodel.JDefinedClass; import com.sun.codemodel.JMod; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.charset.Charset; import junit.framework.TestCase; /** * * @author Lukas Jungmann */ public class OptionsJUTest extends TestCase { private Options o; public OptionsJUTest(String testName) { super(testName); } @Override protected void setUp() throws Exception { super.setUp(); o = new Options(); o.targetDir = new File(System.getProperty("java.io.tmpdir"), "jxc_optionsTest"); o.targetDir.mkdirs(); } @Override protected void tearDown() throws Exception { super.tearDown(); delDirs(o.targetDir); } public void testCreateCodeWriter() throws JClassAlreadyExistsException, IOException { JCodeModel jcm = new JCodeModel(); JDefinedClass c = jcm._class("test.TestClass"); c.constructor(JMod.PUBLIC); o.readOnly = false; //test UTF-8 o.encoding = "UTF-8"; jcm.build(o.createCodeWriter()); File cls = new File(o.targetDir, "test/TestClass.java"); FileInputStream fis = new FileInputStream(cls); - byte[] in = new byte[12]; + //same string in UTF-8 is 1byte shorter on JDK6 than on JDK5 + //therefore final check is for 'contains' and not for 'endsWith' + byte[] in = new byte[13]; fis.read(in); fis.close(); cls.delete(); String inStr = new String(in, "UTF-8"); - assertTrue("Got: '" + inStr + "'", inStr.endsWith("// This f")); + assertTrue("Got: '" + inStr + "'", inStr.contains("// This f")); //test UTF-16 o.noFileHeader = true; o.encoding = "UTF-16"; jcm.build(o.createCodeWriter()); cls = new File(o.targetDir, "test/TestClass.java"); fis = new FileInputStream(cls); - in = new byte[22]; + in = new byte[26]; fis.read(in); fis.close(); cls.delete(); inStr = new String(in, "UTF-16"); - assertTrue("Got: '" + inStr + "'", inStr.endsWith("package t")); + assertTrue("Got: '" + inStr + "'", inStr.contains("package t")); //test default encoding o.noFileHeader = false; o.encoding = null; jcm.build(o.createCodeWriter()); cls = new File(o.targetDir, "test/TestClass.java"); fis = new FileInputStream(cls); //this should handle also UTF-32... in = new byte[84]; fis.read(in); fis.close(); cls.delete(); - inStr = new String(in, Charset.defaultCharset()); + inStr = new String(in, Charset.defaultCharset().name()); assertTrue("Got: '" + inStr + "'", inStr.contains("// This f")); } private static void delDirs(File... dirs) { for (File dir : dirs) { if (!dir.exists()) { continue; } if (dir.isDirectory()) { for (File f : dir.listFiles()) { delDirs(f); } dir.delete(); } else { dir.delete(); } } } }
false
true
public void testCreateCodeWriter() throws JClassAlreadyExistsException, IOException { JCodeModel jcm = new JCodeModel(); JDefinedClass c = jcm._class("test.TestClass"); c.constructor(JMod.PUBLIC); o.readOnly = false; //test UTF-8 o.encoding = "UTF-8"; jcm.build(o.createCodeWriter()); File cls = new File(o.targetDir, "test/TestClass.java"); FileInputStream fis = new FileInputStream(cls); byte[] in = new byte[12]; fis.read(in); fis.close(); cls.delete(); String inStr = new String(in, "UTF-8"); assertTrue("Got: '" + inStr + "'", inStr.endsWith("// This f")); //test UTF-16 o.noFileHeader = true; o.encoding = "UTF-16"; jcm.build(o.createCodeWriter()); cls = new File(o.targetDir, "test/TestClass.java"); fis = new FileInputStream(cls); in = new byte[22]; fis.read(in); fis.close(); cls.delete(); inStr = new String(in, "UTF-16"); assertTrue("Got: '" + inStr + "'", inStr.endsWith("package t")); //test default encoding o.noFileHeader = false; o.encoding = null; jcm.build(o.createCodeWriter()); cls = new File(o.targetDir, "test/TestClass.java"); fis = new FileInputStream(cls); //this should handle also UTF-32... in = new byte[84]; fis.read(in); fis.close(); cls.delete(); inStr = new String(in, Charset.defaultCharset()); assertTrue("Got: '" + inStr + "'", inStr.contains("// This f")); }
public void testCreateCodeWriter() throws JClassAlreadyExistsException, IOException { JCodeModel jcm = new JCodeModel(); JDefinedClass c = jcm._class("test.TestClass"); c.constructor(JMod.PUBLIC); o.readOnly = false; //test UTF-8 o.encoding = "UTF-8"; jcm.build(o.createCodeWriter()); File cls = new File(o.targetDir, "test/TestClass.java"); FileInputStream fis = new FileInputStream(cls); //same string in UTF-8 is 1byte shorter on JDK6 than on JDK5 //therefore final check is for 'contains' and not for 'endsWith' byte[] in = new byte[13]; fis.read(in); fis.close(); cls.delete(); String inStr = new String(in, "UTF-8"); assertTrue("Got: '" + inStr + "'", inStr.contains("// This f")); //test UTF-16 o.noFileHeader = true; o.encoding = "UTF-16"; jcm.build(o.createCodeWriter()); cls = new File(o.targetDir, "test/TestClass.java"); fis = new FileInputStream(cls); in = new byte[26]; fis.read(in); fis.close(); cls.delete(); inStr = new String(in, "UTF-16"); assertTrue("Got: '" + inStr + "'", inStr.contains("package t")); //test default encoding o.noFileHeader = false; o.encoding = null; jcm.build(o.createCodeWriter()); cls = new File(o.targetDir, "test/TestClass.java"); fis = new FileInputStream(cls); //this should handle also UTF-32... in = new byte[84]; fis.read(in); fis.close(); cls.delete(); inStr = new String(in, Charset.defaultCharset().name()); assertTrue("Got: '" + inStr + "'", inStr.contains("// This f")); }
diff --git a/genie-server/src/test/java/com/netflix/genie/server/metrics/TestGenieNodeStatistics.java b/genie-server/src/test/java/com/netflix/genie/server/metrics/TestGenieNodeStatistics.java index 1f725ef860..d02617d0d8 100644 --- a/genie-server/src/test/java/com/netflix/genie/server/metrics/TestGenieNodeStatistics.java +++ b/genie-server/src/test/java/com/netflix/genie/server/metrics/TestGenieNodeStatistics.java @@ -1,171 +1,171 @@ /* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.server.metrics; import java.util.concurrent.atomic.AtomicLong; import org.junit.Assert; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import com.netflix.config.ConfigurationManager; import com.netflix.genie.common.exceptions.CloudServiceException; import com.netflix.genie.server.persistence.PersistenceManager; /** * Test case for GenieNodeStatistics. * * @author skrishnan */ public class TestGenieNodeStatistics { private static GenieNodeStatistics stats; /** * Initialize stats object before any tests are run. */ @BeforeClass public static void init() { stats = GenieNodeStatistics.getInstance(); PersistenceManager.init(); JobCountManager.init(); } /** * Test the counter that increments 200 error codes (success). */ @Test public void test2xxCounter() { // incr 2xx count twice stats.setGenie2xxCount(new AtomicLong(0)); stats.incrGenie2xxCount(); stats.incrGenie2xxCount(); System.out.println("Received: " + stats.getGenie2xxCount().longValue()); Assert.assertEquals(stats.getGenie2xxCount().longValue(), 2L); } /** * Test the counter that increments 400 error codes (~bad requests). */ @Test public void test4xxCounter() { // incr 4xx count 4 times stats.setGenie4xxCount(new AtomicLong(0)); stats.incrGenie4xxCount(); stats.incrGenie4xxCount(); stats.incrGenie4xxCount(); stats.incrGenie4xxCount(); System.out.println("Received: " + stats.getGenie4xxCount().longValue()); Assert.assertEquals(stats.getGenie4xxCount().longValue(), 4L); } /** * Test the counter that increments 500 error codes (server errors). */ @Test public void test5xxCounter() { // incr 5xx count 5 times stats.setGenie5xxCount(new AtomicLong(0)); stats.incrGenie5xxCount(); stats.incrGenie5xxCount(); stats.incrGenie5xxCount(); stats.incrGenie5xxCount(); stats.incrGenie5xxCount(); System.out.println("Received: " + stats.getGenie5xxCount().longValue()); Assert.assertEquals(stats.getGenie5xxCount().longValue(), 5L); } /** * Test the counter that increments job submissions. */ @Test public void testJobSubCounter() { // incr job submissions once stats.setGenieJobSubmissions(new AtomicLong(0)); stats.incrGenieJobSubmissions(); Assert.assertEquals(stats.getGenieJobSubmissions().longValue(), 1L); } /** * Test the counter that increments job failures. */ @Test public void testFailedJobCounter() { // incr failed jobs once stats.setGenieFailedJobs(new AtomicLong(0)); stats.incrGenieFailedJobs(); Assert.assertEquals(stats.getGenieFailedJobs().longValue(), 1L); } /** * Test the counter that increments job kills. */ @Test public void testKilledJobCounter() { // incr killed jobs twice stats.setGenieKilledJobs(new AtomicLong(0)); stats.incrGenieKilledJobs(); stats.incrGenieKilledJobs(); Assert.assertEquals(stats.getGenieKilledJobs().longValue(), 2L); } /** * Test the counter that increments job success. */ @Test public void testSuccessJobCounter() { // incr successful jobs thrice stats.setGenieSuccessfulJobs(new AtomicLong(0)); stats.incrGenieSuccessfulJobs(); stats.incrGenieSuccessfulJobs(); stats.incrGenieSuccessfulJobs(); Assert.assertEquals(stats.getGenieSuccessfulJobs().longValue(), 3L); } /** * Test the counter and daemon thread that sets running job. * * @throws InterruptedException * @throws CloudServiceException */ @Test public void testRunningJobs() throws InterruptedException, CloudServiceException { // get number of running jobs before we get started int numRunningJobs = JobCountManager.getNumInstanceJobs(); stats.setGenieRunningJobs(0); Assert.assertEquals(stats.getGenieRunningJobs().intValue(), 0); ConfigurationManager.getConfigInstance().setProperty("netflix.genie.server.metrics.sleep.ms", new Long(2000)); stats.setGenieRunningJobs(5); Assert.assertEquals(stats.getGenieRunningJobs().intValue(), 5); // sleep for a while - number of running jobs should be same as what we started with - Thread.sleep(15000); + Thread.sleep(30000); Assert.assertEquals(numRunningJobs, stats.getGenieRunningJobs().intValue()); } /** * Shutdown stats object after test is done. */ @AfterClass public static void shutdown() { // shut down cleanly stats.shutdown(); } }
true
true
public void testRunningJobs() throws InterruptedException, CloudServiceException { // get number of running jobs before we get started int numRunningJobs = JobCountManager.getNumInstanceJobs(); stats.setGenieRunningJobs(0); Assert.assertEquals(stats.getGenieRunningJobs().intValue(), 0); ConfigurationManager.getConfigInstance().setProperty("netflix.genie.server.metrics.sleep.ms", new Long(2000)); stats.setGenieRunningJobs(5); Assert.assertEquals(stats.getGenieRunningJobs().intValue(), 5); // sleep for a while - number of running jobs should be same as what we started with Thread.sleep(15000); Assert.assertEquals(numRunningJobs, stats.getGenieRunningJobs().intValue()); }
public void testRunningJobs() throws InterruptedException, CloudServiceException { // get number of running jobs before we get started int numRunningJobs = JobCountManager.getNumInstanceJobs(); stats.setGenieRunningJobs(0); Assert.assertEquals(stats.getGenieRunningJobs().intValue(), 0); ConfigurationManager.getConfigInstance().setProperty("netflix.genie.server.metrics.sleep.ms", new Long(2000)); stats.setGenieRunningJobs(5); Assert.assertEquals(stats.getGenieRunningJobs().intValue(), 5); // sleep for a while - number of running jobs should be same as what we started with Thread.sleep(30000); Assert.assertEquals(numRunningJobs, stats.getGenieRunningJobs().intValue()); }
diff --git a/servicemix-jsr181/src/main/java/org/apache/servicemix/jsr181/Jsr181ExchangeProcessor.java b/servicemix-jsr181/src/main/java/org/apache/servicemix/jsr181/Jsr181ExchangeProcessor.java index d8e189cf0..e53ccc79c 100644 --- a/servicemix-jsr181/src/main/java/org/apache/servicemix/jsr181/Jsr181ExchangeProcessor.java +++ b/servicemix-jsr181/src/main/java/org/apache/servicemix/jsr181/Jsr181ExchangeProcessor.java @@ -1,122 +1,120 @@ /* * Copyright 2005-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. */ package org.apache.servicemix.jsr181; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import javax.jbi.messaging.DeliveryChannel; import javax.jbi.messaging.ExchangeStatus; import javax.jbi.messaging.Fault; import javax.jbi.messaging.InOptionalOut; import javax.jbi.messaging.InOut; import javax.jbi.messaging.MessageExchange; import javax.jbi.messaging.NormalizedMessage; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.transform.Source; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import org.apache.servicemix.common.ExchangeProcessor; import org.apache.servicemix.jbi.jaxp.StringSource; import org.apache.servicemix.jsr181.xfire.JbiTransport; import org.codehaus.xfire.MessageContext; import org.codehaus.xfire.XFire; import org.codehaus.xfire.exchange.InMessage; import org.codehaus.xfire.service.Service; import org.codehaus.xfire.transport.Channel; import org.codehaus.xfire.transport.Transport; public class Jsr181ExchangeProcessor implements ExchangeProcessor { protected DeliveryChannel channel; protected Jsr181Endpoint endpoint; public Jsr181ExchangeProcessor(Jsr181Endpoint endpoint) { this.endpoint = endpoint; } public void process(MessageExchange exchange) throws Exception { if (exchange.getStatus() == ExchangeStatus.DONE) { return; } else if (exchange.getStatus() == ExchangeStatus.ERROR) { - exchange.setStatus(ExchangeStatus.DONE); - channel.send(exchange); return; } // TODO: fault should not be serialized as soap // TODO: clean this code XFire xfire = endpoint.getXFire(); Service service = endpoint.getXFireService(); Transport t = xfire.getTransportManager().getTransport(JbiTransport.JBI_BINDING); ByteArrayOutputStream out = new ByteArrayOutputStream(); Channel c = t.createChannel(); MessageContext ctx = new MessageContext(); ctx.setXFire(xfire); ctx.setService(service); ctx.setProperty(Channel.BACKCHANNEL_URI, out); ctx.setExchange(new org.codehaus.xfire.exchange.MessageExchange(ctx)); InMessage msg = new InMessage(); ctx.getExchange().setInMessage(msg); NormalizedMessage in = exchange.getMessage("in"); msg.setXMLStreamReader(getXMLStreamReader(in.getContent())); c.receive(ctx, msg); // Set response or DONE status if (isInAndOut(exchange)) { if (ctx.getExchange().hasFaultMessage() && ctx.getExchange().getFaultMessage().getBody() != null) { Fault fault = exchange.createFault(); fault.setContent(new StringSource(out.toString())); exchange.setFault(fault); exchange.setStatus(ExchangeStatus.ERROR); } else { NormalizedMessage outMsg = exchange.createMessage(); outMsg.setContent(new StringSource(out.toString())); exchange.setMessage(outMsg, "out"); } } else { exchange.setStatus(ExchangeStatus.DONE); } channel.send(exchange); } public void start() throws Exception { channel = endpoint.getServiceUnit().getComponent().getComponentContext().getDeliveryChannel(); } public void stop() throws Exception { } protected XMLStreamReader getXMLStreamReader(Source source) throws TransformerException, XMLStreamException { try { return XMLInputFactory.newInstance().createXMLStreamReader(source); } catch (Exception e) { // ignore, as this method is not mandatory in stax } ByteArrayOutputStream buffer = new ByteArrayOutputStream(); TransformerFactory.newInstance().newTransformer().transform(source, new StreamResult(buffer)); return XMLInputFactory.newInstance().createXMLStreamReader(new ByteArrayInputStream(buffer.toByteArray())); } protected boolean isInAndOut(MessageExchange exchange) { return exchange instanceof InOut || exchange instanceof InOptionalOut; } }
true
true
public void process(MessageExchange exchange) throws Exception { if (exchange.getStatus() == ExchangeStatus.DONE) { return; } else if (exchange.getStatus() == ExchangeStatus.ERROR) { exchange.setStatus(ExchangeStatus.DONE); channel.send(exchange); return; } // TODO: fault should not be serialized as soap // TODO: clean this code XFire xfire = endpoint.getXFire(); Service service = endpoint.getXFireService(); Transport t = xfire.getTransportManager().getTransport(JbiTransport.JBI_BINDING); ByteArrayOutputStream out = new ByteArrayOutputStream(); Channel c = t.createChannel(); MessageContext ctx = new MessageContext(); ctx.setXFire(xfire); ctx.setService(service); ctx.setProperty(Channel.BACKCHANNEL_URI, out); ctx.setExchange(new org.codehaus.xfire.exchange.MessageExchange(ctx)); InMessage msg = new InMessage(); ctx.getExchange().setInMessage(msg); NormalizedMessage in = exchange.getMessage("in"); msg.setXMLStreamReader(getXMLStreamReader(in.getContent())); c.receive(ctx, msg); // Set response or DONE status if (isInAndOut(exchange)) { if (ctx.getExchange().hasFaultMessage() && ctx.getExchange().getFaultMessage().getBody() != null) { Fault fault = exchange.createFault(); fault.setContent(new StringSource(out.toString())); exchange.setFault(fault); exchange.setStatus(ExchangeStatus.ERROR); } else { NormalizedMessage outMsg = exchange.createMessage(); outMsg.setContent(new StringSource(out.toString())); exchange.setMessage(outMsg, "out"); } } else { exchange.setStatus(ExchangeStatus.DONE); } channel.send(exchange); }
public void process(MessageExchange exchange) throws Exception { if (exchange.getStatus() == ExchangeStatus.DONE) { return; } else if (exchange.getStatus() == ExchangeStatus.ERROR) { return; } // TODO: fault should not be serialized as soap // TODO: clean this code XFire xfire = endpoint.getXFire(); Service service = endpoint.getXFireService(); Transport t = xfire.getTransportManager().getTransport(JbiTransport.JBI_BINDING); ByteArrayOutputStream out = new ByteArrayOutputStream(); Channel c = t.createChannel(); MessageContext ctx = new MessageContext(); ctx.setXFire(xfire); ctx.setService(service); ctx.setProperty(Channel.BACKCHANNEL_URI, out); ctx.setExchange(new org.codehaus.xfire.exchange.MessageExchange(ctx)); InMessage msg = new InMessage(); ctx.getExchange().setInMessage(msg); NormalizedMessage in = exchange.getMessage("in"); msg.setXMLStreamReader(getXMLStreamReader(in.getContent())); c.receive(ctx, msg); // Set response or DONE status if (isInAndOut(exchange)) { if (ctx.getExchange().hasFaultMessage() && ctx.getExchange().getFaultMessage().getBody() != null) { Fault fault = exchange.createFault(); fault.setContent(new StringSource(out.toString())); exchange.setFault(fault); exchange.setStatus(ExchangeStatus.ERROR); } else { NormalizedMessage outMsg = exchange.createMessage(); outMsg.setContent(new StringSource(out.toString())); exchange.setMessage(outMsg, "out"); } } else { exchange.setStatus(ExchangeStatus.DONE); } channel.send(exchange); }
diff --git a/src/org/broad/igv/DirectoryManager.java b/src/org/broad/igv/DirectoryManager.java index f8a88d75..99ab5d04 100644 --- a/src/org/broad/igv/DirectoryManager.java +++ b/src/org/broad/igv/DirectoryManager.java @@ -1,437 +1,437 @@ /* * Copyright (c) 2007-2012 The Broad Institute, Inc. * SOFTWARE COPYRIGHT NOTICE * This software and its documentation are the copyright of the Broad Institute, Inc. All rights are reserved. * * This software is supplied without any warranty or guaranteed support whatsoever. The Broad Institute is not responsible for its use, misuse, or functionality. * * This software is licensed under the terms of the GNU Lesser General Public License (LGPL), * Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php. */ package org.broad.igv; import org.apache.batik.css.engine.value.css2.CursorManager; import org.apache.commons.io.FileUtils; import org.apache.log4j.*; import org.broad.igv.exceptions.DataLoadException; import org.broad.igv.ui.WaitCursorManager; import org.broad.igv.ui.util.MessageUtils; import org.broad.igv.ui.util.ProgressBar; import org.broad.igv.util.RuntimeUtils; import javax.swing.*; import javax.swing.filechooser.FileSystemView; import java.io.File; import java.io.IOException; import java.util.concurrent.ExecutionException; import java.util.prefs.Preferences; /** * @author Jim Robinson * @date 3/19/12 */ public class DirectoryManager { private static Logger log = Logger.getLogger(DirectoryManager.class); private static File USER_HOME; private static File USER_DIRECTORY; // FileSystemView.getFileSystemView().getDefaultDirectory(); private static File IGV_DIRECTORY; // The IGV application directory private static File GENOME_CACHE_DIRECTORY; private static File GENE_LIST_DIRECTORY; private static File BAM_CACHE_DIRECTORY; final public static String IGV_DIR_USERPREF = "igvDir"; private static File getUserHome() { if (USER_HOME == null) { String userHomeString = System.getProperty("user.home"); USER_HOME = new File(userHomeString); } return USER_HOME; } /** * The user directory. On Mac and Linux this should be the user home directory. On Windows platforms this * is the "My Documents" directory. */ public static synchronized File getUserDirectory() { if (USER_DIRECTORY == null) { System.out.print("Fetching user directory... "); USER_DIRECTORY = FileSystemView.getFileSystemView().getDefaultDirectory(); //Mostly for testing, in some environments USER_DIRECTORY can be null if (USER_DIRECTORY == null) { USER_DIRECTORY = getUserHome(); } } return USER_DIRECTORY; } public static File getIgvDirectory() { if (IGV_DIRECTORY == null) { IGV_DIRECTORY = getIgvDirectoryOverride(); // If still null, try the default place if (IGV_DIRECTORY == null) { File rootDir = getUserHome(); IGV_DIRECTORY = new File(rootDir, "igv"); if (!IGV_DIRECTORY.exists()) { // See if a pre-2.1 release directory exists, if so copy it File legacyDirectory = null; try { legacyDirectory = getLegacyIGVDirectory(); if (legacyDirectory.exists()) { log.info("Copying " + legacyDirectory + " => " + IGV_DIRECTORY); FileUtils.copyDirectory(legacyDirectory, IGV_DIRECTORY); } } catch (IOException e) { log.error("Error copying igv directory " + legacyDirectory + " => " + IGV_DIRECTORY, e); } } if (!IGV_DIRECTORY.exists()) { try { boolean wasSuccessful = IGV_DIRECTORY.mkdir(); if (!wasSuccessful) { System.err.println("Failed to create user directory!"); IGV_DIRECTORY = null; } } catch (Exception e) { log.error("Error creating igv directory", e); } } } // The IGV directory either doesn't exist or isn't writeable. This situation can arise with Windows Vista // and Windows 7 due to a Java bug (http://bugs.sun.com/view_bug.do?bug_id=4787931) - if (!(IGV_DIRECTORY.exists() && canWrite(IGV_DIRECTORY))) { + if (IGV_DIRECTORY == null || !IGV_DIRECTORY.exists() || !canWrite(IGV_DIRECTORY)) { if (Globals.isHeadless() || Globals.isSuppressMessages()) { System.err.println("Cannot write to igv directory: " + IGV_DIRECTORY.getAbsolutePath()); IGV_DIRECTORY = (new File(".")).getParentFile(); } else { int option = JOptionPane.showConfirmDialog(null, "<html>The default IGV directory (" + IGV_DIRECTORY + ") " + "cannot be accessed. Click Yes to choose a new folder or No to exit.<br>" + "This folder will be used to store user preferences and cached genomes.", "IGV Directory Error", JOptionPane.YES_NO_OPTION); if (option == JOptionPane.YES_OPTION) { final JFileChooser fc = new JFileChooser(); fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int retValue = fc.showOpenDialog(null); if (retValue == JFileChooser.APPROVE_OPTION) { IGV_DIRECTORY = fc.getSelectedFile(); Preferences prefs = Preferences.userNodeForPackage(Globals.class); prefs.put(IGV_DIR_USERPREF, IGV_DIRECTORY.getAbsolutePath()); } } } } if (!IGV_DIRECTORY.canRead()) { throw new DataLoadException("Cannot read from user directory", IGV_DIRECTORY.getAbsolutePath()); } else if (!canWrite(IGV_DIRECTORY)) { throw new DataLoadException("Cannot write to user directory", IGV_DIRECTORY.getAbsolutePath()); } } return IGV_DIRECTORY; } private static File getIgvDirectoryOverride() { Preferences userPrefs = null; File override = null; try { // See if an override location has been specified. This is stored with the Java Preferences API userPrefs = Preferences.userNodeForPackage(Globals.class); String userDir = userPrefs.get(IGV_DIR_USERPREF, null); if (userDir != null) { override = new File(userDir); if (!override.exists()) { override = null; userPrefs.remove(IGV_DIR_USERPREF); } } } catch (Exception e) { userPrefs.remove(IGV_DIR_USERPREF); override = null; System.err.println("Error creating user directory"); e.printStackTrace(); } return override; } public static File getGenomeCacheDirectory() { if (GENOME_CACHE_DIRECTORY == null) { //Create the Genome Cache GENOME_CACHE_DIRECTORY = new File(getIgvDirectory(), "genomes"); if (!GENOME_CACHE_DIRECTORY.exists()) { GENOME_CACHE_DIRECTORY.mkdir(); } if (!GENOME_CACHE_DIRECTORY.canRead()) { throw new DataLoadException("Cannot read from user directory", GENOME_CACHE_DIRECTORY.getAbsolutePath()); } else if (!GENOME_CACHE_DIRECTORY.canWrite()) { throw new DataLoadException("Cannot write to user directory", GENOME_CACHE_DIRECTORY.getAbsolutePath()); } } return GENOME_CACHE_DIRECTORY; } public static File getGeneListDirectory() { if (GENE_LIST_DIRECTORY == null) { GENE_LIST_DIRECTORY = new File(getIgvDirectory(), "lists"); if (!GENE_LIST_DIRECTORY.exists()) { GENE_LIST_DIRECTORY.mkdir(); } if (!GENE_LIST_DIRECTORY.canRead()) { throw new DataLoadException("Cannot read from user directory", GENE_LIST_DIRECTORY.getAbsolutePath()); } else if (!GENE_LIST_DIRECTORY.canWrite()) { throw new DataLoadException("Cannot write to user directory", GENE_LIST_DIRECTORY.getAbsolutePath()); } } return GENE_LIST_DIRECTORY; } public static synchronized File getCacheDirectory() { if (BAM_CACHE_DIRECTORY == null) { File defaultDir = getIgvDirectory(); if (defaultDir.exists()) { BAM_CACHE_DIRECTORY = new File(defaultDir, "bam"); if (!BAM_CACHE_DIRECTORY.exists()) { BAM_CACHE_DIRECTORY.mkdir(); } } } return BAM_CACHE_DIRECTORY; } public static synchronized File getSamDirectory() { File samDir = new File(DirectoryManager.getIgvDirectory(), "sam"); if (!samDir.exists()) { samDir.mkdir(); } return samDir; } public static synchronized File getLogFile() throws IOException { File logFile = new File(getIgvDirectory(), "igv.log"); if (!logFile.exists()) { logFile.createNewFile(); } return logFile; } /** * Return the user preferences property file ("~/igv/prefs.properties"). * * @return */ public static synchronized File getPreferencesFile() { File igvDirectoy = getIgvDirectory(); File igvPropertyFile = new File(igvDirectoy, "prefs.properties"); // If the property file doesn't exist, try the "legacy" location. This should only make a difference for Macs if (!igvPropertyFile.exists()) { File oldFile = getLegacyPreferencesFile(); if (oldFile.exists()) { try { // Copy contents to new location. Leave oldFile in place for compatibility with earlier IGV releases FileUtils.copyFile(oldFile, igvPropertyFile); } catch (IOException e) { log.error("Error copy property file from: " + oldFile + " to: " + igvPropertyFile, e); } } } if (!igvPropertyFile.exists()) { try { igvPropertyFile.createNewFile(); } catch (IOException e) { log.error("Could not create property file: " + igvPropertyFile, e); } } return igvPropertyFile; } /** * Move the "igv" directory to a new location, copying all contents. Returns True if the directory * is successfully moved, irrespective of any errors that might occur later (e.g. when attempting to * remove the old directory). * * @param newDirectory * @return True if the directory is successfully moved, false otherwise */ public static Boolean moveIGVDirectory(final File newDirectory) { if (newDirectory.equals(IGV_DIRECTORY)) { return false; // Nothing to do } if (IGV_DIRECTORY != null && IGV_DIRECTORY.exists()) { File oldDirectory = IGV_DIRECTORY; try { System.out.println("Moving directory"); FileUtils.copyDirectory(IGV_DIRECTORY, newDirectory); IGV_DIRECTORY = newDirectory; // Store location of new directory in Java preferences node (not pref.properties) Preferences prefs = Preferences.userNodeForPackage(Globals.class); prefs.put(IGV_DIR_USERPREF, newDirectory.getAbsolutePath()); // Update preference manager with new file location PreferenceManager.getInstance().setPrefsFile(getPreferencesFile().getAbsolutePath()); } catch (IOException e) { log.error("Error copying IGV directory", e); MessageUtils.showMessage("<html>Error moving IGV directory:<br/>&nbsp;nbsp;" + e.getMessage()); return false; } // Restart the log LogManager.shutdown(); initializeLog(); // Try to delete the old directory try { deleteDirectory(oldDirectory); } catch (IOException e) { log.error("An error was encountered deleting the previous IGV directory", e); MessageUtils.showMessage("<html>An error was encountered deleting the previous IGV directory (" + e.getMessage() + "):<br>&nbsp;nbsp;nbsp;" + oldDirectory.getAbsolutePath() + "<br>Remaining files should be manually deleted."); } } GENOME_CACHE_DIRECTORY = null; GENE_LIST_DIRECTORY = null; BAM_CACHE_DIRECTORY = null; return true; } /** * Delete the directory and all contents recursively. The apache FileUtils is hanging on Linux. * * @param oldDirectory * @throws IOException */ private static void deleteDirectory(File oldDirectory) throws IOException { if (Globals.IS_LINUX || Globals.IS_MAC) { //System.out.println("Deleting: " + oldDirectory); String result = RuntimeUtils.executeShellCommand("rm -rf " + oldDirectory.getAbsolutePath()); if(result != null && result.trim().length() > 0) { log.info("Response from 'rm -rf': " + result); } } else { // The apache commons FileUtils is not working reliably org.broad.igv.util.FileUtils.deleteDir(oldDirectory); } } /** * Return the pre 2.1 release properties file. This may or may not exist. * * @return */ private static synchronized File getLegacyPreferencesFile() { File rootDir = getLegacyIGVDirectory(); return new File(rootDir, "prefs.properties"); } /** * REturn the pre 2.1 release IGV directory. This differs from the current location only for Macs. * * @return */ private static File getLegacyIGVDirectory() { File rootDir = getUserHome(); if (Globals.IS_MAC) { rootDir = new File(rootDir, ".igv"); } else { rootDir = new File(rootDir, "igv"); } return rootDir; } private static boolean canWrite(File directory) { // There are bugs in the Windows Java JVM that can cause user directories to be non-writable (target fix is // Java 7). The only way to know if the directory is writable for sure is to try to write something. if (Globals.IS_WINDOWS) { File testFile = null; try { testFile = new File(directory, "igv332415dsfjdsklt.testfile"); if (testFile.exists()) { testFile.delete(); } testFile.deleteOnExit(); testFile.createNewFile(); return testFile.exists(); } catch (IOException e) { return false; } finally { if (testFile.exists()) { testFile.delete(); } } } else { return directory.canWrite(); } } public static void initializeLog() { Logger logger = Logger.getRootLogger(); PatternLayout layout = new PatternLayout(); layout.setConversionPattern("%p [%d{ISO8601}] [%F:%L] %m%n"); // Create a log file that is ready to have text appended to it try { File logFile = getLogFile(); RollingFileAppender appender = new RollingFileAppender(); appender.setName("IGV_ROLLING_APPENDER"); appender.setFile(logFile.getAbsolutePath()); appender.setThreshold(Level.ALL); appender.setMaxFileSize("1000KB"); appender.setMaxBackupIndex(1); appender.setLayout(layout); appender.setAppend(true); appender.activateOptions(); logger.addAppender(appender); } catch (IOException e) { // Can't create log file, just log to console System.err.println("Error creating log file"); e.printStackTrace(); ConsoleAppender consoleAppender = new ConsoleAppender(); logger.addAppender(consoleAppender); } } }
true
true
public static File getIgvDirectory() { if (IGV_DIRECTORY == null) { IGV_DIRECTORY = getIgvDirectoryOverride(); // If still null, try the default place if (IGV_DIRECTORY == null) { File rootDir = getUserHome(); IGV_DIRECTORY = new File(rootDir, "igv"); if (!IGV_DIRECTORY.exists()) { // See if a pre-2.1 release directory exists, if so copy it File legacyDirectory = null; try { legacyDirectory = getLegacyIGVDirectory(); if (legacyDirectory.exists()) { log.info("Copying " + legacyDirectory + " => " + IGV_DIRECTORY); FileUtils.copyDirectory(legacyDirectory, IGV_DIRECTORY); } } catch (IOException e) { log.error("Error copying igv directory " + legacyDirectory + " => " + IGV_DIRECTORY, e); } } if (!IGV_DIRECTORY.exists()) { try { boolean wasSuccessful = IGV_DIRECTORY.mkdir(); if (!wasSuccessful) { System.err.println("Failed to create user directory!"); IGV_DIRECTORY = null; } } catch (Exception e) { log.error("Error creating igv directory", e); } } } // The IGV directory either doesn't exist or isn't writeable. This situation can arise with Windows Vista // and Windows 7 due to a Java bug (http://bugs.sun.com/view_bug.do?bug_id=4787931) if (!(IGV_DIRECTORY.exists() && canWrite(IGV_DIRECTORY))) { if (Globals.isHeadless() || Globals.isSuppressMessages()) { System.err.println("Cannot write to igv directory: " + IGV_DIRECTORY.getAbsolutePath()); IGV_DIRECTORY = (new File(".")).getParentFile(); } else { int option = JOptionPane.showConfirmDialog(null, "<html>The default IGV directory (" + IGV_DIRECTORY + ") " + "cannot be accessed. Click Yes to choose a new folder or No to exit.<br>" + "This folder will be used to store user preferences and cached genomes.", "IGV Directory Error", JOptionPane.YES_NO_OPTION); if (option == JOptionPane.YES_OPTION) { final JFileChooser fc = new JFileChooser(); fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int retValue = fc.showOpenDialog(null); if (retValue == JFileChooser.APPROVE_OPTION) { IGV_DIRECTORY = fc.getSelectedFile(); Preferences prefs = Preferences.userNodeForPackage(Globals.class); prefs.put(IGV_DIR_USERPREF, IGV_DIRECTORY.getAbsolutePath()); } } } } if (!IGV_DIRECTORY.canRead()) { throw new DataLoadException("Cannot read from user directory", IGV_DIRECTORY.getAbsolutePath()); } else if (!canWrite(IGV_DIRECTORY)) { throw new DataLoadException("Cannot write to user directory", IGV_DIRECTORY.getAbsolutePath()); } } return IGV_DIRECTORY; }
public static File getIgvDirectory() { if (IGV_DIRECTORY == null) { IGV_DIRECTORY = getIgvDirectoryOverride(); // If still null, try the default place if (IGV_DIRECTORY == null) { File rootDir = getUserHome(); IGV_DIRECTORY = new File(rootDir, "igv"); if (!IGV_DIRECTORY.exists()) { // See if a pre-2.1 release directory exists, if so copy it File legacyDirectory = null; try { legacyDirectory = getLegacyIGVDirectory(); if (legacyDirectory.exists()) { log.info("Copying " + legacyDirectory + " => " + IGV_DIRECTORY); FileUtils.copyDirectory(legacyDirectory, IGV_DIRECTORY); } } catch (IOException e) { log.error("Error copying igv directory " + legacyDirectory + " => " + IGV_DIRECTORY, e); } } if (!IGV_DIRECTORY.exists()) { try { boolean wasSuccessful = IGV_DIRECTORY.mkdir(); if (!wasSuccessful) { System.err.println("Failed to create user directory!"); IGV_DIRECTORY = null; } } catch (Exception e) { log.error("Error creating igv directory", e); } } } // The IGV directory either doesn't exist or isn't writeable. This situation can arise with Windows Vista // and Windows 7 due to a Java bug (http://bugs.sun.com/view_bug.do?bug_id=4787931) if (IGV_DIRECTORY == null || !IGV_DIRECTORY.exists() || !canWrite(IGV_DIRECTORY)) { if (Globals.isHeadless() || Globals.isSuppressMessages()) { System.err.println("Cannot write to igv directory: " + IGV_DIRECTORY.getAbsolutePath()); IGV_DIRECTORY = (new File(".")).getParentFile(); } else { int option = JOptionPane.showConfirmDialog(null, "<html>The default IGV directory (" + IGV_DIRECTORY + ") " + "cannot be accessed. Click Yes to choose a new folder or No to exit.<br>" + "This folder will be used to store user preferences and cached genomes.", "IGV Directory Error", JOptionPane.YES_NO_OPTION); if (option == JOptionPane.YES_OPTION) { final JFileChooser fc = new JFileChooser(); fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int retValue = fc.showOpenDialog(null); if (retValue == JFileChooser.APPROVE_OPTION) { IGV_DIRECTORY = fc.getSelectedFile(); Preferences prefs = Preferences.userNodeForPackage(Globals.class); prefs.put(IGV_DIR_USERPREF, IGV_DIRECTORY.getAbsolutePath()); } } } } if (!IGV_DIRECTORY.canRead()) { throw new DataLoadException("Cannot read from user directory", IGV_DIRECTORY.getAbsolutePath()); } else if (!canWrite(IGV_DIRECTORY)) { throw new DataLoadException("Cannot write to user directory", IGV_DIRECTORY.getAbsolutePath()); } } return IGV_DIRECTORY; }
diff --git a/src/main/java/net/daboross/bukkitdev/uberchat/UberChat.java b/src/main/java/net/daboross/bukkitdev/uberchat/UberChat.java index 3cd0ac1..2b0f8e7 100644 --- a/src/main/java/net/daboross/bukkitdev/uberchat/UberChat.java +++ b/src/main/java/net/daboross/bukkitdev/uberchat/UberChat.java @@ -1,59 +1,59 @@ package net.daboross.bukkitdev.uberchat; import net.daboross.bukkitdev.uberchat.commandexecutors.ColorizorExecutor; import net.daboross.bukkitdev.uberchat.commandexecutors.MeExecutor; import net.daboross.bukkitdev.uberchat.commandexecutors.MsgExecutor; import net.daboross.bukkitdev.uberchat.commandexecutors.ReplyExecutor; import net.daboross.bukkitdev.uberchat.commandexecutors.ShoutExecutor; import org.bukkit.command.PluginCommand; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; /** * UberChat Plugin Made By DaboRoss * * @author daboross */ public final class UberChat extends JavaPlugin { @Override public void onEnable() { registerEvents(); assignCommands(); getLogger().info("UberChat Fully Enabled"); } @Override public void onDisable() { getLogger().info("UberChat Fully Disabled"); } private void registerEvents() { PluginManager pm = this.getServer().getPluginManager(); UberChatListener uberChatListener = new UberChatListener(); pm.registerEvents(uberChatListener, this); } private void assignCommands() { - PluginCommand colorizor = getCommand("colorizor"); - if (colorizor != null) { - colorizor.setExecutor(new ColorizorExecutor()); + PluginCommand colorize = getCommand("colorize"); + if (colorize != null) { + colorize.setExecutor(new ColorizorExecutor()); } PluginCommand me = getCommand("me"); if (me != null) { me.setExecutor(new MeExecutor()); } PluginCommand msg = getCommand("msg"); if (msg != null) { msg.setExecutor(new MsgExecutor()); } PluginCommand reply = getCommand("reply"); if (reply != null) { reply.setExecutor(new ReplyExecutor()); } PluginCommand shout = getCommand("shout"); if (shout != null) { shout.setExecutor(new ShoutExecutor()); } } }
true
true
private void assignCommands() { PluginCommand colorizor = getCommand("colorizor"); if (colorizor != null) { colorizor.setExecutor(new ColorizorExecutor()); } PluginCommand me = getCommand("me"); if (me != null) { me.setExecutor(new MeExecutor()); } PluginCommand msg = getCommand("msg"); if (msg != null) { msg.setExecutor(new MsgExecutor()); } PluginCommand reply = getCommand("reply"); if (reply != null) { reply.setExecutor(new ReplyExecutor()); } PluginCommand shout = getCommand("shout"); if (shout != null) { shout.setExecutor(new ShoutExecutor()); } }
private void assignCommands() { PluginCommand colorize = getCommand("colorize"); if (colorize != null) { colorize.setExecutor(new ColorizorExecutor()); } PluginCommand me = getCommand("me"); if (me != null) { me.setExecutor(new MeExecutor()); } PluginCommand msg = getCommand("msg"); if (msg != null) { msg.setExecutor(new MsgExecutor()); } PluginCommand reply = getCommand("reply"); if (reply != null) { reply.setExecutor(new ReplyExecutor()); } PluginCommand shout = getCommand("shout"); if (shout != null) { shout.setExecutor(new ShoutExecutor()); } }
diff --git a/admin/src/main/java/org/jboss/capedwarf/admin/TimeFormatter.java b/admin/src/main/java/org/jboss/capedwarf/admin/TimeFormatter.java index 94e117e6..5b5bd0f3 100644 --- a/admin/src/main/java/org/jboss/capedwarf/admin/TimeFormatter.java +++ b/admin/src/main/java/org/jboss/capedwarf/admin/TimeFormatter.java @@ -1,37 +1,37 @@ /* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., 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.capedwarf.admin; import javax.inject.Named; import java.util.Date; /** * @author <a href="mailto:[email protected]">Marko Luksa</a> */ @Named public class TimeFormatter { - public String format(long millis) { - return new Date(millis).toString(); + public String format(long usec) { + return new Date(usec / 1000).toString(); } }
true
true
public String format(long millis) { return new Date(millis).toString(); }
public String format(long usec) { return new Date(usec / 1000).toString(); }
diff --git a/app/models/Line.java b/app/models/Line.java index 752ef5c..50650bd 100644 --- a/app/models/Line.java +++ b/app/models/Line.java @@ -1,55 +1,55 @@ package models; import play.data.validation.Email; import play.data.validation.Required; import play.modules.morphia.Model; import play.modules.morphia.Model.AutoTimestamp; import com.google.code.morphia.annotations.Entity; import com.google.code.morphia.annotations.Reference; @AutoTimestamp @Entity public class Line extends Model { // @Required // public int id; @Required @Reference public Budget budget; @Reference public User user; @Required public int line_number; @Required public String name; @Required public double subtotal; public int parent_line_id; @Required public int order; - public Line(Budget budget, User user, int line_number, String name, double subtotal, int parent_line_id, int order) { + public Line(Budget budget, User user, int lineNumber, String name, double subtotal, int parent_line_id, int order) { // this.id = id; this.budget = budget; this.user = user; - this.line_number = line_number; + this.line_number = lineNumber; this.name = name; this.subtotal = subtotal; this.parent_line_id = parent_line_id; this.order = order; } public String toString() { return name; } }
false
true
public Line(Budget budget, User user, int line_number, String name, double subtotal, int parent_line_id, int order) { // this.id = id; this.budget = budget; this.user = user; this.line_number = line_number; this.name = name; this.subtotal = subtotal; this.parent_line_id = parent_line_id; this.order = order; }
public Line(Budget budget, User user, int lineNumber, String name, double subtotal, int parent_line_id, int order) { // this.id = id; this.budget = budget; this.user = user; this.line_number = lineNumber; this.name = name; this.subtotal = subtotal; this.parent_line_id = parent_line_id; this.order = order; }
diff --git a/src/ServiceDiscovery/ServiceDiscovery.java b/src/ServiceDiscovery/ServiceDiscovery.java index a0e7f043..62c2fc4c 100644 --- a/src/ServiceDiscovery/ServiceDiscovery.java +++ b/src/ServiceDiscovery/ServiceDiscovery.java @@ -1,519 +1,522 @@ /* * ServiceDiscovery.java * * Created on 4.06.2005, 21:12 * Copyright (c) 2005-2008, Eugene Stahov (evgs), http://bombus-im.org * * 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. * * You can also redistribute and/or modify this program under the * terms of the Psi License, specified in the accompanied COPYING * file, as published by the Psi Project; either dated January 1st, * 2005, 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 library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package ServiceDiscovery; //#ifndef WMUC import Conference.ConferenceForm; //#endif import images.RosterIcons; import java.util.*; //#ifndef MENU_LISTENER //# import javax.microedition.lcdui.CommandListener; //# import javax.microedition.lcdui.Command; //#else import Menu.MenuListener; import Menu.Command; import Menu.MyMenu; //#endif import javax.microedition.lcdui.Display; import javax.microedition.lcdui.Displayable; import locale.SR; import Colors.ColorTheme; import ui.*; import com.alsutton.jabber.*; import com.alsutton.jabber.datablocks.*; import Client.*; import ui.MainBar; import io.NvStorage; import java.io.DataInputStream; import java.io.EOFException; import ui.controls.AlertBox; import xmpp.XmppError; /** * * @author Evg_S */ public class ServiceDiscovery extends VirtualList implements //#ifndef MENU_LISTENER //# CommandListener, //#else MenuListener, //#endif JabberBlockListener { private final static String NS_ITEMS="http://jabber.org/protocol/disco#items"; private final static String NS_INFO="http://jabber.org/protocol/disco#info"; private final static String NS_REGS="jabber:iq:register"; private final static String NS_SRCH="jabber:iq:search"; private final static String NS_GATE="jabber:iq:gateway"; private final static String NS_MUC="http://jabber.org/protocol/muc"; private final static String NODE_CMDS="http://jabber.org/protocol/commands"; private final static String strCmds="Execute"; private final int AD_HOC_INDEX=17; private Command cmdOk=new Command(SR.MS_BROWSE, Command.SCREEN, 1); private Command cmdRfsh=new Command(SR.MS_REFRESH, Command.SCREEN, 2); private Command cmdFeatures=new Command(SR.MS_FEATURES, Command.SCREEN, 3); private Command cmdSrv=new Command(SR.MS_SERVER, Command.SCREEN, 10); //private Command cmdAdd=new Command(SR.MS_ADD_TO_ROSTER, Command.SCREEN, 11); //FS#464 => this string is commented in SR.java' private Command cmdBack=new Command(SR.MS_BACK, Command.BACK, 98); private Command cmdCancel=new Command(SR.MS_CANCEL, Command.EXIT, 99); private StaticData sd=StaticData.getInstance(); private Vector items; private Vector stackItems=new Vector(); private Vector features; private Vector cmds; private String service; private String node; private int discoIcon; private JabberStream stream; /** Creates a new instance of ServiceDiscovery */ public ServiceDiscovery(Display display, String service, String node, boolean search) { super(display); setMainBarItem(new MainBar(3, null, null, false)); getMainBarItem().addRAlign(); getMainBarItem().addElement(null); stream=sd.roster.theStream; stream.cancelBlockListenerByClass(this.getClass()); stream.addBlockListener(this); //sd.roster.discoveryListener=this; //#ifdef MENU_LISTENER menuCommands.removeAllElements(); //#else //# addCommand(cmdBack); //#endif setCommandListener(this); addCommand(cmdRfsh); addCommand(cmdSrv); addCommand(cmdFeatures); //addCommand(cmdAdd); addCommand(cmdCancel); items=new Vector(); features=new Vector(); this.node=node; if (service!=null && search) { this.service=service; requestQuery(NS_SRCH, "discosrch"); } else if (service!=null) { this.service=service; requestQuery(NS_INFO, "disco"); } else { this.service=null; String myServer=sd.account.getServer(); items.addElement(new DiscoContact(null, myServer, 0)); try { DataInputStream is=NvStorage.ReadFileRecord("disco", 0); try { while (true) { String recent=is.readUTF(); if (myServer.equals(recent)) continue; //only one instance for our service items.addElement(new DiscoContact(null, recent, 0)); } } catch (EOFException e) { is.close(); } } catch (Exception e) {} //sort(items); discoIcon=0; mainbarUpdate(); moveCursorHome(); redraw(); } } private String discoId(String id) { return id+service.hashCode(); } public int getItemCount(){ return items.size();} public VirtualElement getItemRef(int index) { return (VirtualElement) items.elementAt(index);} protected void beginPaint(){ getMainBarItem().setElementAt(sd.roster.getEventIcon(), 4); } private void mainbarUpdate(){ getMainBarItem().setElementAt(new Integer(discoIcon), 0); getMainBarItem().setElementAt((service==null)?SR.MS_RECENT:service, 2); getMainBarItem().setElementAt(sd.roster.getEventIcon(), 4); int size=0; try { size=items.size(); } catch (Exception e) {} String count=null; removeCommand(cmdOk); if (size>0) { //#ifdef MENU_LISTENER menuCommands.insertElementAt(cmdOk, 0); //#else //# addCommand(cmdOk); //#endif count=" ("+size+") "; } getMainBarItem().setElementAt(count,1); } private void requestQuery(String namespace, String id){ discoIcon=RosterIcons.ICON_PROGRESS_INDEX; mainbarUpdate(); redraw(); JabberDataBlock req=new Iq(service, Iq.TYPE_GET, discoId(id)); JabberDataBlock qry=req.addChildNs("query", namespace); qry.setAttribute("node", node); //stream.addBlockListener(this); //System.out.println(">> "+req.toString()); stream.send(req); } private void requestCommand(String namespace, String id){ discoIcon=RosterIcons.ICON_PROGRESS_INDEX; mainbarUpdate(); redraw(); JabberDataBlock req=new Iq(service, Iq.TYPE_SET, id); JabberDataBlock qry=req.addChildNs("command", namespace); qry.setAttribute("node", node); qry.setAttribute("action", "execute"); //stream.addBlockListener(this); //System.out.println(req.toString()); stream.send(req); } public int blockArrived(JabberDataBlock data) { if (!(data instanceof Iq)) return JabberBlockListener.BLOCK_REJECTED; String id=data.getAttribute("id"); if (!id.startsWith("disco")) return JabberBlockListener.BLOCK_REJECTED; if (data.getTypeAttribute().equals("error")) { //System.out.println(data.toString()); discoIcon=RosterIcons.ICON_ERROR_INDEX; mainbarUpdate(); //redraw(); XmppError xe=XmppError.findInStanza(data); new AlertBox(data.getAttribute("from"), xe.toString(), display, this) { public void yes() { }; public void no() { }; }; return JabberBlockListener.BLOCK_PROCESSED; } JabberDataBlock command1=data.getChildBlock("query"); JabberDataBlock command2=data.getChildBlock("command"); if (command1==null) { if (command2!=null) { command1=command2; } - if (command1.getAttribute("node").startsWith("http://jabber.org/protocol/rc#")) id="discocmd"; //hack + String node = command1.getAttribute("node"); + if ((node!=null) && (node.startsWith("http://jabber.org/protocol/rc#"))) + id="discocmd"; //hack + node=null; } JabberDataBlock query=data.getChildBlock((id.equals("discocmd"))?"command":"query"); Vector childs=query.getChildBlocks(); //System.out.println(id); if (id.equals(discoId("disco2"))) { Vector items=new Vector(); if (childs!=null) for (Enumeration e=childs.elements(); e.hasMoreElements(); ){ JabberDataBlock i=(JabberDataBlock)e.nextElement(); if (i.getTagName().equals("item")){ String name=i.getAttribute("name"); String jid=i.getAttribute("jid"); String node=i.getAttribute("node"); Object serv=null; if (node==null) { int resourcePos=jid.indexOf('/'); if (resourcePos>-1) jid=jid.substring(0, resourcePos); serv=new DiscoContact(name, jid, 0); } else { serv=new Node(name, node); } items.addElement(serv); } } showResults(items); } else if (id.equals(discoId("disco"))) { Vector cmds=new Vector(); boolean showPartialResults=false; boolean loadItems=true; boolean client=false; if (childs!=null) { JabberDataBlock identity=query.getChildBlock("identity"); if (identity!=null) { String category=identity.getAttribute("category"); String type=identity.getTypeAttribute(); if (category.equals("automation") && type.equals("command-node")) { cmds.addElement(new DiscoCommand(RosterIcons.ICON_AD_HOC, strCmds)); } if (category.equals("conference")) { cmds.addElement(new DiscoCommand(RosterIcons.ICON_GCJOIN_INDEX, SR.MS_JOIN_CONFERENCE)); if (service.indexOf('@')<=0) { loadItems=false; showPartialResults=true; cmds.addElement(new DiscoCommand(RosterIcons.ICON_ROOMLIST, SR.MS_LOAD_ROOMLIST)); } } } for (Enumeration e=childs.elements(); e.hasMoreElements();) { JabberDataBlock i=(JabberDataBlock)e.nextElement(); if (i.getTagName().equals("feature")) { String var=i.getAttribute("var"); features.addElement(var); //if (var.equals(NS_MUC)) { cmds.addElement(new DiscoCommand(RosterIcons.ICON_GCJOIN_INDEX, strJoin)); } if (var.equals(NS_SRCH)) { cmds.addElement(new DiscoCommand(RosterIcons.ICON_SEARCH_INDEX, SR.MS_SEARCH)); } if (var.equals(NS_REGS)) { cmds.addElement(new DiscoCommand(RosterIcons.ICON_REGISTER_INDEX, SR.MS_REGISTER)); } if (var.equals(NS_GATE)) { showPartialResults=true; } //if (var.equals(NODE_CMDS)) { cmds.addElement(new DiscoCommand(AD_HOC_INDEX,strCmds)); } } } } /*if (data.getAttribute("from").equals(service)) */ { //FIXME!!! this.cmds=cmds; if (loadItems) requestQuery(NS_ITEMS, "disco2"); if (showPartialResults) showResults(new Vector()); } } else if (id.startsWith ("discoreg")) { discoIcon=0; new DiscoForm(display, data, stream, "discoResult", "query"); } else if (id.startsWith("discocmd")) { discoIcon=0; new DiscoForm(display, data, stream, "discocmd", "command"); } else if (id.startsWith("discosrch")) { discoIcon=0; new DiscoForm(display, data, stream, "discoRSearch", "query"); } else if (id.startsWith("discoR")) { String text=SR.MS_DONE; String mainbar=data.getTypeAttribute(); if (mainbar.equals("error")) { text=XmppError.findInStanza(data).toString(); } if (text.equals(SR.MS_DONE) && id.endsWith("Search") ) { new SearchResult(display, data); } else { new AlertBox(mainbar, text, display, null) { public void yes() { } public void no() { } }; } } redraw(); return JabberBlockListener.BLOCK_PROCESSED; } public void eventOk(){ super.eventOk(); Object o= getFocusedObject(); if (o!=null) if (o instanceof Contact) { browse( ((Contact) o).jid.getJid(), null ); } if (o instanceof Node) { browse( service, ((Node) o).getNode() ); } } private void showResults(final Vector items) { try { sort(items); } catch (Exception e) { //e.printStackTrace(); }; /*if (data.getAttribute("from").equals(service)) - jid hashed in id attribute*/ //{ for (Enumeration e=cmds.elements(); e.hasMoreElements();) items.insertElementAt(e.nextElement(),0); this.items=items; moveCursorHome(); discoIcon=0; mainbarUpdate(); //} } public void browse(String service, String node){ State st=new State(); st.cursor=cursor; st.items=items; st.service=this.service; st.node=this.node; st.features=features; stackItems.addElement(st); items=new Vector(); features=new Vector(); removeCommand(cmdBack); addCommand(cmdBack); this.service=service; this.node=node; requestQuery(NS_INFO,"disco"); } public void commandAction(Command c, Displayable d){ if (c==cmdOk) eventOk(); if (c==cmdBack) exitDiscovery(false); if (c==cmdRfsh) { if (service!=null) requestQuery(NS_INFO, "disco"); } if (c==cmdSrv) { new ServerBox(display, this, service, this); } if (c==cmdFeatures) { new DiscoFeatures(display, service, features); } if (c==cmdCancel) exitDiscovery(true); } private void exitDiscovery(boolean cancel){ if (cancel || stackItems.isEmpty()) { stream.cancelBlockListener(this); if (display!=null && parentView!=null /*prevents potential app hiding*/ ) display.setCurrent(parentView); } else { State st=(State)stackItems.lastElement(); stackItems.removeElement(st); service=st.service; items=st.items; features=st.features; discoIcon=0; mainbarUpdate(); moveCursorTo(st.cursor); redraw(); } } public void destroyView() { exitDiscovery(false); } public void userKeyPressed(int keyCode) { super.userKeyPressed(keyCode); switch (keyCode) { case KEY_NUM4: pageLeft(); break; case KEY_NUM6: pageRight(); break; } } private class DiscoCommand extends IconTextElement { String name; int index; int icon; public DiscoCommand(int icon, String name) { super(RosterIcons.getInstance()); this.icon=icon; this.name=name; } public int getColor(){ return ColorTheme.getInstance().getColor(ColorTheme.DISCO_CMD); } public int getImageIndex() { return icon; } public String toString(){ return name; } public void onSelect(){ switch (icon) { //#ifndef WMUC case RosterIcons.ICON_GCJOIN_INDEX: { int rp=service.indexOf('@'); String room=null; String server=service; if (rp>0) { room=service.substring(0,rp); server=service.substring(rp+1); } new ConferenceForm(display, parentView, room, service, null, false); break; } //#endif case RosterIcons.ICON_SEARCH_INDEX: requestQuery(NS_SRCH, "discosrch"); break; case RosterIcons.ICON_REGISTER_INDEX: requestQuery(NS_REGS, "discoreg"); break; case RosterIcons.ICON_ROOMLIST: requestQuery(NS_ITEMS, "disco2"); break; case RosterIcons.ICON_AD_HOC: requestCommand(NODE_CMDS, "discocmd"); default: } } } private void exitDiscovery(){ stream.cancelBlockListener(this); destroyView(); } //#ifdef MENU_LISTENER protected void keyPressed(int keyCode) { //kHold=0; if (keyCode==Config.SOFT_RIGHT || keyCode==Config.KEY_BACK) { if (!reconnectWindow.getInstance().isActive()) { exitDiscovery(false); return; } } super.keyPressed(keyCode); } public void showMenu() { new MyMenu(display, parentView, this, SR.MS_DISCO, null, menuCommands); } //#endif } class State{ public String service; public String node; public Vector items; public Vector features; public int cursor; }
true
true
public int blockArrived(JabberDataBlock data) { if (!(data instanceof Iq)) return JabberBlockListener.BLOCK_REJECTED; String id=data.getAttribute("id"); if (!id.startsWith("disco")) return JabberBlockListener.BLOCK_REJECTED; if (data.getTypeAttribute().equals("error")) { //System.out.println(data.toString()); discoIcon=RosterIcons.ICON_ERROR_INDEX; mainbarUpdate(); //redraw(); XmppError xe=XmppError.findInStanza(data); new AlertBox(data.getAttribute("from"), xe.toString(), display, this) { public void yes() { }; public void no() { }; }; return JabberBlockListener.BLOCK_PROCESSED; } JabberDataBlock command1=data.getChildBlock("query"); JabberDataBlock command2=data.getChildBlock("command"); if (command1==null) { if (command2!=null) { command1=command2; } if (command1.getAttribute("node").startsWith("http://jabber.org/protocol/rc#")) id="discocmd"; //hack } JabberDataBlock query=data.getChildBlock((id.equals("discocmd"))?"command":"query"); Vector childs=query.getChildBlocks(); //System.out.println(id); if (id.equals(discoId("disco2"))) { Vector items=new Vector(); if (childs!=null) for (Enumeration e=childs.elements(); e.hasMoreElements(); ){ JabberDataBlock i=(JabberDataBlock)e.nextElement(); if (i.getTagName().equals("item")){ String name=i.getAttribute("name"); String jid=i.getAttribute("jid"); String node=i.getAttribute("node"); Object serv=null; if (node==null) { int resourcePos=jid.indexOf('/'); if (resourcePos>-1) jid=jid.substring(0, resourcePos); serv=new DiscoContact(name, jid, 0); } else { serv=new Node(name, node); } items.addElement(serv); } } showResults(items); } else if (id.equals(discoId("disco"))) { Vector cmds=new Vector(); boolean showPartialResults=false; boolean loadItems=true; boolean client=false; if (childs!=null) { JabberDataBlock identity=query.getChildBlock("identity"); if (identity!=null) { String category=identity.getAttribute("category"); String type=identity.getTypeAttribute(); if (category.equals("automation") && type.equals("command-node")) { cmds.addElement(new DiscoCommand(RosterIcons.ICON_AD_HOC, strCmds)); } if (category.equals("conference")) { cmds.addElement(new DiscoCommand(RosterIcons.ICON_GCJOIN_INDEX, SR.MS_JOIN_CONFERENCE)); if (service.indexOf('@')<=0) { loadItems=false; showPartialResults=true; cmds.addElement(new DiscoCommand(RosterIcons.ICON_ROOMLIST, SR.MS_LOAD_ROOMLIST)); } } } for (Enumeration e=childs.elements(); e.hasMoreElements();) { JabberDataBlock i=(JabberDataBlock)e.nextElement(); if (i.getTagName().equals("feature")) { String var=i.getAttribute("var"); features.addElement(var); //if (var.equals(NS_MUC)) { cmds.addElement(new DiscoCommand(RosterIcons.ICON_GCJOIN_INDEX, strJoin)); } if (var.equals(NS_SRCH)) { cmds.addElement(new DiscoCommand(RosterIcons.ICON_SEARCH_INDEX, SR.MS_SEARCH)); } if (var.equals(NS_REGS)) { cmds.addElement(new DiscoCommand(RosterIcons.ICON_REGISTER_INDEX, SR.MS_REGISTER)); } if (var.equals(NS_GATE)) { showPartialResults=true; } //if (var.equals(NODE_CMDS)) { cmds.addElement(new DiscoCommand(AD_HOC_INDEX,strCmds)); } } } } /*if (data.getAttribute("from").equals(service)) */ { //FIXME!!! this.cmds=cmds; if (loadItems) requestQuery(NS_ITEMS, "disco2"); if (showPartialResults) showResults(new Vector()); } } else if (id.startsWith ("discoreg")) {
public int blockArrived(JabberDataBlock data) { if (!(data instanceof Iq)) return JabberBlockListener.BLOCK_REJECTED; String id=data.getAttribute("id"); if (!id.startsWith("disco")) return JabberBlockListener.BLOCK_REJECTED; if (data.getTypeAttribute().equals("error")) { //System.out.println(data.toString()); discoIcon=RosterIcons.ICON_ERROR_INDEX; mainbarUpdate(); //redraw(); XmppError xe=XmppError.findInStanza(data); new AlertBox(data.getAttribute("from"), xe.toString(), display, this) { public void yes() { }; public void no() { }; }; return JabberBlockListener.BLOCK_PROCESSED; } JabberDataBlock command1=data.getChildBlock("query"); JabberDataBlock command2=data.getChildBlock("command"); if (command1==null) { if (command2!=null) { command1=command2; } String node = command1.getAttribute("node"); if ((node!=null) && (node.startsWith("http://jabber.org/protocol/rc#"))) id="discocmd"; //hack node=null; } JabberDataBlock query=data.getChildBlock((id.equals("discocmd"))?"command":"query"); Vector childs=query.getChildBlocks(); //System.out.println(id); if (id.equals(discoId("disco2"))) { Vector items=new Vector(); if (childs!=null) for (Enumeration e=childs.elements(); e.hasMoreElements(); ){ JabberDataBlock i=(JabberDataBlock)e.nextElement(); if (i.getTagName().equals("item")){ String name=i.getAttribute("name"); String jid=i.getAttribute("jid"); String node=i.getAttribute("node"); Object serv=null; if (node==null) { int resourcePos=jid.indexOf('/'); if (resourcePos>-1) jid=jid.substring(0, resourcePos); serv=new DiscoContact(name, jid, 0); } else { serv=new Node(name, node); } items.addElement(serv); } } showResults(items); } else if (id.equals(discoId("disco"))) { Vector cmds=new Vector(); boolean showPartialResults=false; boolean loadItems=true; boolean client=false; if (childs!=null) { JabberDataBlock identity=query.getChildBlock("identity"); if (identity!=null) { String category=identity.getAttribute("category"); String type=identity.getTypeAttribute(); if (category.equals("automation") && type.equals("command-node")) { cmds.addElement(new DiscoCommand(RosterIcons.ICON_AD_HOC, strCmds)); } if (category.equals("conference")) { cmds.addElement(new DiscoCommand(RosterIcons.ICON_GCJOIN_INDEX, SR.MS_JOIN_CONFERENCE)); if (service.indexOf('@')<=0) { loadItems=false; showPartialResults=true; cmds.addElement(new DiscoCommand(RosterIcons.ICON_ROOMLIST, SR.MS_LOAD_ROOMLIST)); } } } for (Enumeration e=childs.elements(); e.hasMoreElements();) { JabberDataBlock i=(JabberDataBlock)e.nextElement(); if (i.getTagName().equals("feature")) { String var=i.getAttribute("var"); features.addElement(var); //if (var.equals(NS_MUC)) { cmds.addElement(new DiscoCommand(RosterIcons.ICON_GCJOIN_INDEX, strJoin)); } if (var.equals(NS_SRCH)) { cmds.addElement(new DiscoCommand(RosterIcons.ICON_SEARCH_INDEX, SR.MS_SEARCH)); } if (var.equals(NS_REGS)) { cmds.addElement(new DiscoCommand(RosterIcons.ICON_REGISTER_INDEX, SR.MS_REGISTER)); } if (var.equals(NS_GATE)) { showPartialResults=true; } //if (var.equals(NODE_CMDS)) { cmds.addElement(new DiscoCommand(AD_HOC_INDEX,strCmds)); } } } } /*if (data.getAttribute("from").equals(service)) */ { //FIXME!!! this.cmds=cmds; if (loadItems) requestQuery(NS_ITEMS, "disco2"); if (showPartialResults) showResults(new Vector()); } } else if (id.startsWith ("discoreg")) {
diff --git a/plugins/org.integratedmodelling.thinklab.core/src/org/integratedmodelling/thinklab/rest/RESTUserModel.java b/plugins/org.integratedmodelling.thinklab.core/src/org/integratedmodelling/thinklab/rest/RESTUserModel.java index 20201e48..0ed3e16c 100644 --- a/plugins/org.integratedmodelling.thinklab.core/src/org/integratedmodelling/thinklab/rest/RESTUserModel.java +++ b/plugins/org.integratedmodelling.thinklab.core/src/org/integratedmodelling/thinklab/rest/RESTUserModel.java @@ -1,70 +1,70 @@ package org.integratedmodelling.thinklab.rest; import java.io.InputStream; import java.io.PrintStream; import java.util.HashMap; import java.util.Properties; import org.integratedmodelling.thinklab.authentication.AuthenticationManager; import org.integratedmodelling.thinklab.exception.ThinklabException; import org.integratedmodelling.thinklab.interfaces.applications.ISession; import org.integratedmodelling.thinklab.interfaces.applications.IUserModel; import org.integratedmodelling.thinklab.interfaces.knowledge.IInstance; import org.integratedmodelling.thinklab.owlapi.Session; public class RESTUserModel implements IUserModel { Properties properties = null; ISession session = null; public RESTUserModel( HashMap<String, String> arguments, Properties p, Session session) { this.properties = p; this.session = session; } @Override public InputStream getInputStream() { // TODO Auto-generated method stub return null; } @Override public PrintStream getOutputStream() { // TODO Auto-generated method stub return null; } @Override public void initialize(ISession session) { this.session = session; } @Override public void setProperties(Properties uprop) { this.properties = uprop; } @Override public Properties getProperties() { return this.properties; } @Override public IInstance getUserInstance() throws ThinklabException { IInstance ret = session.retrieveObject("user"); - if (ret == null) { + if (ret == null && properties != null) { String user = properties.getProperty("authenticated-user"); if (user == null) return null; ret = AuthenticationManager.get().getUserInstance(user, session); } return ret; } }
true
true
public IInstance getUserInstance() throws ThinklabException { IInstance ret = session.retrieveObject("user"); if (ret == null) { String user = properties.getProperty("authenticated-user"); if (user == null) return null; ret = AuthenticationManager.get().getUserInstance(user, session); } return ret; }
public IInstance getUserInstance() throws ThinklabException { IInstance ret = session.retrieveObject("user"); if (ret == null && properties != null) { String user = properties.getProperty("authenticated-user"); if (user == null) return null; ret = AuthenticationManager.get().getUserInstance(user, session); } return ret; }
diff --git a/src/kundera-elastic-search/src/test/java/com/impetus/client/es/ESClientTest.java b/src/kundera-elastic-search/src/test/java/com/impetus/client/es/ESClientTest.java index ad1a2834b..0eb7a8139 100644 --- a/src/kundera-elastic-search/src/test/java/com/impetus/client/es/ESClientTest.java +++ b/src/kundera-elastic-search/src/test/java/com/impetus/client/es/ESClientTest.java @@ -1,179 +1,179 @@ /******************************************************************************* * * Copyright 2013 Impetus Infotech. * * * * 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.impetus.client.es; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import junit.framework.Assert; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.node.Node; import org.elasticsearch.node.NodeBuilder; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import com.impetus.client.es.PersonES.Day; import com.impetus.kundera.Constants; import com.impetus.kundera.PersistenceProperties; import com.impetus.kundera.configure.ClientFactoryConfiguraton; import com.impetus.kundera.metadata.KunderaMetadataManager; import com.impetus.kundera.metadata.MetadataBuilder; import com.impetus.kundera.metadata.model.ApplicationMetadata; import com.impetus.kundera.metadata.model.ClientMetadata; import com.impetus.kundera.metadata.model.EntityMetadata; import com.impetus.kundera.metadata.model.KunderaMetadata; import com.impetus.kundera.metadata.model.MetamodelImpl; import com.impetus.kundera.metadata.model.PersistenceUnitMetadata; import com.impetus.kundera.metadata.processor.IndexProcessor; import com.impetus.kundera.metadata.processor.TableProcessor; public class ESClientTest { private final static String persistenceUnit = "es-pu"; private static Node node = null; @BeforeClass public static void setUpBeforeClass() throws Exception { ImmutableSettings.Builder builder = ImmutableSettings.settingsBuilder(); builder.put("path.data", "target/data"); node = new NodeBuilder().settings(builder).node(); } @Before public void setup() { getEntityManagerFactory(); } @Test public void test() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { ESClientFactory esFactory = new ESClientFactory(); Map<String, Object> props = new HashMap<String, Object>(); props.put(PersistenceProperties.KUNDERA_NODES, "localhost"); props.put(PersistenceProperties.KUNDERA_PORT, "9300"); Field f = esFactory.getClass().getSuperclass().getDeclaredField("persistenceUnit"); if (!f.isAccessible()) { f.setAccessible(true); } f.set(esFactory, persistenceUnit); esFactory.load(persistenceUnit, props); ESClient client = (ESClient) esFactory.getClientInstance(); EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(PersonES.class); PersonES entity = new PersonES(); entity.setAge(21); entity.setDay(Day.FRIDAY); entity.setPersonId("1"); entity.setPersonName("vivek"); client.onPersist(metadata, entity, "1", null); PersonES result = (PersonES) client.find(PersonES.class, "1"); Assert.assertNotNull(result); PersonES invalidResult = (PersonES) client.find(PersonES.class, "2_p"); Assert.assertNull(invalidResult); client.delete(result, "1"); result = (PersonES) client.find(PersonES.class, "1"); Assert.assertNull(result); } private void getEntityManagerFactory() { ClientMetadata clientMetadata = new ClientMetadata(); Map<String, Object> props = new HashMap<String, Object>(); props.put(Constants.PERSISTENCE_UNIT_NAME, persistenceUnit); props.put(PersistenceProperties.KUNDERA_CLIENT_FACTORY, ESClientFactory.class.getName()); props.put(PersistenceProperties.KUNDERA_NODES, "localhost"); props.put(PersistenceProperties.KUNDERA_PORT, "9300"); - props.put(PersistenceProperties.KUNDERA_KEYSPACE, "KunderaMetaDataTest"); + props.put(PersistenceProperties.KUNDERA_KEYSPACE, "esSchema"); clientMetadata.setLuceneIndexDir(null); KunderaMetadata.INSTANCE.setApplicationMetadata(null); ApplicationMetadata appMetadata = KunderaMetadata.INSTANCE.getApplicationMetadata(); PersistenceUnitMetadata puMetadata = new PersistenceUnitMetadata(); puMetadata.setPersistenceUnitName(persistenceUnit); Properties p = new Properties(); p.putAll(props); puMetadata.setProperties(p); Map<String, PersistenceUnitMetadata> metadata = new HashMap<String, PersistenceUnitMetadata>(); metadata.put(persistenceUnit, puMetadata); appMetadata.addPersistenceUnitMetadata(metadata); Map<String, List<String>> clazzToPu = new HashMap<String, List<String>>(); List<String> pus = new ArrayList<String>(); pus.add(persistenceUnit); MetadataBuilder metadataBuilder = new MetadataBuilder(persistenceUnit, ESClient.class.getSimpleName(), null); EntityMetadata entityMetadata = new EntityMetadata(PersonES.class); // TableProcessor processor = new TableProcessor(null); processor.process(PersonES.class, entityMetadata); IndexProcessor indexProcessor = new IndexProcessor(); indexProcessor.process(PersonES.class, entityMetadata); // entityMetadata.setPersistenceUnit(persistenceUnit); // MetamodelImpl metaModel = new MetamodelImpl(); metaModel.addEntityMetadata(PersonES.class, metadataBuilder.buildEntityMetadata(PersonES.class)); appMetadata.getMetamodelMap().put(persistenceUnit, metaModel); // metaModel.assignManagedTypes(appMetadata.getMetaModelBuilder(persistenceUnit).getManagedTypes()); metaModel.assignEmbeddables(appMetadata.getMetaModelBuilder(persistenceUnit).getEmbeddables()); metaModel.assignMappedSuperClass(appMetadata.getMetaModelBuilder(persistenceUnit).getMappedSuperClassTypes()); // cla String[] persistenceUnits = new String[] { persistenceUnit }; clazzToPu.put(PersonES.class.getName(), Arrays.asList(persistenceUnits)); appMetadata.setClazzToPuMap(clazzToPu); new ClientFactoryConfiguraton(null, persistenceUnits).configure(); } @AfterClass public static void tearDownAfterClass() throws Exception { node.close(); KunderaMetadata.INSTANCE.setApplicationMetadata(null); } }
true
true
private void getEntityManagerFactory() { ClientMetadata clientMetadata = new ClientMetadata(); Map<String, Object> props = new HashMap<String, Object>(); props.put(Constants.PERSISTENCE_UNIT_NAME, persistenceUnit); props.put(PersistenceProperties.KUNDERA_CLIENT_FACTORY, ESClientFactory.class.getName()); props.put(PersistenceProperties.KUNDERA_NODES, "localhost"); props.put(PersistenceProperties.KUNDERA_PORT, "9300"); props.put(PersistenceProperties.KUNDERA_KEYSPACE, "KunderaMetaDataTest"); clientMetadata.setLuceneIndexDir(null); KunderaMetadata.INSTANCE.setApplicationMetadata(null); ApplicationMetadata appMetadata = KunderaMetadata.INSTANCE.getApplicationMetadata(); PersistenceUnitMetadata puMetadata = new PersistenceUnitMetadata(); puMetadata.setPersistenceUnitName(persistenceUnit); Properties p = new Properties(); p.putAll(props); puMetadata.setProperties(p); Map<String, PersistenceUnitMetadata> metadata = new HashMap<String, PersistenceUnitMetadata>(); metadata.put(persistenceUnit, puMetadata); appMetadata.addPersistenceUnitMetadata(metadata); Map<String, List<String>> clazzToPu = new HashMap<String, List<String>>(); List<String> pus = new ArrayList<String>(); pus.add(persistenceUnit); MetadataBuilder metadataBuilder = new MetadataBuilder(persistenceUnit, ESClient.class.getSimpleName(), null); EntityMetadata entityMetadata = new EntityMetadata(PersonES.class); // TableProcessor processor = new TableProcessor(null); processor.process(PersonES.class, entityMetadata); IndexProcessor indexProcessor = new IndexProcessor(); indexProcessor.process(PersonES.class, entityMetadata); // entityMetadata.setPersistenceUnit(persistenceUnit); // MetamodelImpl metaModel = new MetamodelImpl(); metaModel.addEntityMetadata(PersonES.class, metadataBuilder.buildEntityMetadata(PersonES.class)); appMetadata.getMetamodelMap().put(persistenceUnit, metaModel); // metaModel.assignManagedTypes(appMetadata.getMetaModelBuilder(persistenceUnit).getManagedTypes()); metaModel.assignEmbeddables(appMetadata.getMetaModelBuilder(persistenceUnit).getEmbeddables()); metaModel.assignMappedSuperClass(appMetadata.getMetaModelBuilder(persistenceUnit).getMappedSuperClassTypes()); // cla String[] persistenceUnits = new String[] { persistenceUnit }; clazzToPu.put(PersonES.class.getName(), Arrays.asList(persistenceUnits)); appMetadata.setClazzToPuMap(clazzToPu); new ClientFactoryConfiguraton(null, persistenceUnits).configure(); }
private void getEntityManagerFactory() { ClientMetadata clientMetadata = new ClientMetadata(); Map<String, Object> props = new HashMap<String, Object>(); props.put(Constants.PERSISTENCE_UNIT_NAME, persistenceUnit); props.put(PersistenceProperties.KUNDERA_CLIENT_FACTORY, ESClientFactory.class.getName()); props.put(PersistenceProperties.KUNDERA_NODES, "localhost"); props.put(PersistenceProperties.KUNDERA_PORT, "9300"); props.put(PersistenceProperties.KUNDERA_KEYSPACE, "esSchema"); clientMetadata.setLuceneIndexDir(null); KunderaMetadata.INSTANCE.setApplicationMetadata(null); ApplicationMetadata appMetadata = KunderaMetadata.INSTANCE.getApplicationMetadata(); PersistenceUnitMetadata puMetadata = new PersistenceUnitMetadata(); puMetadata.setPersistenceUnitName(persistenceUnit); Properties p = new Properties(); p.putAll(props); puMetadata.setProperties(p); Map<String, PersistenceUnitMetadata> metadata = new HashMap<String, PersistenceUnitMetadata>(); metadata.put(persistenceUnit, puMetadata); appMetadata.addPersistenceUnitMetadata(metadata); Map<String, List<String>> clazzToPu = new HashMap<String, List<String>>(); List<String> pus = new ArrayList<String>(); pus.add(persistenceUnit); MetadataBuilder metadataBuilder = new MetadataBuilder(persistenceUnit, ESClient.class.getSimpleName(), null); EntityMetadata entityMetadata = new EntityMetadata(PersonES.class); // TableProcessor processor = new TableProcessor(null); processor.process(PersonES.class, entityMetadata); IndexProcessor indexProcessor = new IndexProcessor(); indexProcessor.process(PersonES.class, entityMetadata); // entityMetadata.setPersistenceUnit(persistenceUnit); // MetamodelImpl metaModel = new MetamodelImpl(); metaModel.addEntityMetadata(PersonES.class, metadataBuilder.buildEntityMetadata(PersonES.class)); appMetadata.getMetamodelMap().put(persistenceUnit, metaModel); // metaModel.assignManagedTypes(appMetadata.getMetaModelBuilder(persistenceUnit).getManagedTypes()); metaModel.assignEmbeddables(appMetadata.getMetaModelBuilder(persistenceUnit).getEmbeddables()); metaModel.assignMappedSuperClass(appMetadata.getMetaModelBuilder(persistenceUnit).getMappedSuperClassTypes()); // cla String[] persistenceUnits = new String[] { persistenceUnit }; clazzToPu.put(PersonES.class.getName(), Arrays.asList(persistenceUnits)); appMetadata.setClazzToPuMap(clazzToPu); new ClientFactoryConfiguraton(null, persistenceUnits).configure(); }