input
stringlengths
20
285k
output
stringlengths
20
285k
private void calculateShortestPaths() { for (V j : this.vertices) { for (V i : this.vertices) { if (!i.equals(j)) { for (V k : this.vertices) { if (!k.equals(j)) { Double new_value = this.d.get(i).get(j) + this.d.get(j).get(k); if (new_value < this.d.get(i).get(k)) { this.d.get(i).put(k, new_value); this.t.get(i).put(k, j); } } } if (this.d.get(i).get(j) < 0) throw new NegativeCircleFoundException(); } } } }
private void calculateShortestPaths() { for (V j : this.vertices) { for (V i : this.vertices) { if (!i.equals(j)) { for (V k : this.vertices) { if (!k.equals(j)) { Double new_value = this.d.get(i).get(j) + this.d.get(j).get(k); if (new_value < this.d.get(i).get(k)) { this.d.get(i).put(k, new_value); this.t.get(i).put(k, j); } } } if (this.d.get(i).get(i) < 0) { throw new NegativeCircleFoundException(); } } } } }
public void onProjectileLaunch(ProjectileLaunchEvent event) { if(!ModDamage.isEnabled) return; Projectile projectile = (Projectile)event.getEntity(); LivingEntity shooter = projectile.getShooter(); EventData data = myInfo.makeData( shooter, projectile, projectile.getWorld()); runRoutines(data); event.setCancelled(data.get(Boolean.class, data.start + data.objects.length - 1)); }
public void onProjectileLaunch(ProjectileLaunchEvent event) { if(!ModDamage.isEnabled) return; Projectile projectile = (Projectile)event.getEntity(); LivingEntity shooter = projectile.getShooter(); EventData data = myInfo.makeData( shooter, projectile, projectile.getWorld(), event.isCancelled()); runRoutines(data); event.setCancelled(data.get(Boolean.class, data.start + data.objects.length - 1)); }
private InputStream handleHTTP(IHttpRequest http, String uri) throws IOException { InputStream in = null; String queryStr = getQuery(uri); String baseUri = removeQueryFromURI(uri); try { in = getStream(baseUri); } catch (IOException e) { http.reply(404, e.getMessage()); return null; } long offset = 0; String range = http.get("Range"); if ((range != null) && range.startsWith("bytes=") && range.endsWith("-")) { try { offset = Long.parseLong(range.substring(6, range.length() - 1)); } catch (NumberFormatException e) { } } if (!http.getReplied()) { if (offset == 0) { http.reply(200, "Media follows"); } else { http.reply(206, "Partial Media follows"); } } String ct = null; if (baseUri.endsWith(".mpeg") || baseUri.endsWith(".mpg")) { ct = "video/mpeg"; } else if (baseUri.endsWith(".mp3")) { ct = "audio/mpeg"; long mp3duration = getMP3Duration(uri); System.out.println("MP3 stream duration: " + mp3duration); if (mp3duration > 0) http.addHeader(IHmeConstants.TIVO_DURATION, "" + mp3duration); if (in != null && queryStr != null) { int seekTime = getSeekTime(queryStr); Mp3Helper mp3Helper = new Mp3Helper(in, in.available()); in = mp3Helper.seek(seekTime); } } if (ct != null) { http.addHeader("Content-Type", ct); } if (offset > 0) { long total = in.available(); http.addHeader("Content-Range", "bytes " + offset + "-" + (total-1) + "/" + total); in.skip(offset); } addHeaders(http, baseUri); if (http.get("http-method").equalsIgnoreCase("HEAD")) { return null; } return in; }
private InputStream handleHTTP(IHttpRequest http, String uri) throws IOException { InputStream in = null; String queryStr = getQuery(uri); String baseUri = removeQueryFromURI(uri); try { in = getStream(baseUri); } catch (IOException e) { http.reply(404, e.getMessage()); return null; } long offset = 0; String range = http.get("Range"); if ((range != null) && range.startsWith("bytes=") && range.endsWith("-")) { try { offset = Long.parseLong(range.substring(6, range.length() - 1)); } catch (NumberFormatException e) { } } if (!http.getReplied()) { if (offset == 0) { http.reply(200, "Media follows"); } else { http.reply(206, "Partial Media follows"); } } String ct = null; if (baseUri.endsWith(".mpeg") || baseUri.endsWith(".mpg")) { ct = "video/mpeg"; } else if (baseUri.endsWith(".mp3")) { ct = "audio/mpeg"; long mp3duration = getMP3Duration(baseUri); System.out.println("MP3 stream duration: " + mp3duration); if (mp3duration > 0) http.addHeader(IHmeConstants.TIVO_DURATION, "" + mp3duration); if (in != null && queryStr != null) { int seekTime = getSeekTime(queryStr); Mp3Helper mp3Helper = new Mp3Helper(in, in.available()); in = mp3Helper.seek(seekTime); } } if (ct != null) { http.addHeader("Content-Type", ct); } if (offset > 0) { long total = in.available(); http.addHeader("Content-Range", "bytes " + offset + "-" + (total-1) + "/" + total); in.skip(offset); } addHeaders(http, baseUri); if (http.get("http-method").equalsIgnoreCase("HEAD")) { return null; } return in; }
public String partitionDAX( PegasusProperties properties , String daxFile, String directory, String type ){ int status = 0; if ( daxFile == null || daxFile.length() == 0 ) { mLogger.log( "The dax file that is to be partitioned not " + "specified", LogManager.FATAL_MESSAGE_LEVEL ); printShortVersion(); status = 1; throw new RuntimeException( "Unable to partition" ); } File dir = new File( directory ); dir.mkdirs(); String callbackClass = ( type.equalsIgnoreCase("label") ) ? "DAX2LabelGraph": "DAX2Graph"; Callback callback = null; Partitioner partitioner = null; String daxName = null; int state = 0; try{ callback = DAXCallbackFactory.loadInstance( properties, daxFile, callbackClass ); if( callback instanceof DAX2LabelGraph ){ ((DAX2LabelGraph)callback).setLabelKey( properties.getPartitionerLabelKey() ); } state = 1; PegasusBag bag = new PegasusBag(); bag.add( PegasusBag.PEGASUS_PROPERTIES, properties ); DaxParser d = new DaxParser( daxFile, bag, callback ); state = 2; Map graphMap = (Map) callback.getConstructedObject(); GraphNode root = (GraphNode) graphMap.get( DAX2Graph.DUMMY_NODE_ID ); daxName = ( (DAX2Graph) callback).getNameOfDAX(); state = 3; partitioner = PartitionerFactory.loadInstance( properties, root, graphMap, type ); } catch ( FactoryException fe){ mLogger.log( fe.convertException() , LogManager.FATAL_MESSAGE_LEVEL); System.exit( 2 ); } catch( Exception e ){ int errorStatus = 1; switch(state){ case 0: mLogger.log( "Unable to load the DAXCallback", e, LogManager.FATAL_MESSAGE_LEVEL ); errorStatus = 2; break; case 1: mLogger.log( "Error while parsing the DAX file", e , LogManager.FATAL_MESSAGE_LEVEL ); errorStatus = 1; break; case 2: mLogger.log( "Error while determining the root of the parsed DAX", e, LogManager.FATAL_MESSAGE_LEVEL ); errorStatus = 1; break; case 3: mLogger.log( "Unable to load the partitioner", e, LogManager.FATAL_MESSAGE_LEVEL ); errorStatus = 2; break; default: mLogger.log( "Unknown Error", e, LogManager.FATAL_MESSAGE_LEVEL ); errorStatus = 1; break; } status = errorStatus; } if( status > 0 ){ throw new RuntimeException( "Unable to partition" ); } WriterCallback cb = new WriterCallback(); cb.initialize( properties, daxFile, daxName, directory ); partitioner.determinePartitions( cb ); return cb.getPDAX(); }
public String partitionDAX( PegasusProperties properties , String daxFile, String directory, String type ){ int status = 0; if ( daxFile == null || daxFile.length() == 0 ) { mLogger.log( "The dax file that is to be partitioned not " + "specified", LogManager.FATAL_MESSAGE_LEVEL ); printShortVersion(); status = 1; throw new RuntimeException( "Unable to partition" ); } File dir = new File( directory ); dir.mkdirs(); String callbackClass = ( type.equalsIgnoreCase("label") ) ? "DAX2LabelGraph": "DAX2Graph"; Callback callback = null; Partitioner partitioner = null; String daxName = null; int state = 0; try{ callback = DAXCallbackFactory.loadInstance( properties, daxFile, callbackClass ); if( callback instanceof DAX2LabelGraph ){ ((DAX2LabelGraph)callback).setLabelKey( properties.getPartitionerLabelKey() ); } state = 1; PegasusBag bag = new PegasusBag(); bag.add( PegasusBag.PEGASUS_PROPERTIES, properties ); bag.add( PegasusBag.PEGASUS_LOGMANAGER, mLogger ); DaxParser d = new DaxParser( daxFile, bag, callback ); state = 2; Map graphMap = (Map) callback.getConstructedObject(); GraphNode root = (GraphNode) graphMap.get( DAX2Graph.DUMMY_NODE_ID ); daxName = ( (DAX2Graph) callback).getNameOfDAX(); state = 3; partitioner = PartitionerFactory.loadInstance( properties, root, graphMap, type ); } catch ( FactoryException fe){ mLogger.log( fe.convertException() , LogManager.FATAL_MESSAGE_LEVEL); System.exit( 2 ); } catch( Exception e ){ int errorStatus = 1; switch(state){ case 0: mLogger.log( "Unable to load the DAXCallback", e, LogManager.FATAL_MESSAGE_LEVEL ); errorStatus = 2; break; case 1: mLogger.log( "Error while parsing the DAX file", e , LogManager.FATAL_MESSAGE_LEVEL ); errorStatus = 1; break; case 2: mLogger.log( "Error while determining the root of the parsed DAX", e, LogManager.FATAL_MESSAGE_LEVEL ); errorStatus = 1; break; case 3: mLogger.log( "Unable to load the partitioner", e, LogManager.FATAL_MESSAGE_LEVEL ); errorStatus = 2; break; default: mLogger.log( "Unknown Error", e, LogManager.FATAL_MESSAGE_LEVEL ); errorStatus = 1; break; } status = errorStatus; } if( status > 0 ){ throw new RuntimeException( "Unable to partition" ); } WriterCallback cb = new WriterCallback(); cb.initialize( properties, daxFile, daxName, directory ); partitioner.determinePartitions( cb ); return cb.getPDAX(); }
public void update(float deltaTime) { super.update(deltaTime); float elapsedSeconds = (float)deltaTime; float scaleChange = scaleVelocity * elapsedSeconds; scale += scaleChange; remainingScaleAmount -= Math.abs(scaleChange); if (remainingScaleAmount <= 0) { scale += remainingScaleAmount * -(scaleChange< 0 ? -1 : (scaleChange > 0 ? 1 : 0)); scaleVelocity = 0; } }
public void update(float deltaTime) { super.update(deltaTime); float elapsedSeconds = (float)deltaTime; float scaleChange = scaleVelocity * elapsedSeconds; scale += scaleChange; remainingScaleAmount -= Math.abs(scaleChange); if (remainingScaleAmount <= 0) { scale += remainingScaleAmount * (scaleChange< 0 ? -1 : (scaleChange > 0 ? 1 : 0)); scaleVelocity = 0; } }
protected OpenJPAEntityManagerFactorySPI createNamedEMF(String pu, Object... props) { Map map = new HashMap(System.getProperties()); List<Class> types = new ArrayList<Class>(); boolean prop = false; for (int i = 0; i < props.length; i++) { if (prop) { map.put(props[i - 1], props[i]); prop = false; } else if (props[i] == CLEAR_TABLES) { map.put("openjpa.jdbc.SynchronizeMappings", "buildSchema(ForeignKeys=true," + "SchemaAction='add,deleteTableContents')"); } else if (props[i] == DROP_TABLES) { map.put("openjpa.jdbc.SynchronizeMappings", "buildSchema(ForeignKeys=true," + "SchemaAction='drop,add')"); } else if (props[i] instanceof Class) types.add((Class) props[i]); else if (props[i] != null) prop = true; } if (!types.isEmpty()) { StringBuffer buf = new StringBuffer(); for (Class c : types) { if (buf.length() > 0) buf.append(";"); buf.append(c.getName()); } map.put("openjpa.MetaDataFactory", "jpa(Types=" + buf.toString() + ")"); } return (OpenJPAEntityManagerFactorySPI) Persistence. createEntityManagerFactory(pu, map); }
protected OpenJPAEntityManagerFactorySPI createNamedEMF(String pu, Object... props) { Map map = new HashMap(System.getProperties()); List<Class> types = new ArrayList<Class>(); boolean prop = false; for (int i = 0; i < props.length; i++) { if (prop) { map.put(props[i - 1], props[i]); prop = false; } else if (props[i] == CLEAR_TABLES) { map.put("openjpa.jdbc.SynchronizeMappings", "buildSchema(ForeignKeys=true," + "SchemaAction='add,deleteTableContents')"); } else if (props[i] == DROP_TABLES) { map.put("openjpa.jdbc.SynchronizeMappings", "buildSchema(ForeignKeys=true," + "SchemaAction='drop,add')"); } else if (props[i] instanceof Class) types.add((Class) props[i]); else if (props[i] != null) prop = true; } if (!types.isEmpty()) { StringBuffer buf = new StringBuffer(); for (Class c : types) { if (buf.length() > 0) buf.append(";"); buf.append(c.getName()); } map.put("openjpa.MetaDataFactory", "jpa(Types=" + buf.toString() + ")"); } OpenJPAEntityManagerFactorySPI oemf = (OpenJPAEntityManagerFactorySPI) Persistence.createEntityManagerFactory(pu, map); if (oemf == null) throw new NullPointerException( "Expected an entity manager factory " + "for the persistence unit named: \"" + pu + "\""); return oemf; }
public void testSignificantWhiteSpace() throws Exception { String text = "<p><b>word</b> <i>word</i></p>"; parser.parse( text, sink ); Iterator it = sink.getEventList().iterator(); assertEquals( "paragraph", ( (SinkEventElement) it.next() ).getName() ); assertEquals( "bold", ( (SinkEventElement) it.next() ).getName() ); assertEquals( "text", ( (SinkEventElement) it.next() ).getName() ); assertEquals( "bold_", ( (SinkEventElement) it.next() ).getName() ); SinkEventElement el = (SinkEventElement) it.next(); assertEquals( "text", el.getName() ); assertEquals( " ", (String) el.getArgs()[0] ); assertEquals( "italic", ( (SinkEventElement) it.next() ).getName() ); assertEquals( "text", ( (SinkEventElement) it.next() ).getName() ); assertEquals( "italic_", ( (SinkEventElement) it.next() ).getName() ); assertEquals( "paragraph_", ( (SinkEventElement) it.next() ).getName() ); assertFalse( it.hasNext() ); String EOL = System.getProperty( "line.separator" ); text = "<p><b>word</b>" + EOL + "<i>word</i></p>"; sink.reset(); parser.parse( text, sink ); it = sink.getEventList().iterator(); assertEquals( "paragraph", ( (SinkEventElement) it.next() ).getName() ); assertEquals( "bold", ( (SinkEventElement) it.next() ).getName() ); assertEquals( "text", ( (SinkEventElement) it.next() ).getName() ); assertEquals( "bold_", ( (SinkEventElement) it.next() ).getName() ); el = (SinkEventElement) it.next(); assertEquals( "text", el.getName() ); assertEquals( EOL, (String) el.getArgs()[0] ); assertEquals( "italic", ( (SinkEventElement) it.next() ).getName() ); assertEquals( "text", ( (SinkEventElement) it.next() ).getName() ); assertEquals( "italic_", ( (SinkEventElement) it.next() ).getName() ); assertEquals( "paragraph_", ( (SinkEventElement) it.next() ).getName() ); assertFalse( it.hasNext() ); text = "<p>There should be no space after the last <i>word</i>.</p>"; sink.reset(); parser.parse( text, sink ); it = sink.getEventList().iterator(); assertEquals( "paragraph", ( (SinkEventElement) it.next() ).getName() ); assertEquals( "text", ( (SinkEventElement) it.next() ).getName() ); assertEquals( "italic", ( (SinkEventElement) it.next() ).getName() ); assertEquals( "text", ( (SinkEventElement) it.next() ).getName() ); assertEquals( "italic_", ( (SinkEventElement) it.next() ).getName() ); el = (SinkEventElement) it.next(); assertEquals( "text", el.getName() ); assertEquals( ".", (String) el.getArgs()[0] ); assertEquals( "paragraph_", ( (SinkEventElement) it.next() ).getName() ); assertFalse( it.hasNext() ); }
public void testSignificantWhiteSpace() throws Exception { String text = "<p><b>word</b> <i>word</i></p>"; parser.parse( text, sink ); Iterator it = sink.getEventList().iterator(); assertEquals( "paragraph", ( (SinkEventElement) it.next() ).getName() ); assertEquals( "bold", ( (SinkEventElement) it.next() ).getName() ); assertEquals( "text", ( (SinkEventElement) it.next() ).getName() ); assertEquals( "bold_", ( (SinkEventElement) it.next() ).getName() ); SinkEventElement el = (SinkEventElement) it.next(); assertEquals( "text", el.getName() ); assertEquals( " ", (String) el.getArgs()[0] ); assertEquals( "italic", ( (SinkEventElement) it.next() ).getName() ); assertEquals( "text", ( (SinkEventElement) it.next() ).getName() ); assertEquals( "italic_", ( (SinkEventElement) it.next() ).getName() ); assertEquals( "paragraph_", ( (SinkEventElement) it.next() ).getName() ); assertFalse( it.hasNext() ); String EOL = System.getProperty( "line.separator" ); text = "<p><b>word</b>" + EOL + "<i>word</i></p>"; sink.reset(); parser.parse( text, sink ); it = sink.getEventList().iterator(); assertEquals( "paragraph", ( (SinkEventElement) it.next() ).getName() ); assertEquals( "bold", ( (SinkEventElement) it.next() ).getName() ); assertEquals( "text", ( (SinkEventElement) it.next() ).getName() ); assertEquals( "bold_", ( (SinkEventElement) it.next() ).getName() ); el = (SinkEventElement) it.next(); assertEquals( "text", el.getName() ); assertEquals( "\n", (String) el.getArgs()[0] ); assertEquals( "italic", ( (SinkEventElement) it.next() ).getName() ); assertEquals( "text", ( (SinkEventElement) it.next() ).getName() ); assertEquals( "italic_", ( (SinkEventElement) it.next() ).getName() ); assertEquals( "paragraph_", ( (SinkEventElement) it.next() ).getName() ); assertFalse( it.hasNext() ); text = "<p>There should be no space after the last <i>word</i>.</p>"; sink.reset(); parser.parse( text, sink ); it = sink.getEventList().iterator(); assertEquals( "paragraph", ( (SinkEventElement) it.next() ).getName() ); assertEquals( "text", ( (SinkEventElement) it.next() ).getName() ); assertEquals( "italic", ( (SinkEventElement) it.next() ).getName() ); assertEquals( "text", ( (SinkEventElement) it.next() ).getName() ); assertEquals( "italic_", ( (SinkEventElement) it.next() ).getName() ); el = (SinkEventElement) it.next(); assertEquals( "text", el.getName() ); assertEquals( ".", (String) el.getArgs()[0] ); assertEquals( "paragraph_", ( (SinkEventElement) it.next() ).getName() ); assertFalse( it.hasNext() ); }
public static List<String> getTokens(String path) { if (path == null) throw new IllegalArgumentException("Null path"); int start = -1, length = path.length(), state = STATE_INITIAL; char ch; List<String> list = new ArrayList<String>(); for (int index = 0; index < length; index ++) { ch = path.charAt(index); switch (ch) { case '/': { switch (state) { case STATE_INITIAL: { continue; } case STATE_MAYBE_CURRENT_PATH: { list.add(CURRENT_PATH); state = STATE_INITIAL; continue; } case STATE_MAYBE_REVERSE_PATH: { list.add(REVERSE_PATH); state = STATE_INITIAL; continue; } case STATE_NORMAL: { list.add(path.substring(start, index)); state = STATE_INITIAL; continue; } } continue; } case '.': { switch (state) { case STATE_INITIAL: { state = STATE_MAYBE_CURRENT_PATH; start = index; continue; } case STATE_MAYBE_CURRENT_PATH: { state = STATE_MAYBE_REVERSE_PATH; continue; } case STATE_MAYBE_REVERSE_PATH: { state = STATE_NORMAL; continue; } } continue; } default: { switch (state) { case STATE_INITIAL: { state = STATE_NORMAL; start = index; continue; } } } } } switch (state) { case STATE_INITIAL: { break; } case STATE_MAYBE_CURRENT_PATH: { list.add(CURRENT_PATH); break; } case STATE_MAYBE_REVERSE_PATH: { list.add(REVERSE_PATH); break; } case STATE_NORMAL: { list.add(path.substring(start)); break; } } return list; }
public static List<String> getTokens(String path) { if (path == null) throw new IllegalArgumentException("Null path"); int start = -1, length = path.length(), state = STATE_INITIAL; char ch; List<String> list = new ArrayList<String>(); for (int index = 0; index < length; index ++) { ch = path.charAt(index); switch (ch) { case '/': { switch (state) { case STATE_INITIAL: { continue; } case STATE_MAYBE_CURRENT_PATH: { list.add(CURRENT_PATH); state = STATE_INITIAL; continue; } case STATE_MAYBE_REVERSE_PATH: { list.add(REVERSE_PATH); state = STATE_INITIAL; continue; } case STATE_NORMAL: { list.add(path.substring(start, index)); state = STATE_INITIAL; continue; } } continue; } case '.': { switch (state) { case STATE_INITIAL: { state = STATE_MAYBE_CURRENT_PATH; start = index; continue; } case STATE_MAYBE_CURRENT_PATH: { state = STATE_MAYBE_REVERSE_PATH; continue; } case STATE_MAYBE_REVERSE_PATH: { if (errorOnSuspiciousTokens) { throw new IllegalArgumentException("Illegal suspicious token in path: " + path); } state = STATE_NORMAL; continue; } } continue; } default: { switch (state) { case STATE_INITIAL: { state = STATE_NORMAL; start = index; continue; } case STATE_MAYBE_CURRENT_PATH: case STATE_MAYBE_REVERSE_PATH: { if (errorOnSuspiciousTokens) { throw new IllegalArgumentException("Illegal suspicious token in path: " + path); } state = STATE_NORMAL; continue; } } } } } switch (state) { case STATE_INITIAL: { break; } case STATE_MAYBE_CURRENT_PATH: { list.add(CURRENT_PATH); break; } case STATE_MAYBE_REVERSE_PATH: { list.add(REVERSE_PATH); break; } case STATE_NORMAL: { list.add(path.substring(start)); break; } } return list; }
public synchronized void reloginFromKeytab() throws IOException { if (!isSecurityEnabled()) return; LoginContext login = getLogin(); if (login == null || keytabFile == null) { throw new IOException("loginUserFromKeyTab must be done first"); } long now = System.currentTimeMillis(); if (now - lastReloginTime < MIN_TIME_BEFORE_RELOGIN ) { LOG.warn("Not attempting to re-login since the last re-login was " + "attempted less than " + (MIN_TIME_BEFORE_RELOGIN/1000) + " seconds"+ " before."); return; } lastReloginTime = System.currentTimeMillis(); try { LOG.info("Initiating logout for " + getUserName()); login.logout(); login = new LoginContext(HadoopConfiguration.KEYTAB_KERBEROS_CONFIG_NAME, getSubject()); LOG.info("Initiating re-login for " + keytabPrincipal); login.login(); } catch (LoginException le) { throw new IOException("Login failure for " + keytabPrincipal + " from keytab " + keytabFile, le); } }
public synchronized void reloginFromKeytab() throws IOException { if (!isSecurityEnabled()) return; LoginContext login = getLogin(); if (login == null || keytabFile == null) { throw new IOException("loginUserFromKeyTab must be done first"); } long now = System.currentTimeMillis(); if (now - lastReloginTime < MIN_TIME_BEFORE_RELOGIN ) { LOG.warn("Not attempting to re-login since the last re-login was " + "attempted less than " + (MIN_TIME_BEFORE_RELOGIN/1000) + " seconds"+ " before."); return; } lastReloginTime = System.currentTimeMillis(); try { LOG.info("Initiating logout for " + getUserName()); login.logout(); login = new LoginContext(HadoopConfiguration.KEYTAB_KERBEROS_CONFIG_NAME, getSubject()); LOG.info("Initiating re-login for " + keytabPrincipal); login.login(); setLogin(login); } catch (LoginException le) { throw new IOException("Login failure for " + keytabPrincipal + " from keytab " + keytabFile, le); } }
public void process(CrawlURI curi, ChainStatusReceiver thread) throws InterruptedException { assert KeyedProperties.overridesActiveFrom(curi); String skipToProc = null; ploop: for(Processor curProc : this ) { if(skipToProc!=null && curProc.getBeanName() != skipToProc) { continue; } else { skipToProc = null; } if(thread!=null) { thread.atProcessor(curProc); } ArchiveUtils.continueCheck(); ProcessResult pr = curProc.process(curi); switch (pr.getProcessStatus()) { case PROCEED: continue; case FINISH: break ploop; case JUMP: skipToProc = pr.getJumpTarget(); continue; } } }
public void process(CrawlURI curi, ChainStatusReceiver thread) throws InterruptedException { assert KeyedProperties.overridesActiveFrom(curi); String skipToProc = null; ploop: for(Processor curProc : this ) { if(skipToProc!=null && !curProc.getBeanName().equals(skipToProc)) { continue; } else { skipToProc = null; } if(thread!=null) { thread.atProcessor(curProc); } ArchiveUtils.continueCheck(); ProcessResult pr = curProc.process(curi); switch (pr.getProcessStatus()) { case PROCEED: continue; case FINISH: break ploop; case JUMP: skipToProc = pr.getJumpTarget(); continue; } } }
private void loadMap(BaseRepository<GameMap> repo, File file) throws Exception { Document doc = builder.build(file); Element root = doc.getDescendants(new ElementFilter("maps")).next(); for (Element element : root.getChildren("map")) { GameMap map = factory.newGameMap(); map.setId(element.getAttribute("id").getIntValue()); map.setPosition(new Point( element.getAttribute("abscissa").getIntValue(), element.getAttribute("ordinate").getIntValue() )); map.setWidth(element.getAttribute("width").getIntValue()); map.setHeight(element.getAttribute("height").getIntValue()); map.setCells(CellLoader.parse(element.getChild("data").getAttributeValue("value"), factory)); map.setDate(element.getAttribute("date").getValue()); map.setKey(element.getChild("key").getAttributeValue("value")); map.setSubscriber(element.getAttributeValue("subscriber") == "1"); repo.put(map.getId(), map); } for (Element element : root.getChildren("map")) { GameMap map = repo.byId(element.getAttribute("id").getIntValue()); Map<Short, MapTrigger> triggers = Maps.newHashMap(); for (Element trigger_elem : element.getChildren("trigger")) { MapTrigger trigger = factory.newMapTrigger(); trigger.setMap(map); trigger.setCell((short) trigger_elem.getAttribute("cell").getIntValue()); trigger.setNextMap(repo.byId(trigger_elem.getAttribute("next_map").getIntValue())); trigger.setNextCell((short) trigger_elem.getAttribute("next_cell").getIntValue()); triggers.put(trigger.getCell(), trigger); } map.setTrigger(triggers); } }
private void loadMap(BaseRepository<GameMap> repo, File file) throws Exception { Document doc = builder.build(file); Element root = doc.getDescendants(new ElementFilter("maps")).next(); for (Element element : root.getChildren("map")) { GameMap map = factory.newGameMap(); map.setId(element.getAttribute("id").getIntValue()); map.setPosition(new Point( element.getAttribute("abscissa").getIntValue(), element.getAttribute("ordinate").getIntValue() )); map.setWidth(element.getAttribute("width").getIntValue()); map.setHeight(element.getAttribute("height").getIntValue()); map.setCells(CellLoader.parse(element.getChild("data").getAttributeValue("value"), factory)); map.setDate(element.getAttribute("date").getValue()); map.setKey(element.getChild("key").getAttributeValue("value")); map.setSubscriber(element.getAttributeValue("subscriber") == "1"); repo.put(map.getId(), map); } for (Element element : root.getChildren("map")) { GameMap map = repo.byId(element.getAttribute("id").getIntValue()); Map<Short, MapTrigger> triggers = Maps.newHashMap(); for (Element trigger_elem : element.getChildren("trigger")) { MapTrigger trigger = factory.newMapTrigger(); trigger.setMap(map); trigger.setCell((short) trigger_elem.getAttribute("cell").getIntValue()); if (!trigger_elem.getAttribute("next_map").getValue().isEmpty()) { trigger.setNextMap(repo.byId(trigger_elem.getAttribute("next_map").getIntValue())); } trigger.setNextCell((short) trigger_elem.getAttribute("next_cell").getIntValue()); triggers.put(trigger.getCell(), trigger); } map.setTrigger(triggers); } }
public static ErrorExemptions getVistAFOIAInstance() { ErrorExemptions r = new ErrorExemptions(); r.addLine("ANRVRRL", "BEGIN", 3); r.addLine("ANRVRRL", "A1R", 2); r.addLine("DINVMSM", "T0", 2); r.addLine("DINVMSM", "T1", 2); r.addLine("ZOSVMSM", "T0", 2); r.addLine("ZOSVMSM", "T1", 2); r.addLine("MUSMCR3", "BEG", 2); r.addLine("MUSMCR3", "BEG", 6); r.addLine("MUSMCR1", "EN11", 3); r.addLine("DENTA14", "P1", 0); r.addLine("HLOTCP", "RETRY", 8); r.addLine("HLOTCP", "RETRY", 9); r.addLine("HLOTCP", "RETRY", 14); r.addLine("RGUTRRC", "JOBIT", 2); r.addLine("ZISHMSU", "OPEN", 9); r.addLine("ZISG3", "SUBITEM", 4); r.addLine("PRCBR1", "LOCK", 1); r.addLine("ZISTCP", "CVXD", 2); r.addLine("ZOSVKRV", "JT", 11); r.addLine("ZTMB", "RESTART", 21); r.addLine("LEXAR7", "MAILQ", 1); r.addLine("XMRTCP", "SOC25", 3); r.addLine("ORRDI2", "TCOLD", 6); r.addLine("PSSFDBRT", "POST", 21); r.addLine("PSSHTTP", "PEPSPOST", 26); r.addLine("PSSHTTP", "PEPSPOST", 34); r.addRoutine("PSORELD1"); r.addRoutine("HLUCM001"); r.addRoutine("ZISG3"); r.addRoutine("ZOSVKSOE"); r.addRoutine("DGRUGMFU"); r.addRoutine("SPNRPC4"); r.addRoutine("MUSMCR1"); r.addRoutine("SDCNP"); return r; }
public static ErrorExemptions getVistAFOIAInstance() { ErrorExemptions r = new ErrorExemptions(); r.addLine("ANRVRRL", "BEGIN", 3); r.addLine("ANRVRRL", "A1R", 2); r.addLine("DINVMSM", "T0", 2); r.addLine("DINVMSM", "T1", 2); r.addLine("ZOSVMSM", "T0", 2); r.addLine("ZOSVMSM", "T1", 2); r.addLine("MUSMCR3", "BEG", 2); r.addLine("MUSMCR3", "BEG", 6); r.addLine("MUSMCR1", "EN11", 3); r.addLine("DENTA14", "P1", 0); r.addLine("HLOTCP", "RETRY", 8); r.addLine("HLOTCP", "RETRY", 9); r.addLine("HLOTCP", "RETRY", 14); r.addLine("RGUTRRC", "JOBIT", 2); r.addLine("ZISHMSU", "OPEN", 9); r.addLine("ZISG3", "SUBITEM", 4); r.addLine("PRCBR1", "LOCK", 1); r.addLine("ZISTCP", "CVXD", 2); r.addLine("ZOSVKRV", "JT", 11); r.addLine("ZTMB", "RESTART", 21); r.addLine("LEXAR7", "MAILQ", 1); r.addLine("XMRTCP", "SOC25", 3); r.addLine("ORRDI2", "TCOLD", 6); r.addLine("PSSFDBRT", "POST", 21); r.addLine("PSSHTTP", "PEPSPOST", 26); r.addLine("PSSHTTP", "PEPSPOST", 34); r.addLine("GMTSDGCH", "MAIN", 6); r.addLine("GMTSDGCH", "MAIN", 7); r.addRoutine("PSORELD1"); r.addRoutine("HLUCM001"); r.addRoutine("ZISG3"); r.addRoutine("ZOSVKSOE"); r.addRoutine("DGRUGMFU"); r.addRoutine("SPNRPC4"); r.addRoutine("MUSMCR1"); r.addRoutine("SDCNP"); return r; }
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException{ playButtonState = 0; play = new Button(new Image("graphics/buttons/playbutton.png"), new Image("graphics/buttons/playbuttonhover.png"), Button.LEFTBOT(), Button.LEFTBOT(), gc); }
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException{ playButtonState = 0; play = new Button(new Image("graphics/buttons/textplaybutton.png"), new Image("graphics/buttons/textplaybuttonhover.png"), Button.MID(), Button.MID(), gc); }
public static void main(String[] args) { OptionParser parser = new OptionParser(); parser.accepts(OPTION_SCENARIO, "Scenario XML file.") .withRequiredArg() .ofType(File.class); parser.accepts(OPTION_WORLD, "World XML file.") .withRequiredArg() .ofType(File.class); parser.accepts(OPTION_SCALE, "Constrained real time scaling factor.") .withRequiredArg() .ofType(Double.class); parser.accepts(OPTION_PAUSED, "Start in a paused state."); parser.accepts(OPTION_LOG, "Log4j properties file (optional).") .withRequiredArg() .ofType(File.class); parser.accepts(OPTION_HELP, "Show help"); OptionSet opts = parser.parse(args); if (opts.has(OPTION_HELP)) { try { parser.printHelpOn(System.out); return; } catch(IOException ioe) { logger.fatal("Could not print help to stdout.", ioe); return; } } if (opts.has(OPTION_LOG)) { Properties logProps = new Properties(); try { logProps.load(new FileInputStream((File)opts.valueOf(OPTION_LOG))); } catch(FileNotFoundException fnf) { logger.fatal("Could not open the scenario XML file.", fnf); return; } catch(IOException ioe) { logger.fatal("Could not load the properties file.", ioe); return; } Logger.getRootLogger().removeAllAppenders(); PropertyConfigurator.configure(logProps); } Document scenarioDoc = null; if (opts.has(OPTION_SCENARIO)) { try { InputStream stream = new FileInputStream((File)opts.valueOf(OPTION_SCENARIO)); scenarioDoc = DocUtil.getDocumentFromXml(stream); } catch(FileNotFoundException fnf) { logger.fatal("Could not open the scenario XML file.", fnf); return; } } if (scenarioDoc == null) { logger.fatal("Must supply a scenario XML file."); return; } Document worldDoc = null; if (opts.has(OPTION_WORLD)) { try { InputStream stream = new FileInputStream((File)opts.valueOf(OPTION_WORLD)); worldDoc = DocUtil.getDocumentFromXml(stream); } catch(FileNotFoundException fnf) { logger.fatal("Could not open the scenario XML file.", fnf); return; } } if (worldDoc == null) { logger.fatal("Must supply a world XML file."); return; } Scenario scenario; World world; try { scenario = JaxbHelper.objectFromNode(scenarioDoc, Scenario.class); world = JaxbHelper.objectFromNode(worldDoc, World.class); } catch(JAXBException je) { throw new RuntimeException("Could not parse the given scenario or world file.", je); } double scale = 0; if (opts.has(OPTION_SCALE)) { scale = (Double)opts.valueOf(OPTION_SCALE); } SimController sim = new SimController(); sim.runSim(scenario, world, scale, opts.has(OPTION_PAUSED)); }
public static void main(String[] args) { OptionParser parser = new OptionParser(); parser.accepts(OPTION_SCENARIO, "Scenario XML file.") .withRequiredArg() .ofType(File.class); parser.accepts(OPTION_WORLD, "World XML file.") .withRequiredArg() .ofType(File.class); parser.accepts(OPTION_SCALE, "Constrained real time scaling factor.") .withRequiredArg() .ofType(Double.class); parser.accepts(OPTION_PAUSED, "Start in a paused state."); parser.accepts(OPTION_LOG, "Log4j properties file (optional).") .withRequiredArg() .ofType(File.class); parser.accepts(OPTION_HELP, "Show help"); OptionSet opts = parser.parse(args); if (opts.has(OPTION_HELP)) { try { parser.printHelpOn(System.out); return; } catch(IOException ioe) { logger.fatal("Could not print help to stdout.", ioe); return; } } if (opts.has(OPTION_LOG)) { Properties logProps = new Properties(); try { logProps.load(new FileInputStream((File)opts.valueOf(OPTION_LOG))); } catch(FileNotFoundException fnf) { logger.fatal("Could not open the log4j properties file.", fnf); return; } catch(IOException ioe) { logger.fatal("Could not load the log4j properties file.", ioe); return; } Logger.getRootLogger().removeAllAppenders(); PropertyConfigurator.configure(logProps); } Document scenarioDoc = null; if (opts.has(OPTION_SCENARIO)) { try { InputStream stream = new FileInputStream((File)opts.valueOf(OPTION_SCENARIO)); scenarioDoc = DocUtil.getDocumentFromXml(stream); } catch(FileNotFoundException fnf) { logger.fatal("Could not open the scenario XML file.", fnf); return; } } if (scenarioDoc == null) { logger.fatal("Must supply a scenario XML file."); return; } Document worldDoc = null; if (opts.has(OPTION_WORLD)) { try { InputStream stream = new FileInputStream((File)opts.valueOf(OPTION_WORLD)); worldDoc = DocUtil.getDocumentFromXml(stream); } catch(FileNotFoundException fnf) { logger.fatal("Could not open the scenario XML file.", fnf); return; } } if (worldDoc == null) { logger.fatal("Must supply a world XML file."); return; } Scenario scenario; World world; try { scenario = JaxbHelper.objectFromNode(scenarioDoc, Scenario.class); world = JaxbHelper.objectFromNode(worldDoc, World.class); } catch(JAXBException je) { throw new RuntimeException("Could not parse the given scenario or world file.", je); } double scale = 0; if (opts.has(OPTION_SCALE)) { scale = (Double)opts.valueOf(OPTION_SCALE); } SimController sim = new SimController(); sim.runSim(scenario, world, scale, opts.has(OPTION_PAUSED)); }
protected Object doStringToObjectConversion(String s, Object o) throws DataTypeConversionException { try { return new SimpleDateFormat(displayFormat).parse(s); } catch (ParseException ex) { } for (String format : possibleFormats) { try { SimpleDateFormat dateFormat = new SimpleDateFormat(format); dateFormat.setLenient(false); return dateFormat.parse(s); } catch (ParseException ex) { } } throw new DataTypeConversionException("Not a valid date format", new ErrorObject(ErrorCodes.ERROR_CODE_BAD_DATE_FORMAT, s)); }
protected Object doStringToObjectConversion(String s, Object o) throws DataTypeConversionException { try { return new SimpleDateFormat(displayFormat).parse(s); } catch (Exception ex) { } for (String format : possibleFormats) { try { SimpleDateFormat dateFormat = new SimpleDateFormat(format); dateFormat.setLenient(false); return dateFormat.parse(s); } catch (Exception ex) { } } throw new DataTypeConversionException("Not a valid date format", new ErrorObject(ErrorCodes.ERROR_CODE_BAD_DATE_FORMAT, s)); }
public static Iterator<RevObject> getAll(final ObjectDatabase objectDb, final ObjectDatabase stagingDb, final Iterable<ObjectId> ids, final BulkOpListener listener) { final List<ObjectId> missingInStaging = Lists.newLinkedList(); final int limit = 1000; final BulkOpListener stagingListener = new BulkOpListener.ForwardingListener(listener) { @Override public void notFound(ObjectId id) { missingInStaging.add(id); } }; final Iterator<RevObject> foundInStaging = stagingDb.getAll(ids, stagingListener); Iterator<RevObject> compositeIterator = new AbstractIterator<RevObject>() { Iterator<RevObject> forwardedToObjectDb = Iterators.emptyIterator(); @Override protected RevObject computeNext() { if (forwardedToObjectDb.hasNext()) { return forwardedToObjectDb.next(); } if (missingInStaging.size() >= limit) { List<ObjectId> missing = new ArrayList<ObjectId>(missingInStaging); missingInStaging.clear(); forwardedToObjectDb = objectDb.getAll(missing, listener); return computeNext(); } if (foundInStaging.hasNext()) { return foundInStaging.next(); } else if (forwardedToObjectDb.hasNext()) { return forwardedToObjectDb.next(); } return endOfData(); } }; return compositeIterator; }
public static Iterator<RevObject> getAll(final ObjectDatabase objectDb, final ObjectDatabase stagingDb, final Iterable<ObjectId> ids, final BulkOpListener listener) { final List<ObjectId> missingInStaging = Lists.newLinkedList(); final int limit = 1000; final BulkOpListener stagingListener = new BulkOpListener.ForwardingListener(listener) { @Override public void notFound(ObjectId id) { missingInStaging.add(id); } }; final Iterator<RevObject> foundInStaging = stagingDb.getAll(ids, stagingListener); Iterator<RevObject> compositeIterator = new AbstractIterator<RevObject>() { Iterator<RevObject> forwardedToObjectDb = Iterators.emptyIterator(); @Override protected RevObject computeNext() { if (forwardedToObjectDb.hasNext()) { return forwardedToObjectDb.next(); } if (missingInStaging.size() >= limit) { List<ObjectId> missing = new ArrayList<ObjectId>(missingInStaging); missingInStaging.clear(); forwardedToObjectDb = objectDb.getAll(missing, listener); return computeNext(); } if (foundInStaging.hasNext()) { return foundInStaging.next(); } else if (forwardedToObjectDb.hasNext()) { return forwardedToObjectDb.next(); } else if (!missingInStaging.isEmpty()) { List<ObjectId> missing = new ArrayList<ObjectId>(missingInStaging); missingInStaging.clear(); forwardedToObjectDb = objectDb.getAll(missing, listener); return computeNext(); } return endOfData(); } }; return compositeIterator; }
public void update(float delta) { cam.getVelocity().add(new Vector2(cam.getDeltaPosition().scl(3f))); if(cam.getVelocity().x >= MAX_VEL) cam.getVelocity().x = MAX_VEL; if(cam.getVelocity().x <= -MAX_VEL) cam.getVelocity().x=-MAX_VEL; if(cam.getVelocity().y >= MAX_VEL) cam.getVelocity().y = MAX_VEL; if(cam.getVelocity().y <= -MAX_VEL) cam.getVelocity().y=-MAX_VEL; if(cam.getAcceleration().x >= MAX_ACC) cam.getAcceleration().x = MAX_ACC; if(cam.getAcceleration().x <= -MAX_ACC) cam.getAcceleration().x=-MAX_ACC; if(cam.getAcceleration().y >= MAX_ACC) cam.getAcceleration().y = MAX_ACC; if(cam.getAcceleration().y <= -MAX_ACC) cam.getAcceleration().y=-MAX_ACC; cam.getPosition().add(new Vector2(cam.getVelocity()).scl(delta)); cam.update(); if(!cam.isFree()) { cam.getVelocity().scl(0.9f); cam.setShift(0, 0); } else { cam.getVelocity().scl(0.95f); } if(cam.getVelocity().x <= 0.01f && cam.getVelocity().y <= 0.01f ) { cam.getVelocity().x = 0f; cam.getVelocity().y = 0f; if(world != null) { world.getTarget().setPosition(cam.getPosition()); world.getTarget().setReached(false); } } }
public void update(float delta) { cam.getVelocity().add(new Vector2(cam.getDeltaPosition().scl(3f))); if(cam.getVelocity().x >= MAX_VEL) cam.getVelocity().x = MAX_VEL; if(cam.getVelocity().x <= -MAX_VEL) cam.getVelocity().x=-MAX_VEL; if(cam.getVelocity().y >= MAX_VEL) cam.getVelocity().y = MAX_VEL; if(cam.getVelocity().y <= -MAX_VEL) cam.getVelocity().y=-MAX_VEL; if(cam.getAcceleration().x >= MAX_ACC) cam.getAcceleration().x = MAX_ACC; if(cam.getAcceleration().x <= -MAX_ACC) cam.getAcceleration().x=-MAX_ACC; if(cam.getAcceleration().y >= MAX_ACC) cam.getAcceleration().y = MAX_ACC; if(cam.getAcceleration().y <= -MAX_ACC) cam.getAcceleration().y=-MAX_ACC; cam.getPosition().add(new Vector2(cam.getVelocity()).scl(delta)); cam.update(); if(!cam.isFree()) { cam.getVelocity().scl(0.9f); cam.setShift(0, 0); } else { cam.getVelocity().scl(0.95f); } if(cam.getVelocity().x <= 0.01f && cam.getVelocity().y <= 0.01f ) { if(world != null) { world.getTarget().setPosition(cam.getPosition()); world.getTarget().setReached(false); } } }
public static void main(String[] args) { boolean debugwindow = false; int i; for (i = 0; i < args.length; ++i) { if (args[i].equals("-d")) debugwindow = true; break; } if (debugwindow) Log.addDebugWindow(); if (args.length == i+1 && args[i].equals("test")) { test(); } else if (args.length == i+1 && args[i].equals("mapgen")) { MapGenerator.main(new String[0]); } else if (args.length == i+1 && args[i].equals("listai")) { list("AI", Lists.ai); } else if (args.length == i+1 && args[i].equals("listrules")) { list("Turn Rules", Lists.turnRule); list("Victory Rules", Lists.victoryRule); list("Environment Collision Rules", Lists.envCollisionRule); list("Player Collision Rules", Lists.playerCollisionRule); } else if (args.length == i+1 && args[i].equals("newgui")) { new MainFrame(); } else if (args.length == i) { new Z_Menu(); } else { System.err.println("Usage: java gdp.racetrack.Main [-d] [test|mapgen|listai|listrules|newgui]"); System.err.println(" or java -jar <jarfile> [-d] [test|mapgen|listai|listrules|newgui]"); } }
public static void main(String[] args) { boolean debugwindow = false; int i; for (i = 0; i < args.length; ++i) { if (args[i].equals("-d")) debugwindow = true; else break; } if (debugwindow) Log.addDebugWindow(); if (args.length == i+1 && args[i].equals("test")) { test(); } else if (args.length == i+1 && args[i].equals("mapgen")) { MapGenerator.main(new String[0]); } else if (args.length == i+1 && args[i].equals("listai")) { list("AI", Lists.ai); } else if (args.length == i+1 && args[i].equals("listrules")) { list("Turn Rules", Lists.turnRule); list("Victory Rules", Lists.victoryRule); list("Environment Collision Rules", Lists.envCollisionRule); list("Player Collision Rules", Lists.playerCollisionRule); } else if (args.length == i+1 && args[i].equals("newgui")) { new MainFrame(); } else if (args.length == i) { new Z_Menu(); } else { System.err.println("Usage: java gdp.racetrack.Main [-d] [test|mapgen|listai|listrules|newgui]"); System.err.println(" or java -jar <jarfile> [-d] [test|mapgen|listai|listrules|newgui]"); } }
public ConsoleErrorFrame(ErrorFrame frame, ConsoleError.Observer observer) { initWidget(uiBinder.createAndBindUi(this)); frame_ = frame; observer_ = observer; boolean hasSource = !frame.getFileName().isEmpty(); functionName.setText(frame.getFunctionName() + (hasSource ? " at " : "")); if (hasSource) { sourceLink.setText(frame.getFileName()); sourceLink.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { if (frame_ != null) { observer_.showSourceForFrame(frame_); } } }); } }
public ConsoleErrorFrame(ErrorFrame frame, ConsoleError.Observer observer) { initWidget(uiBinder.createAndBindUi(this)); frame_ = frame; observer_ = observer; boolean hasSource = !frame.getFileName().isEmpty(); functionName.setText(frame.getFunctionName() + (hasSource ? " at " : "")); if (hasSource) { sourceLink.setText(frame.getFileName() + "#" + frame.getLineNumber()); sourceLink.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { if (frame_ != null) { observer_.showSourceForFrame(frame_); } } }); } }
public void climb() { if(Climbing_ == false) { Climbing_ = true; ConveyorsThread_ = new Thread(new Runnable() { public void run() { RobotMap.LHConveyor.set(0.5); RobotMap.RHConveyor.set(0.5); Timer.delay(0.2); RobotMap.LHConveyor.set(0); RobotMap.RHConveyor.set(0); while(!RobotMap.Joystick1.getRawButton(8)) { Timer.delay(0.1); } while(LevelCount_ <= StopClimbLevel_ && End_ == false) { if(RobotMap.LHTop.get() && RobotMap.RHTop.get()) { LHClimb_ = true; RHClimb_ = true; LHClimbPower_ *= -1; RHClimbPower_ *= -1; LevelCount_ += 1; } else { if(RobotMap.LHMiddle.get() && RobotMap.RHMiddle.get()) { LHClimb_ = true; RHClimb_ = true; if(LevelCount_ == StopClimbLevel_) { LHClimb_ = false; RHClimb_ = false; } else { LHClimbPower_ *= -1; RHClimbPower_ *= -1; } } else { if(RobotMap.LHTop.get() && !RobotMap.RHTop.get()) { LHClimb_ = false; } else if(RobotMap.RHTop.get() && !RobotMap.LHTop.get()) { RHClimb_ = false; } if(RobotMap.LHMiddle.get() && !RobotMap.RHMiddle.get()) { LHClimb_ = false; } else if(RobotMap.RHMiddle.get() && !RobotMap.LHMiddle.get()) { RHClimb_ = false; } } } if(LHClimb_) { RobotMap.LHConveyor.set(LHClimbPower_); } else { RobotMap.LHConveyor.set(0); } if(RHClimb_) { RobotMap.RHConveyor.set(RHClimbPower_); } else { RobotMap.RHConveyor.set(0); } Timer.delay(0.05); } RobotMap.LHConveyor.set(0); RobotMap.RHConveyor.set(0); } }); LegThread_ = new Thread(new Runnable() { public void run() { boolean bringDown = false; boolean bringUp = false; while(LevelCount_ < StopClimbLevel_ && End_ == false) { if(RobotMap.LHMiddle.get() && RobotMap.RHMiddle.get()) { bringDown = true; } if(RobotMap.LHTop.get() && RobotMap.RHTop.get()) { bringUp = true; } if(bringDown) { if(!RobotMap.LegDown.get() == false) { RobotMap.Leg.set(LegPower_); } else { RobotMap.Leg.set(0); bringDown = false; } } if(bringUp) { if(!RobotMap.LegUp.get() == false) { RobotMap.Leg.set(-LegPower_); } else { RobotMap.Leg.set(0); bringDown = false; } } Timer.delay(0.05); } while(!RobotMap.LegUp.get() == false && End_ == false) { RobotMap.Leg.set(-LegPower_); Timer.delay(0.05); } RobotMap.Leg.set(0); } }); ConveyorsThread_.start(); LegThread_.start(); } }
public void climb() { if(Climbing_ == false) { Climbing_ = true; ConveyorsThread_ = new Thread(new Runnable() { public void run() { RobotMap.LHConveyor.set(0.5); RobotMap.RHConveyor.set(0.5); Timer.delay(0.2); RobotMap.LHConveyor.set(0); RobotMap.RHConveyor.set(0); while(!RobotMap.Joystick1.getRawButton(8) && End_ == false) { Timer.delay(0.1); } while(LevelCount_ <= StopClimbLevel_ && End_ == false) { if(RobotMap.LHTop.get() && RobotMap.RHTop.get()) { LHClimb_ = true; RHClimb_ = true; LHClimbPower_ *= -1; RHClimbPower_ *= -1; LevelCount_ += 1; } else { if(RobotMap.LHMiddle.get() && RobotMap.RHMiddle.get()) { LHClimb_ = true; RHClimb_ = true; if(LevelCount_ == StopClimbLevel_) { LHClimb_ = false; RHClimb_ = false; } else { LHClimbPower_ *= -1; RHClimbPower_ *= -1; } } else { if(RobotMap.LHTop.get() && !RobotMap.RHTop.get()) { LHClimb_ = false; } else if(RobotMap.RHTop.get() && !RobotMap.LHTop.get()) { RHClimb_ = false; } if(RobotMap.LHMiddle.get() && !RobotMap.RHMiddle.get()) { LHClimb_ = false; } else if(RobotMap.RHMiddle.get() && !RobotMap.LHMiddle.get()) { RHClimb_ = false; } } } if(LHClimb_) { RobotMap.LHConveyor.set(LHClimbPower_); } else { RobotMap.LHConveyor.set(0); } if(RHClimb_) { RobotMap.RHConveyor.set(RHClimbPower_); } else { RobotMap.RHConveyor.set(0); } Timer.delay(0.05); } RobotMap.LHConveyor.set(0); RobotMap.RHConveyor.set(0); } }); LegThread_ = new Thread(new Runnable() { public void run() { boolean bringDown = false; boolean bringUp = false; while(LevelCount_ < StopClimbLevel_ && End_ == false) { if(RobotMap.LHMiddle.get() && RobotMap.RHMiddle.get()) { bringDown = true; } if(RobotMap.LHTop.get() && RobotMap.RHTop.get()) { bringUp = true; } if(bringDown) { if(!RobotMap.LegDown.get() == false) { RobotMap.Leg.set(LegPower_); } else { RobotMap.Leg.set(0); bringDown = false; } } if(bringUp) { if(!RobotMap.LegUp.get() == false) { RobotMap.Leg.set(-LegPower_); } else { RobotMap.Leg.set(0); bringDown = false; } } Timer.delay(0.05); } while(!RobotMap.LegUp.get() == false && End_ == false) { RobotMap.Leg.set(-LegPower_); Timer.delay(0.05); } RobotMap.Leg.set(0); } }); ConveyorsThread_.start(); LegThread_.start(); } }
public boolean track(HttpServletRequest request, HttpServletResponse response, TrackingData trackingData) { if (request.getHeader("User-Agent") != null) { UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent")); trackingData.addValue("browser", userAgent.getBrowser().getName()); trackingData.addValue("browser-version", userAgent.getBrowserVersion().getVersion()); } return true; }
public boolean track(HttpServletRequest request, HttpServletResponse response, TrackingData trackingData) { if (request.getHeader("User-Agent") != null) { UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent")); if (userAgent == null) { return true; } if (userAgent.getBrowser() != null) { trackingData.addValue("browser", userAgent.getBrowser().getName()); } if (userAgent.getBrowserVersion() != null) { trackingData.addValue("browser-version", userAgent.getBrowserVersion().getVersion()); } } return true; }
private void indexGenes(final ProgressUpdater progressUpdater, final List<BioEntity> bioEntities) throws IndexBuilderException { shuffle(bioEntities); final int total = bioEntities.size(); getLog().info("Found " + total + " genes to index"); final ArrayListMultimap<Long, DesignElement> allDesignElementsForGene = bioEntityDAO.getAllDesignElementsForGene(); final AtomicInteger processed = new AtomicInteger(0); final long timeStart = System.currentTimeMillis(); final int chunksize = atlasProperties.getGeneAtlasIndexBuilderChunksize(); final int commitfreq = atlasProperties.getGeneAtlasIndexBuilderCommitfreq(); getLog().info("Using {} chunk size, committing every {} genes", chunksize, commitfreq); List<Callable<Boolean>> tasks = new ArrayList<Callable<Boolean>>(bioEntities.size()); for (final List<BioEntity> genelist : partition(bioEntities, chunksize)) { tasks.add(new Callable<Boolean>() { public Boolean call() throws IOException, SolrServerException { try { StringBuilder sblog = new StringBuilder(); long start = System.currentTimeMillis(); bioEntityDAO.getPropertiesForGenes(genelist); List<SolrInputDocument> solrDocs = new ArrayList<SolrInputDocument>(genelist.size()); for (BioEntity gene : genelist) { SolrInputDocument solrInputDoc = createGeneSolrInputDocument(gene); Set<String> designElements = new HashSet<String>(); List<DesignElement> elementList = allDesignElementsForGene.get(gene.getId()); for (DesignElement de : elementList) { designElements.add(de.getName()); designElements.add(de.getAccession()); } solrInputDoc.addField("property_designelement", designElements); solrInputDoc.addField("properties", "designelement"); solrDocs.add(solrInputDoc); int processedNow = processed.incrementAndGet(); if (processedNow % commitfreq == 0 || processedNow == total) { long timeNow = System.currentTimeMillis(); long elapsed = timeNow - timeStart; double speed = (processedNow / (elapsed / (double) commitfreq)); double estimated = (total - processedNow) / (speed * 60); getLog().info( String.format("Processed %d/%d genes %d%%, %.1f genes/sec overall, estimated %.1f min remaining", processedNow, total, (processedNow * 100 / total), speed, estimated)); progressUpdater.update(processedNow + "/" + total); } gene.clearProperties(); } log(sblog, start, "adding genes to Solr index..."); getSolrServer().add(solrDocs); log(sblog, start, "... batch complete."); getLog().info("Gene chunk done:\n" + sblog); return true; } catch (RuntimeException e) { getLog().error("Runtime exception occurred: " + e.getMessage(), e); return false; } } }); } bioEntities.clear(); try { List<Future<Boolean>> results = executor.invokeAll(tasks); Iterator<Future<Boolean>> iresults = results.iterator(); while (iresults.hasNext()) { Future<Boolean> result = iresults.next(); result.get(); iresults.remove(); } } catch (InterruptedException e) { getLog().error("Indexing interrupted!", e); } catch (ExecutionException e) { throw new IndexBuilderException("Error in indexing!", e.getCause()); } finally { allDesignElementsForGene.clear(); } }
private void indexGenes(final ProgressUpdater progressUpdater, final List<BioEntity> bioEntities) throws IndexBuilderException { shuffle(bioEntities); final int total = bioEntities.size(); getLog().info("Found " + total + " genes to index"); final ArrayListMultimap<Long, DesignElement> allDesignElementsForGene = bioEntityDAO.getAllDesignElementsForGene(); getLog().info("Found " + allDesignElementsForGene.asMap().size() + " genes with de"); final AtomicInteger processed = new AtomicInteger(0); final long timeStart = System.currentTimeMillis(); final int chunksize = atlasProperties.getGeneAtlasIndexBuilderChunksize(); final int commitfreq = atlasProperties.getGeneAtlasIndexBuilderCommitfreq(); getLog().info("Using {} chunk size, committing every {} genes", chunksize, commitfreq); List<Callable<Boolean>> tasks = new ArrayList<Callable<Boolean>>(bioEntities.size()); for (final List<BioEntity> genelist : partition(bioEntities, chunksize)) { tasks.add(new Callable<Boolean>() { public Boolean call() throws IOException, SolrServerException { try { StringBuilder sblog = new StringBuilder(); long start = System.currentTimeMillis(); bioEntityDAO.getPropertiesForGenes(genelist); List<SolrInputDocument> solrDocs = new ArrayList<SolrInputDocument>(genelist.size()); for (BioEntity gene : genelist) { SolrInputDocument solrInputDoc = createGeneSolrInputDocument(gene); Set<String> designElements = new HashSet<String>(); for (DesignElement de : allDesignElementsForGene.get(gene.getId())) { designElements.add(de.getName()); designElements.add(de.getAccession()); } solrInputDoc.addField("property_designelement", designElements); solrInputDoc.addField("properties", "designelement"); solrDocs.add(solrInputDoc); int processedNow = processed.incrementAndGet(); if (processedNow % commitfreq == 0 || processedNow == total) { long timeNow = System.currentTimeMillis(); long elapsed = timeNow - timeStart; double speed = (processedNow / (elapsed / (double) commitfreq)); double estimated = (total - processedNow) / (speed * 60); getLog().info( String.format("Processed %d/%d genes %d%%, %.1f genes/sec overall, estimated %.1f min remaining", processedNow, total, (processedNow * 100 / total), speed, estimated)); progressUpdater.update(processedNow + "/" + total); } gene.clearProperties(); } log(sblog, start, "adding genes to Solr index..."); getSolrServer().add(solrDocs); log(sblog, start, "... batch complete."); getLog().info("Gene chunk done:\n" + sblog); return true; } catch (RuntimeException e) { getLog().error("Runtime exception occurred: " + e.getMessage(), e); return false; } } }); } bioEntities.clear(); try { List<Future<Boolean>> results = executor.invokeAll(tasks); Iterator<Future<Boolean>> iresults = results.iterator(); while (iresults.hasNext()) { Future<Boolean> result = iresults.next(); result.get(); iresults.remove(); } } catch (InterruptedException e) { getLog().error("Indexing interrupted!", e); } catch (ExecutionException e) { throw new IndexBuilderException("Error in indexing!", e.getCause()); } finally { allDesignElementsForGene.clear(); } }
public void onClick(View v) { Log.d(tag, "View : " + v.getId()); switch (v.getId()) { case R.id.button_workout_form_save: if (this.validateForm() == true) { model.open(); model.insert(nameTextField.getText().toString(), workoutTextField .getText().toString(), workoutConstant, recordConstant); model.close(); Intent i = new Intent(this, CustomActivity.class); startActivity(i); } else { Context context = getApplicationContext(); CharSequence text = "Please fill out all fields!"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); } break; case R.id.button_workout_form_start: if (this.validateForm() == true) { model.open(); long newId = model.insert(nameTextField.getText().toString(), workoutTextField .getText().toString(), workoutConstant, recordConstant); model.close(); Intent i = new Intent(this, WorkoutProfileActivity.class); i.putExtra("ID", newId); startActivity(i); } else { Context context = getApplicationContext(); CharSequence text = "Please fill out all fields!"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); } break; case R.id.custom_add_background: hideKeyboard(workoutTextField); hideKeyboard(nameTextField); break; } }
public void onClick(View v) { Log.d(tag, "View : " + v.getId()); switch (v.getId()) { case R.id.button_workout_form_save: if (this.validateForm() == true) { model.open(); model.insert(nameTextField.getText().toString(), workoutTextField .getText().toString(), workoutConstant, recordConstant); model.close(); finish(); Intent i = new Intent(this, CustomActivity.class); startActivity(i); } else { Context context = getApplicationContext(); CharSequence text = "Please fill out all fields!"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); } break; case R.id.button_workout_form_start: if (this.validateForm() == true) { model.open(); long newId = model.insert(nameTextField.getText().toString(), workoutTextField .getText().toString(), workoutConstant, recordConstant); model.close(); finish(); Intent i = new Intent(this, WorkoutProfileActivity.class); i.putExtra("ID", newId); startActivity(i); } else { Context context = getApplicationContext(); CharSequence text = "Please fill out all fields!"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); } break; case R.id.custom_add_background: hideKeyboard(workoutTextField); hideKeyboard(nameTextField); break; } }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter pw = response.getWriter(); try { int status = 1; String message = "U R highest bidder"; JSONObject jobj = new JSONObject(); try { String itemId = request.getParameter("itemId"); Double finalPrice = 0.0; if (request.getParameter("amount") != null) { finalPrice = Double.parseDouble((String) request .getParameter("amount")); } else { Double price = getCurrentPrice(itemId); if (price == 0) { pw.println("error"); return; } finalPrice = getBidIncrements(price); } System.out.println(request.getParameter("amount")); ApiContext apiContext = GetApiContext.getApiContext(); PlaceOfferCall apiCall = new PlaceOfferCall(apiContext); apiCall.setItemID(itemId); OfferType offer = new OfferType(); offer.setAction(BidActionCodeType.BID); AmountType amount = new AmountType(); amount.setCurrencyID(CurrencyCodeType.USD); amount.setValue(finalPrice); offer.setMaxBid(amount); offer.setQuantity(1); apiCall.setOffer(offer); apiCall.setEndUserIP("195.34.23.32"); System.out.println("Begin to cal eBay API, please wait ... "); SellingStatusType sellingStatus = apiCall.placeOffer(); Double currentPrice = sellingStatus.getCurrentPrice() .getValue(); System.out.println("cr " +currentPrice); System.out.println("fr " +finalPrice); if (currentPrice <= finalPrice) { status = 0; } else { status = 1; message = "Outbid. Bid atleast $" + sellingStatus.getMinimumToBid().getValue(); } System.out.println("End to cal eBay API, show call result ..."); } catch (Exception e) { System.out.println("Fail to get eBay official time."); status = 2; message = "Your Bid < current price"; e.printStackTrace(); } jobj.put("ack", status); jobj.put("message", message); pw.println(jobj); } catch (JSONException je) { pw.print("error"); } }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter pw = response.getWriter(); try { int status = 1; String message = "U R highest bidder"; JSONObject jobj = new JSONObject(); try { String itemId = request.getParameter("itemId"); Double finalPrice = 0.0; if (request.getParameter("amount") != null) { finalPrice = Double.parseDouble((String) request .getParameter("amount")); } else { Double price = getCurrentPrice(itemId); if (price == 0) { pw.println("error"); return; } finalPrice = getBidIncrements(price); } System.out.println(request.getParameter("amount")); ApiContext apiContext = GetApiContext.getApiContext(); PlaceOfferCall apiCall = new PlaceOfferCall(apiContext); apiCall.setItemID(itemId); OfferType offer = new OfferType(); offer.setAction(BidActionCodeType.BID); AmountType amount = new AmountType(); amount.setCurrencyID(CurrencyCodeType.USD); amount.setValue(finalPrice); offer.setMaxBid(amount); offer.setQuantity(1); apiCall.setOffer(offer); apiCall.setEndUserIP("195.34.23.32"); System.out.println("Begin to cal eBay API, please wait ... "); SellingStatusType sellingStatus = apiCall.placeOffer(); Double currentPrice = sellingStatus.getCurrentPrice() .getValue(); System.out.println("cr " +currentPrice); System.out.println("fr " +finalPrice); if (currentPrice <= finalPrice) { status = 0; } else { status = 1; message = "Outbid. Bid atleast $" + sellingStatus.getMinimumToBid().getValue(); } System.out.println("End to cal eBay API, show call result ..."); } catch (Exception e) { System.out.println("Fail to get eBay official time."); status = 2; message = "Your Bid price is too low"; e.printStackTrace(); } jobj.put("ack", status); jobj.put("message", message); pw.println(jobj); } catch (JSONException je) { pw.print("error"); } }
public static void main( String[] args ) { try{ (new Core(args)).run(); } catch(FileNotFoundException e) { System.out.println(Message.getSSLError("FileNotFound")); System.out.println("[CRITICAL]: Closing server."); } catch(IOException e) { System.out.println(Message.getSSLError("WrongKey")); System.out.println("[CRITICAL]: Closing server."); } catch (UnrecoverableKeyException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (CertificateException e) { System.out.println(Message.getSSLError("WrongCertificate")); System.out.println("[CRITICAL]: Closing server."); } }
public static void main( String[] args ) { try{ (new Core(args)).run(); } catch(FileNotFoundException e) { System.out.println(Message.getSSLError("FileNotFound")); System.out.println("[CRITICAL]: Closing server."); } catch(java.net.ConnectException e) { System.out.println(Message.getSSLError("NoConnection")); System.out.println("[CRITICAL]: Closing server."); } catch(IOException e) { System.out.println(Message.getSSLError("WrongKey")); System.out.println("[CRITICAL]: Closing server."); } catch (UnrecoverableKeyException e) { System.out.println(Message.getSSLError("UnrecoverableKeyException")); System.out.println("[CRITICAL]: Closing server."); } catch (KeyManagementException e) { System.out.println(Message.getSSLError("KeyManagementException")); System.out.println("[CRITICAL]: Closing server."); } catch (KeyStoreException e) { System.out.println(Message.getSSLError("KeyStoreException")); System.out.println("[CRITICAL]: Closing server."); } catch (NoSuchAlgorithmException e) { System.out.println(Message.getSSLError("NoSuchAlgorithmException")); System.out.println("[CRITICAL]: Closing server."); } catch (CertificateException e) { System.out.println(Message.getSSLError("WrongCertificate")); System.out.println("[CRITICAL]: Closing server."); } }
protected void computePositions() { final int[] levels = new int[internalGraph.getNodeCount()]; Arrays.fill(levels, -1); final int[] columns = new int[internalGraph.getNodeCount()]; LinkedList<Node> roots = new LinkedList<Node>(), roots2 = new LinkedList<Node>(); if (this.roots.size() > 0) { for (int i = 0; i < roots.size(); i++) roots.add(internalGraph.getNode(this.roots.get(i))); } SpanningTree tree = new Prim("weight", "inTree"); tree.init(internalGraph); tree.compute(); if (roots.size() == 0) { int max = internalGraph.getNode(0).getDegree(); int maxIndex = 0; for (int i = 1; i < internalGraph.getNodeCount(); i++) if (internalGraph.getNode(i).getDegree() > max) { max = internalGraph.getNode(i).getDegree(); maxIndex = i; } roots.add(internalGraph.getNode(maxIndex)); } Box rootBox = new Box(); LevelBox rootLevelBox = new LevelBox(0); LinkedList<LevelBox> levelBoxes = new LinkedList<LevelBox>(); rootLevelBox.add(rootBox); levelBoxes.add(rootLevelBox); for (int i = 0; i < roots.size(); i++) { Node n = roots.get(i); levels[n.getIndex()] = 0; columns[n.getIndex()] = i; setBox(rootBox, n); } do { while (roots.size() > 0) { Node root = roots.poll(); int level = levels[root.getIndex()] + 1; Box box = getChildrenBox(root); for (Edge e : root.getEdgeSet()) { if (e.getAttribute(tree.getFlagAttribute()).equals( tree.getFlagOn())) { Node op = e.getOpposite(root); if (levels[op.getIndex()] < 0 || level < levels[op.getIndex()]) { levels[op.getIndex()] = level; roots2.add(op); op.setAttribute("parent", root); setBox(box, op); } } } } roots.addAll(roots2); roots2.clear(); } while (roots.size() > 0); FibonacciHeap<Integer, Box> boxes = new FibonacciHeap<Integer, Box>(); boxes.add(0, rootBox); for (int i = 0; i < internalGraph.getNodeCount(); i++) { Box box = getChildrenBox(internalGraph.getNode(i)); if (box != null) { boxes.add(box.level, box); while (levelBoxes.size() <= box.level) levelBoxes.add(new LevelBox(levelBoxes.size())); levelBoxes.get(box.level).add(box); } } for (int i = 0; i < levelBoxes.size(); i++) levelBoxes.get(i).sort(); while (boxes.size() > 0) renderBox(boxes.extractMin()); hi.x = hi.y = Double.MIN_VALUE; lo.x = lo.y = Double.MAX_VALUE; for (int idx = 0; idx < internalGraph.getNodeCount(); idx++) { Node n = internalGraph.getNode(idx); double y = n.getNumber("y"); double x = n.getNumber("x"); if (!n.hasNumber("oldX") || n.getNumber("oldX") != x || !n.hasNumber("oldY") || n.getNumber("oldY") != y) { n.setAttribute("oldX", x); n.setAttribute("oldY", y); n.addAttribute("changed"); nodeMoved++; } hi.x = Math.max(hi.x, x); hi.y = Math.max(hi.y, y); lo.x = Math.min(lo.x, x); lo.y = Math.min(lo.y, y); } }
protected void computePositions() { final int[] levels = new int[internalGraph.getNodeCount()]; Arrays.fill(levels, -1); final int[] columns = new int[internalGraph.getNodeCount()]; LinkedList<Node> roots = new LinkedList<Node>(), roots2 = new LinkedList<Node>(); if (this.roots.size() > 0) { for (int i = 0; i < this.roots.size(); i++) roots.add(internalGraph.getNode(this.roots.get(i))); } SpanningTree tree = new Prim("weight", "inTree"); tree.init(internalGraph); tree.compute(); if (roots.size() == 0) { int max = internalGraph.getNode(0).getDegree(); int maxIndex = 0; for (int i = 1; i < internalGraph.getNodeCount(); i++) if (internalGraph.getNode(i).getDegree() > max) { max = internalGraph.getNode(i).getDegree(); maxIndex = i; } roots.add(internalGraph.getNode(maxIndex)); } Box rootBox = new Box(); LevelBox rootLevelBox = new LevelBox(0); LinkedList<LevelBox> levelBoxes = new LinkedList<LevelBox>(); rootLevelBox.add(rootBox); levelBoxes.add(rootLevelBox); for (int i = 0; i < roots.size(); i++) { Node n = roots.get(i); levels[n.getIndex()] = 0; columns[n.getIndex()] = i; setBox(rootBox, n); } do { while (roots.size() > 0) { Node root = roots.poll(); int level = levels[root.getIndex()] + 1; Box box = getChildrenBox(root); for (Edge e : root.getEdgeSet()) { if (e.getAttribute(tree.getFlagAttribute()).equals( tree.getFlagOn())) { Node op = e.getOpposite(root); if (levels[op.getIndex()] < 0 || level < levels[op.getIndex()]) { levels[op.getIndex()] = level; roots2.add(op); op.setAttribute("parent", root); setBox(box, op); } } } } roots.addAll(roots2); roots2.clear(); } while (roots.size() > 0); FibonacciHeap<Integer, Box> boxes = new FibonacciHeap<Integer, Box>(); boxes.add(0, rootBox); for (int i = 0; i < internalGraph.getNodeCount(); i++) { Box box = getChildrenBox(internalGraph.getNode(i)); if (box != null) { boxes.add(box.level, box); while (levelBoxes.size() <= box.level) levelBoxes.add(new LevelBox(levelBoxes.size())); levelBoxes.get(box.level).add(box); } } for (int i = 0; i < levelBoxes.size(); i++) levelBoxes.get(i).sort(); while (boxes.size() > 0) renderBox(boxes.extractMin()); hi.x = hi.y = Double.MIN_VALUE; lo.x = lo.y = Double.MAX_VALUE; for (int idx = 0; idx < internalGraph.getNodeCount(); idx++) { Node n = internalGraph.getNode(idx); double y = n.getNumber("y"); double x = n.getNumber("x"); if (!n.hasNumber("oldX") || n.getNumber("oldX") != x || !n.hasNumber("oldY") || n.getNumber("oldY") != y) { n.setAttribute("oldX", x); n.setAttribute("oldY", y); n.addAttribute("changed"); nodeMoved++; } hi.x = Math.max(hi.x, x); hi.y = Math.max(hi.y, y); lo.x = Math.min(lo.x, x); lo.y = Math.min(lo.y, y); } }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); ListPreference order = (ListPreference) findPreference("sortOrderPref"); order.setSummary(order.getEntry()); order.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { ListPreference x = (ListPreference) preference; int index = Arrays.asList(x.getEntryValues()).indexOf(newValue); preference.setSummary(x.getEntries()[index]); return true; } }); CheckBoxPreference vibrate = (CheckBoxPreference) findPreference("pingVibrate"); vibrate.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { CheckBoxPreference x = (CheckBoxPreference) preference; if (x.isChecked()) { Vibrator v = (Vibrator) getSystemService(VIBRATOR_SERVICE); v.vibrate(100); } return true; } }); }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); ListPreference order = (ListPreference) findPreference("sortOrderPref"); order.setSummary(order.getEntry()); order.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { ListPreference x = (ListPreference) preference; int index = Arrays.asList(x.getEntryValues()).indexOf(newValue); preference.setSummary(x.getEntries()[index]); return true; } }); CheckBoxPreference vibrate = (CheckBoxPreference) findPreference("pingVibrate"); vibrate.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { if ((Boolean) newValue) { Vibrator v = (Vibrator) getSystemService(VIBRATOR_SERVICE); v.vibrate(25); } return true; } }); }
public static Properties getInstance(){ if (properties == null){ properties = new Properties(); try { properties.load(new FileInputStream("src/main/config/default.config")); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return properties; }
public static Properties getInstance(){ if (properties == null){ properties = new Properties(); try { properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("default.config")); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return properties; }
private AnnotatedParameter addUniqueQualifier(final AnnotatedMethod method, final AnnotatedParameter param, final String identifier) { final BusManaged qualifier = new BusManaged() { @Override public Class<? extends Annotation> annotationType() { return BusManaged.class; } @Override public String value() { return identifier; } }; addQualifierToMap(method, param, qualifier); final Set<Annotation> annotations = new HashSet<Annotation>(); annotations.addAll(param.getAnnotations()); annotations.add(qualifier); return new AnnotatedParameter<Object>() { @Override public <T extends Annotation> T getAnnotation(final Class<T> clazz) { if (BusManaged.class.isAssignableFrom(clazz)) { return (T) qualifier; } return param.getAnnotation(clazz); } @Override public Set<Annotation> getAnnotations() { return annotations; } @Override public Type getBaseType() { return param.getBaseType(); } @Override public Set<Type> getTypeClosure() { return param.getTypeClosure(); } @Override public boolean isAnnotationPresent(final Class<? extends Annotation> clazz) { if (BusManaged.class.isAssignableFrom(clazz)) { return true; } return param.isAnnotationPresent(clazz); } @Override public AnnotatedCallable<Object> getDeclaringCallable() { return param.getDeclaringCallable(); } @Override public int getPosition() { return param.getPosition(); } }; }
private AnnotatedParameter addUniqueQualifier(final AnnotatedMethod method, final AnnotatedParameter param, final String identifier) { final BusManaged qualifier = new BusManaged() { @Override public Class<? extends Annotation> annotationType() { return BusManaged.class; } @Override public String value() { return identifier; } }; addQualifierToMap(method, param, qualifier); final Set<Annotation> annotations = new HashSet<Annotation>(); annotations.addAll(param.getAnnotations()); annotations.add(qualifier); return new AnnotatedParameter<Object>() { @Override public <T extends Annotation> T getAnnotation(final Class<T> clazz) { if (BusManaged.class.isAssignableFrom(clazz)) { return (T) qualifier; } return param.getAnnotation(clazz); } @Override public Set<Annotation> getAnnotations() { return annotations; } @Override public Type getBaseType() { return param.getBaseType(); } @Override public Set<Type> getTypeClosure() { return param.getTypeClosure(); } @Override public boolean isAnnotationPresent(final Class<? extends Annotation> clazz) { if (BusManaged.class.isAssignableFrom(clazz)) { return true; } return param.isAnnotationPresent(clazz); } @Override public AnnotatedCallable<Object> getDeclaringCallable() { return param.getDeclaringCallable(); } @Override public int getPosition() { return param.getPosition(); } }; }
protected String generateConfig() { StringBuilder sb = new StringBuilder(); sb.append("<dataConfig> \n"); sb.append("<dataSource name=\"derby\" driver=\"org.apache.derby.jdbc.EmbeddedDriver\" url=\"jdbc:derby:memory:derbyDB;\" /> \n"); sb.append("<document name=\"TestSimplePropertiesWriter\"> \n"); sb.append("<entity name=\"FIRST\" processor=\"SqlEntityProcessor\" dataSource=\"derby\" "); sb.append(" query=\"select 1 as id, 'PORK' as FIRST_S from sysibm.sysdummy1 \" >\n"); sb.append(" <field column=\"FIRST_S\" name=\"first_s\" /> \n"); sb.append(" <entity name=\"SECOND\" processor=\"SqlEntityProcessor\" dataSource=\"derby\" "); sb.append(" query=\"select 1 as id, 2 as SECOND_ID, 'BEEF' as SECOND_S from sysibm.sysdummy1 WHERE 1=${FIRST.ID}\" >\n"); sb.append(" <field column=\"SECOND_S\" name=\"second_s\" /> \n"); sb.append(" <entity name=\"SECOND\" processor=\"SqlEntityProcessor\" dataSource=\"derby\" "); sb.append(" query=\"select 1 as id, 'CHICKEN' as THIRD_S from sysibm.sysdummy1 WHERE 2=${SECOND.SECOND_ID}\" >\n"); sb.append(" <field column=\"THIRD_S\" name=\"third_s\" /> \n"); sb.append(" </entity>\n"); sb.append(" </entity>\n"); sb.append("</entity>\n"); sb.append("</document> \n"); sb.append("</dataConfig> \n"); String config = sb.toString(); log.debug(config); return config; }
protected String generateConfig() { StringBuilder sb = new StringBuilder(); sb.append("<dataConfig> \n"); sb.append("<dataSource name=\"derby\" driver=\"org.apache.derby.jdbc.EmbeddedDriver\" url=\"jdbc:derby:memory:derbyDB;\" /> \n"); sb.append("<document name=\"TestSimplePropertiesWriter\"> \n"); sb.append("<entity name=\"FIRST\" processor=\"SqlEntityProcessor\" dataSource=\"derby\" "); sb.append(" query=\"select 1 as id, 'PORK' as FIRST_S from sysibm.sysdummy1 \" >\n"); sb.append(" <field column=\"FIRST_S\" name=\"first_s\" /> \n"); sb.append(" <entity name=\"SECOND\" processor=\"SqlEntityProcessor\" dataSource=\"derby\" "); sb.append(" query=\"select 1 as id, 2 as SECOND_ID, 'BEEF' as SECOND_S from sysibm.sysdummy1 WHERE 1=${FIRST.ID}\" >\n"); sb.append(" <field column=\"SECOND_S\" name=\"second_s\" /> \n"); sb.append(" <entity name=\"THIRD\" processor=\"SqlEntityProcessor\" dataSource=\"derby\" "); sb.append(" query=\"select 1 as id, 'CHICKEN' as THIRD_S from sysibm.sysdummy1 WHERE 2=${SECOND.SECOND_ID}\" >\n"); sb.append(" <field column=\"THIRD_S\" name=\"third_s\" /> \n"); sb.append(" </entity>\n"); sb.append(" </entity>\n"); sb.append("</entity>\n"); sb.append("</document> \n"); sb.append("</dataConfig> \n"); String config = sb.toString(); log.debug(config); return config; }
private List<JCStatement> transformCondition(Tree.Condition cond, int tag, Tree.Block thenPart, Tree.Block elsePart) { JCExpression test; JCVariableDecl decl = null; JCBlock thenBlock = null; JCBlock elseBlock = null; if ((cond instanceof Tree.IsCondition) || (cond instanceof Tree.NonemptyCondition) || (cond instanceof Tree.ExistsCondition)) { String name; ProducedType toType; Expression specifierExpr; if (cond instanceof Tree.IsCondition) { Tree.IsCondition isdecl = (Tree.IsCondition) cond; name = isdecl.getVariable().getIdentifier().getText(); toType = isdecl.getType().getTypeModel(); specifierExpr = isdecl.getVariable().getSpecifierExpression().getExpression(); } else if (cond instanceof Tree.NonemptyCondition) { Tree.NonemptyCondition nonempty = (Tree.NonemptyCondition) cond; name = nonempty.getVariable().getIdentifier().getText(); toType = nonempty.getVariable().getType().getTypeModel(); specifierExpr = nonempty.getVariable().getSpecifierExpression().getExpression(); } else { Tree.ExistsCondition exists = (Tree.ExistsCondition) cond; name = exists.getVariable().getIdentifier().getText(); toType = exists.getVariable().getType().getTypeModel(); specifierExpr = exists.getVariable().getSpecifierExpression().getExpression(); } JCExpression expr = expressionGen().transformExpression(specifierExpr); at(cond); if (cond instanceof Tree.IsCondition && isNothing(toType)) { test = make().Binary(JCTree.EQ, expr, makeNull()); } else { toType = simplifyType(toType); JCExpression toTypeExpr = makeJavaType(toType); String tmpVarName = aliasName(name); Name origVarName = names().fromString(name); Name substVarName = names().fromString(aliasName(name)); ProducedType tmpVarType = specifierExpr.getTypeModel(); JCExpression tmpVarTypeExpr; JCExpression rawToTypeExpr = makeJavaType(toType, NO_PRIMITIVES | WANT_RAW_TYPE); JCExpression tmpVarExpr = makeIdent(tmpVarName); if (cond instanceof Tree.ExistsCondition) { tmpVarExpr = unboxType(tmpVarExpr, toType); tmpVarTypeExpr = makeJavaType(tmpVarType); } else if(cond instanceof Tree.IsCondition){ tmpVarExpr = unboxType(at(cond).TypeCast(rawToTypeExpr, tmpVarExpr), toType); tmpVarTypeExpr = make().Type(syms().objectType); } else { tmpVarExpr = at(cond).TypeCast(toTypeExpr, tmpVarExpr); tmpVarTypeExpr = makeJavaType(tmpVarType); } decl = makeVar(tmpVarName, tmpVarTypeExpr, null); JCVariableDecl decl2 = at(cond).VarDef(make().Modifiers(FINAL), substVarName, toTypeExpr, tmpVarExpr); String prevSubst = addVariableSubst(origVarName.toString(), substVarName.toString()); thenBlock = transform(thenPart); List<JCStatement> stats = List.<JCStatement> of(decl2); stats = stats.appendList(thenBlock.getStatements()); thenBlock = at(cond).Block(0, stats); removeVariableSubst(origVarName.toString(), prevSubst); at(cond); JCExpression testExpr = make().Assign(makeIdent(tmpVarName), expr); if (cond instanceof Tree.ExistsCondition) { test = make().Binary(JCTree.NE, testExpr, makeNull()); } else { test = makeTypeTest(testExpr, expr, toType); } } } else if (cond instanceof Tree.BooleanCondition) { Tree.BooleanCondition booleanCondition = (Tree.BooleanCondition) cond; test = expressionGen().transformExpression(booleanCondition.getExpression(), BoxingStrategy.UNBOXED, null); } else { throw new RuntimeException("Not implemented: " + cond.getNodeType()); } at(cond); if (thenPart != null && thenBlock == null) { thenBlock = transform(thenPart); } if (elsePart != null && elseBlock == null) { elseBlock = transform(elsePart); } JCStatement cond1; switch (tag) { case JCTree.IF: cond1 = make().If(test, thenBlock, elseBlock); break; case JCTree.WHILELOOP: cond1 = make().WhileLoop(makeLetExpr(make().TypeIdent(TypeTags.BOOLEAN), test), thenBlock); break; default: throw new RuntimeException(); } if (decl != null) { return List.<JCStatement> of(decl, cond1); } else { return List.<JCStatement> of(cond1); } }
private List<JCStatement> transformCondition(Tree.Condition cond, int tag, Tree.Block thenPart, Tree.Block elsePart) { JCExpression test; JCVariableDecl decl = null; JCBlock thenBlock = null; JCBlock elseBlock = null; if ((cond instanceof Tree.IsCondition) || (cond instanceof Tree.NonemptyCondition) || (cond instanceof Tree.ExistsCondition)) { String name; ProducedType toType; Expression specifierExpr; if (cond instanceof Tree.IsCondition) { Tree.IsCondition isdecl = (Tree.IsCondition) cond; name = isdecl.getVariable().getIdentifier().getText(); toType = isdecl.getType().getTypeModel(); specifierExpr = isdecl.getVariable().getSpecifierExpression().getExpression(); } else if (cond instanceof Tree.NonemptyCondition) { Tree.NonemptyCondition nonempty = (Tree.NonemptyCondition) cond; name = nonempty.getVariable().getIdentifier().getText(); toType = nonempty.getVariable().getType().getTypeModel(); specifierExpr = nonempty.getVariable().getSpecifierExpression().getExpression(); } else { Tree.ExistsCondition exists = (Tree.ExistsCondition) cond; name = exists.getVariable().getIdentifier().getText(); toType = simplifyType(exists.getVariable().getType().getTypeModel()); specifierExpr = exists.getVariable().getSpecifierExpression().getExpression(); } JCExpression expr = expressionGen().transformExpression(specifierExpr); at(cond); if (cond instanceof Tree.IsCondition && isNothing(toType)) { test = make().Binary(JCTree.EQ, expr, makeNull()); } else { JCExpression toTypeExpr = makeJavaType(toType); String tmpVarName = aliasName(name); Name origVarName = names().fromString(name); Name substVarName = names().fromString(aliasName(name)); ProducedType tmpVarType = specifierExpr.getTypeModel(); JCExpression tmpVarTypeExpr; JCExpression rawToTypeExpr = makeJavaType(toType, NO_PRIMITIVES | WANT_RAW_TYPE); JCExpression tmpVarExpr = makeIdent(tmpVarName); if (cond instanceof Tree.ExistsCondition) { tmpVarExpr = unboxType(tmpVarExpr, toType); tmpVarTypeExpr = makeJavaType(tmpVarType); } else if(cond instanceof Tree.IsCondition){ tmpVarExpr = unboxType(at(cond).TypeCast(rawToTypeExpr, tmpVarExpr), toType); tmpVarTypeExpr = make().Type(syms().objectType); } else { tmpVarExpr = at(cond).TypeCast(toTypeExpr, tmpVarExpr); tmpVarTypeExpr = makeJavaType(tmpVarType); } decl = makeVar(tmpVarName, tmpVarTypeExpr, null); JCVariableDecl decl2 = at(cond).VarDef(make().Modifiers(FINAL), substVarName, toTypeExpr, tmpVarExpr); String prevSubst = addVariableSubst(origVarName.toString(), substVarName.toString()); thenBlock = transform(thenPart); List<JCStatement> stats = List.<JCStatement> of(decl2); stats = stats.appendList(thenBlock.getStatements()); thenBlock = at(cond).Block(0, stats); removeVariableSubst(origVarName.toString(), prevSubst); at(cond); JCExpression testExpr = make().Assign(makeIdent(tmpVarName), expr); if (cond instanceof Tree.ExistsCondition) { test = make().Binary(JCTree.NE, testExpr, makeNull()); } else { test = makeTypeTest(testExpr, expr, toType); } } } else if (cond instanceof Tree.BooleanCondition) { Tree.BooleanCondition booleanCondition = (Tree.BooleanCondition) cond; test = expressionGen().transformExpression(booleanCondition.getExpression(), BoxingStrategy.UNBOXED, null); } else { throw new RuntimeException("Not implemented: " + cond.getNodeType()); } at(cond); if (thenPart != null && thenBlock == null) { thenBlock = transform(thenPart); } if (elsePart != null && elseBlock == null) { elseBlock = transform(elsePart); } JCStatement cond1; switch (tag) { case JCTree.IF: cond1 = make().If(test, thenBlock, elseBlock); break; case JCTree.WHILELOOP: cond1 = make().WhileLoop(makeLetExpr(make().TypeIdent(TypeTags.BOOLEAN), test), thenBlock); break; default: throw new RuntimeException(); } if (decl != null) { return List.<JCStatement> of(decl, cond1); } else { return List.<JCStatement> of(cond1); } }
public Collection<Api> parse() { List<Api> apis = new ArrayList<Api>(); Map<String, Collection<Method>> apiMethods = new HashMap<String, Collection<Method>>(); for (MethodDoc method : classDoc.methods()) { ApiMethodParser methodParser = parentMethod == null ? new ApiMethodParser(options, rootPath, method) : new ApiMethodParser(options, parentMethod, method); Method parsedMethod = methodParser.parse(); if (parsedMethod == null) { continue; } if (parsedMethod.isSubResource()) { ClassDoc subResourceClassDoc = lookUpClassDoc(method.returnType()); if (subResourceClassDoc != null) { Collection<ClassDoc> shrunkClasses = new ArrayList<ClassDoc>(classes); shrunkClasses.remove(classDoc); ApiClassParser subResourceParser = new ApiClassParser(options, subResourceClassDoc, shrunkClasses, parsedMethod); apis.addAll(subResourceParser.parse()); models.addAll(subResourceParser.models()); continue; } } models.addAll(methodParser.models()); String realPath = parsedMethod.getPath(); Collection<Method> matchingMethods = apiMethods.get(realPath); if (matchingMethods == null) { matchingMethods = new ArrayList<Method>(); apiMethods.put(realPath, matchingMethods); } matchingMethods.add(parsedMethod); } for (Map.Entry<String, Collection<Method>> apiEntries : apiMethods.entrySet()) { Collection<Operation> operations = new ArrayList<Operation>( transform(apiEntries.getValue(), new Function<Method, Operation>() { @Override public Operation apply(Method method) { return new Operation(method); } }) ); apis.add(new Api(apiEntries.getKey(), "", operations)); } Collections.sort(apis, new Comparator<Api>() { @Override public int compare(Api o1, Api o2) { return o1.getPath().compareTo(o2.getPath()); } }); return apis; }
public Collection<Api> parse() { List<Api> apis = new ArrayList<Api>(); Map<String, Collection<Method>> apiMethods = new HashMap<String, Collection<Method>>(); for (MethodDoc method : classDoc.methods()) { ApiMethodParser methodParser = parentMethod == null ? new ApiMethodParser(options, rootPath, method) : new ApiMethodParser(options, parentMethod, method); Method parsedMethod = methodParser.parse(); if (parsedMethod == null) { continue; } if (parsedMethod.isSubResource()) { ClassDoc subResourceClassDoc = lookUpClassDoc(method.returnType()); if (subResourceClassDoc != null) { Collection<ClassDoc> shrunkClasses = new ArrayList<ClassDoc>(classes); shrunkClasses.remove(classDoc); ApiClassParser subResourceParser = new ApiClassParser(options, subResourceClassDoc, shrunkClasses, parsedMethod); apis.addAll(subResourceParser.parse()); models.addAll(subResourceParser.models()); } continue; } models.addAll(methodParser.models()); String realPath = parsedMethod.getPath(); Collection<Method> matchingMethods = apiMethods.get(realPath); if (matchingMethods == null) { matchingMethods = new ArrayList<Method>(); apiMethods.put(realPath, matchingMethods); } matchingMethods.add(parsedMethod); } for (Map.Entry<String, Collection<Method>> apiEntries : apiMethods.entrySet()) { Collection<Operation> operations = new ArrayList<Operation>( transform(apiEntries.getValue(), new Function<Method, Operation>() { @Override public Operation apply(Method method) { return new Operation(method); } }) ); apis.add(new Api(apiEntries.getKey(), "", operations)); } Collections.sort(apis, new Comparator<Api>() { @Override public int compare(Api o1, Api o2) { return o1.getPath().compareTo(o2.getPath()); } }); return apis; }
public static BufferedImage getQRCode(Integer size, String paymentString, boolean hasBranging) throws IOException { if (size == null) { size = SmartPaymentConstants.defQRSize; } else if (size < SmartPaymentConstants.minQRSize) { size = SmartPaymentConstants.minQRSize; } else if (size > SmartPaymentConstants.maxQRSize) { size = SmartPaymentConstants.maxQRSize; } BitMatrix matrix = null; int h = size; int w = size; int barsize = -1; Writer writer = new MultiFormatWriter(); try { Map<EncodeHintType, Object> hints = new EnumMap<EncodeHintType, Object>(EncodeHintType.class); hints.put(EncodeHintType.CHARACTER_SET, "ISO-8859-1"); QRCode code = Encoder.encode(paymentString, ErrorCorrectionLevel.M, hints); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); barsize = size / (code.getMatrix().getWidth() + 8); matrix = writer.encode(paymentString, com.google.zxing.BarcodeFormat.QR_CODE, w, h, hints); } catch (com.google.zxing.WriterException e) { System.out.println(e.getMessage()); } if (matrix == null || barsize < 0) { throw new InvalidFormatException(); } BufferedImage image = MatrixToImageWriter.toBufferedImage(matrix); if (hasBranging) { Graphics2D g = (Graphics2D) image.getGraphics(); BasicStroke bs = new BasicStroke(2); g.setStroke(bs); g.setColor(Color.BLACK); g.drawLine(0, 0, w, 0); g.drawLine(0, 0, 0, h); g.drawLine(w, 0, w, h); g.drawLine(0, h, w, h); String str = "QR Platba"; int fontSize = size / 12; g.setFont(new Font("Arial", Font.BOLD, fontSize)); FontMetrics fm = g.getFontMetrics(); Rectangle2D rect = fm.getStringBounds(str, g); g.setColor(Color.WHITE); g.fillRect(2 * barsize, h - fm.getAscent(), (int) rect.getWidth() + 4 * barsize, (int) rect.getHeight()); int padding = 4 * barsize; BufferedImage paddedImage = new BufferedImage(w + 2 * padding, h + padding + (int) rect.getHeight(), image.getType()); Graphics2D g2 = paddedImage.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP); g2.setFont(new Font("Arial", Font.BOLD, fontSize)); g2.setPaint(Color.WHITE); g2.fillRect(0, 0, paddedImage.getWidth(), paddedImage.getHeight()); g2.drawImage(image, padding, padding, Color.WHITE, null); g2.setColor(Color.BLACK); g2.drawString(str, padding + 4 * barsize, (int) (padding + h + rect.getHeight() - barsize)); image = paddedImage; } return image; }
public static BufferedImage getQRCode(Integer size, String paymentString, boolean hasBranging) throws IOException { if (size == null) { size = SmartPaymentConstants.defQRSize; } else if (size < SmartPaymentConstants.minQRSize) { size = SmartPaymentConstants.minQRSize; } else if (size > SmartPaymentConstants.maxQRSize) { size = SmartPaymentConstants.maxQRSize; } BitMatrix matrix = null; int h = size; int w = size; int barsize = -1; Writer writer = new MultiFormatWriter(); try { Map<EncodeHintType, Object> hints = new EnumMap<EncodeHintType, Object>(EncodeHintType.class); hints.put(EncodeHintType.CHARACTER_SET, "ISO-8859-1"); QRCode code = Encoder.encode(paymentString, ErrorCorrectionLevel.M, hints); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); barsize = size / (code.getMatrix().getWidth() + 8); matrix = writer.encode(paymentString, com.google.zxing.BarcodeFormat.QR_CODE, w, h, hints); } catch (com.google.zxing.WriterException e) { System.out.println(e.getMessage()); } if (matrix == null || barsize < 0) { throw new InvalidFormatException(); } BufferedImage image = MatrixToImageWriter.toBufferedImage(matrix); if (hasBranging) { Graphics2D g = (Graphics2D) image.getGraphics(); BasicStroke bs = new BasicStroke(2); g.setStroke(bs); g.setColor(Color.BLACK); g.drawLine(0, 0, w, 0); g.drawLine(0, 0, 0, h); g.drawLine(w, 0, w, h); g.drawLine(0, h, w, h); String str = "QR Platba"; int fontSize = size / 12; g.setFont(new Font("Verdana", Font.BOLD, fontSize)); FontMetrics fm = g.getFontMetrics(); Rectangle2D rect = fm.getStringBounds(str, g); g.setColor(Color.WHITE); g.fillRect(2 * barsize, h - fm.getAscent(), (int) rect.getWidth() + 4 * barsize, (int) rect.getHeight()); int padding = 4 * barsize; BufferedImage paddedImage = new BufferedImage(w + 2 * padding, h + padding + (int) rect.getHeight(), image.getType()); Graphics2D g2 = paddedImage.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP); g2.setFont(new Font("Verdana", Font.BOLD, fontSize)); g2.setPaint(Color.WHITE); g2.fillRect(0, 0, paddedImage.getWidth(), paddedImage.getHeight()); g2.drawImage(image, padding, padding, Color.WHITE, null); g2.setColor(Color.BLACK); g2.drawString(str, padding + 4 * barsize, (int) (padding + h + rect.getHeight() - barsize)); image = paddedImage; } return image; }
public static void main(String args[]) throws Exception { File inboxDirectory = new File("data/inbox"); File outboxDirectory = new File("data/outbox"); outboxDirectory.mkdir(); File[] files = inboxDirectory.listFiles(); for (File source : files) { File dest = new File( outboxDirectory.getPath() + File.separator + source.getName()); copyFile(source, dest); } }
public static void main(String args[]) throws Exception { File inboxDirectory = new File("data/inbox"); File outboxDirectory = new File("data/outbox"); outboxDirectory.mkdir(); File[] files = inboxDirectory.listFiles(); for (File source : files) { if (source.isFile()) { File dest = new File( outboxDirectory.getPath() + File.separator + source.getName()); copyFile(source, dest); } } }
public static double intersectionArea(Shape s1, Shape s2) { final int w = 100; final int h = 100; final Area area = new Area(s1); area.intersect(new Area(s2)); Rectangle2D bounds = area.getBounds2D(); final double dx = bounds.getWidth() / w; final double dy = bounds.getHeight() / h; final double tx = -bounds.getMinX(); final double ty = -bounds.getMinY(); final AffineTransform at = AffineTransform.getScaleInstance(1.0 / dx, 1.0 / dy); at.concatenate(AffineTransform.getTranslateInstance(tx, ty)); java.awt.image.BufferedImage image = new java.awt.image.BufferedImage( w, h, java.awt.image.BufferedImage.TYPE_INT_RGB); java.awt.Graphics2D g = image.createGraphics(); g.setPaint(java.awt.Color.WHITE); g.fillRect(0, 0, w, h); g.setPaint(java.awt.Color.BLACK); g.fill(at.createTransformedShape(area)); int num = 0; for (int i = 0; i < w; i++) for (int j = 0; j < h; j++) if ((image.getRGB(i, j) & 0x00ffffff) == 0) num++; return 4 * dx * dy * num; }
public static double intersectionArea(Shape s1, Shape s2) { final int w = 100; final int h = 100; final Area area = new Area(s1); area.intersect(new Area(s2)); Rectangle2D bounds = area.getBounds2D(); final double dx = bounds.getWidth() / w; final double dy = bounds.getHeight() / h; final double tx = -bounds.getMinX(); final double ty = -bounds.getMinY(); final AffineTransform at = AffineTransform.getScaleInstance(1.0 / dx, 1.0 / dy); at.concatenate(AffineTransform.getTranslateInstance(tx, ty)); java.awt.image.BufferedImage image = new java.awt.image.BufferedImage( w, h, java.awt.image.BufferedImage.TYPE_INT_RGB); java.awt.Graphics2D g = image.createGraphics(); g.setPaint(java.awt.Color.WHITE); g.fillRect(0, 0, w, h); g.setPaint(java.awt.Color.BLACK); g.fill(at.createTransformedShape(area)); int num = 0; for (int i = 0; i < w; i++) for (int j = 0; j < h; j++) if ((image.getRGB(i, j) & 0x00ffffff) == 0) num++; return dx * dy * num; }
public String getName() { String result = null; IAnnotationDeclaration d = getManagedBeanDeclaration(); if(d != null) { Object m = d.getMemberValue("name"); if(m != null) { result = m.toString(); } } return result; }
public String getName() { String result = null; IAnnotationDeclaration d = getManagedBeanDeclaration(); if(d != null) { Object m = d.getMemberValue("name"); if(m != null) { result = m.toString(); } if(result == null || result.length() == 0) { result = typeDefinition.getType().getElementName(); if(result.length() > 0) { result = result.substring(0, 1).toLowerCase() + result.substring(1); } } } return result; }
public void applyConfiguration() throws Exception { LOG.debug("Applying configuration"); validateSdkDirectory(); File libOutDir = new File(getServiceInformation().getBaseDirectory(), "lib"); File tempLibDir = new File(getServiceInformation().getBaseDirectory(), "temp"); tempLibDir.mkdir(); String projectName = getDeployPropertiesFromSdkDir().getProperty( SDK41StyleConstants.DeployProperties.PROJECT_NAME); File remoteClientDir = new File(sdkDirectory, "output" + File.separator + projectName + File.separator + "package" + File.separator + "remote-client"); File localClientDir = new File(sdkDirectory, "output" + File.separator + projectName + File.separator + "package" + File.separator + "local-client"); LOG.debug("Creating a jar to contain the remote configuration of the caCORE SDK system"); File remoteConfigDir = new File(remoteClientDir, "conf"); String remoteConfigJarName = projectName + "-remote-config.jar"; File remoteConfigJar = new File(tempLibDir, remoteConfigJarName); JarUtilities.jarDirectory(remoteConfigDir, remoteConfigJar); LOG.debug("Creating a jar to contain the local configuration of the caCORE SDK system"); File localConfigDir = new File(localClientDir, "conf"); String localConfigJarName = projectName + "-local-config.jar"; File localConfigJar = new File(tempLibDir, localConfigJarName); JarUtilities.jarDirectory(localConfigDir, localConfigJar); SharedConfiguration.getInstance().setRemoteConfigJarFile(remoteConfigJar); SharedConfiguration.getInstance().setLocalConfigJarFile(localConfigJar); File globusLocation = new File(System.getenv(GLOBUS_LOCATION_ENV)); File globusLib = new File(globusLocation, "lib"); File[] globusJars = globusLib.listFiles(new FileFilters.JarFileFilter()); Set<String> globusJarNames = new HashSet<String>(); for (File jar : globusJars) { globusJarNames.add(jar.getName()); } Set<String> serviceJarNames = new HashSet<String>(); for (File jar : libOutDir.listFiles(new FileFilters.JarFileFilter())) { serviceJarNames.add(jar.getName()); } final String applicationName = getDeployPropertiesFromSdkDir().getProperty( SDK41StyleConstants.DeployProperties.PROJECT_NAME); LOG.debug("Copying libraries from remote client directory"); File[] remoteLibs = new File(remoteClientDir, "lib").listFiles(new FileFilters.JarFileFilter()); for (File lib : remoteLibs) { String libName = lib.getName(); if (!globusJarNames.contains(libName)) { File libOutput = new File(libOutDir, libName); Utils.copyFile(lib, libOutput); LOG.debug(libName + " copied to the service"); } } LOG.debug("Copying libraries from the local client directory"); File localLibDir = new File(localClientDir, "lib"); File[] localLibs = localLibDir.listFiles(); for (File lib : localLibs) { String name = lib.getName(); boolean ok = name.equals(applicationName + "-orm.jar") || name.equals("sdk-core.jar") || name.startsWith("caGrid-sdkQuery4-") || name.equals("dom4j-1.4.jar"); if (ok && serviceJarNames.contains(name)) { ok = false; } if (ok && name.startsWith("caGrid-") && name.endsWith("-1.2.jar")) { String trimmedName = name.substring(name.length() - 8); for (String inService : serviceJarNames) { if (inService.startsWith(trimmedName)) { ok = false; break; } } } if (ok && !globusJarNames.contains(name)) { File libOutput = new File(libOutDir, name); Utils.copyFile(lib, libOutput); LOG.debug(name + " copied to the service"); } } setCql1ProcessorProperty( SDK41QueryProcessor.PROPERTY_APPLICATION_NAME, applicationName, false); setCql2ProcessorProperty( SDK41CQL2QueryProcessor.PROPERTY_APPLICATION_NAME, applicationName, false); try { LOG.debug("Copying castor marshalling and unmarshalling files"); File marshallingMappingFile = new File(remoteConfigDir, CastorMappingUtil.CASTOR_MARSHALLING_MAPPING_FILE); File unmarshallingMappingFile = new File(remoteConfigDir, CastorMappingUtil.CASTOR_UNMARSHALLING_MAPPING_FILE); String marshallOut = CastorMappingUtil.getMarshallingCastorMappingFileName(getServiceInformation()); String unmarshallOut = CastorMappingUtil.getUnmarshallingCastorMappingFileName(getServiceInformation()); Utils.copyFile(marshallingMappingFile, new File(marshallOut)); Utils.copyFile(unmarshallingMappingFile, new File(unmarshallOut)); } catch (IOException ex) { ex.printStackTrace(); CompositeErrorDialog.showErrorDialog("Error copying castor mapping files", ex.getMessage(), ex); } SharedConfiguration.getInstance().setSdkDirectory(getSdkDirectory()); SharedConfiguration.getInstance().setServiceInfo(getServiceInformation()); SharedConfiguration.getInstance().setSdkDeployProperties(getDeployPropertiesFromSdkDir()); }
public void applyConfiguration() throws Exception { LOG.debug("Applying configuration"); validateSdkDirectory(); File libOutDir = new File(getServiceInformation().getBaseDirectory(), "lib"); File tempLibDir = new File(getServiceInformation().getBaseDirectory(), "temp"); tempLibDir.mkdir(); String projectName = getDeployPropertiesFromSdkDir().getProperty( SDK41StyleConstants.DeployProperties.PROJECT_NAME); File remoteClientDir = new File(sdkDirectory, "output" + File.separator + projectName + File.separator + "package" + File.separator + "remote-client"); File localClientDir = new File(sdkDirectory, "output" + File.separator + projectName + File.separator + "package" + File.separator + "local-client"); LOG.debug("Creating a jar to contain the remote configuration of the caCORE SDK system"); File remoteConfigDir = new File(remoteClientDir, "conf"); String remoteConfigJarName = projectName + "-remote-config.jar"; File remoteConfigJar = new File(tempLibDir, remoteConfigJarName); JarUtilities.jarDirectory(remoteConfigDir, remoteConfigJar); LOG.debug("Creating a jar to contain the local configuration of the caCORE SDK system"); File localConfigDir = new File(localClientDir, "conf"); String localConfigJarName = projectName + "-local-config.jar"; File localConfigJar = new File(tempLibDir, localConfigJarName); JarUtilities.jarDirectory(localConfigDir, localConfigJar); SharedConfiguration.getInstance().setRemoteConfigJarFile(remoteConfigJar); SharedConfiguration.getInstance().setLocalConfigJarFile(localConfigJar); File globusLocation = new File(System.getenv(GLOBUS_LOCATION_ENV)); File globusLib = new File(globusLocation, "lib"); File[] globusJars = globusLib.listFiles(new FileFilters.JarFileFilter()); Set<String> globusJarNames = new HashSet<String>(); for (File jar : globusJars) { globusJarNames.add(jar.getName()); } Set<String> serviceJarNames = new HashSet<String>(); for (File jar : libOutDir.listFiles(new FileFilters.JarFileFilter())) { serviceJarNames.add(jar.getName()); } final String applicationName = getDeployPropertiesFromSdkDir().getProperty( SDK41StyleConstants.DeployProperties.PROJECT_NAME); LOG.debug("Copying libraries from remote client directory"); File[] remoteLibs = new File(remoteClientDir, "lib").listFiles(new FileFilters.JarFileFilter()); for (File lib : remoteLibs) { String libName = lib.getName(); if (!globusJarNames.contains(libName) && !libName.startsWith("caGrid-CQL-cql.1.0-")) { File libOutput = new File(libOutDir, libName); Utils.copyFile(lib, libOutput); LOG.debug(libName + " copied to the service"); } } LOG.debug("Copying libraries from the local client directory"); File localLibDir = new File(localClientDir, "lib"); File[] localLibs = localLibDir.listFiles(); for (File lib : localLibs) { String name = lib.getName(); boolean ok = true; ok = !(name.equals("axis.jar") || name.startsWith("commons-collections") || name.startsWith("commons-logging") || name.startsWith("commons-discovery") || name.startsWith("log4j")); if (ok && serviceJarNames.contains(name)) { ok = false; } if (ok && name.startsWith("caGrid-") && name.endsWith("-1.2.jar")) { if (!name.startsWith("caGrid-sdkQuery4-")) { ok = false; } } if (ok && !globusJarNames.contains(name)) { File libOutput = new File(libOutDir, name); Utils.copyFile(lib, libOutput); LOG.debug(name + " copied to the service"); } } setCql1ProcessorProperty( SDK41QueryProcessor.PROPERTY_APPLICATION_NAME, applicationName, false); setCql2ProcessorProperty( SDK41CQL2QueryProcessor.PROPERTY_APPLICATION_NAME, applicationName, false); try { LOG.debug("Copying castor marshalling and unmarshalling files"); File marshallingMappingFile = new File(remoteConfigDir, CastorMappingUtil.CASTOR_MARSHALLING_MAPPING_FILE); File unmarshallingMappingFile = new File(remoteConfigDir, CastorMappingUtil.CASTOR_UNMARSHALLING_MAPPING_FILE); String marshallOut = CastorMappingUtil.getMarshallingCastorMappingFileName(getServiceInformation()); String unmarshallOut = CastorMappingUtil.getUnmarshallingCastorMappingFileName(getServiceInformation()); Utils.copyFile(marshallingMappingFile, new File(marshallOut)); Utils.copyFile(unmarshallingMappingFile, new File(unmarshallOut)); } catch (IOException ex) { ex.printStackTrace(); CompositeErrorDialog.showErrorDialog("Error copying castor mapping files", ex.getMessage(), ex); } SharedConfiguration.getInstance().setSdkDirectory(getSdkDirectory()); SharedConfiguration.getInstance().setServiceInfo(getServiceInformation()); SharedConfiguration.getInstance().setSdkDeployProperties(getDeployPropertiesFromSdkDir()); }
public ModuleMap read(File file, IProgressMonitor monitor) throws PersistenceException { Map<String, Integer> itemNameToRowMapping = new TreeMap<String, Integer>(); if (isItemNamesFilterEnabled()) { String[] itemNames = getItemNames(); for (int i = 0; i < itemNames.length; i++) itemNameToRowMapping.put(itemNames[i], i); } final Map<String, Set<Integer>> moduleItemsMap = new HashMap<String, Set<Integer>>(); try { monitor.begin("Reading modules ...", 1); Reader reader = PersistenceUtils.openReader(file); CSVParser parser = new CSVParser(reader, CSVStrategies.TSV); readModuleMappings(parser, isItemNamesFilterEnabled(), itemNameToRowMapping, moduleItemsMap); monitor.end(); } catch (Exception ex) { throw new PersistenceException(ex); } monitor.begin("Filtering modules ...", 1); int minSize = getMinSize(); int maxSize = getMaxSize(); String[] itemNames = new String[itemNameToRowMapping.size()]; for (Map.Entry<String, Integer> entry : itemNameToRowMapping.entrySet()) { itemNames[entry.getValue()] = entry.getKey(); } BitSet used = new BitSet(itemNames.length); int lastIndex = 0; int[] indexMap = new int[itemNames.length]; List<String> moduleNames = new ArrayList<String>(); List<int[]> modulesItemIndices = new ArrayList<int[]>(); Iterator<Entry<String, Set<Integer>>> it = moduleItemsMap.entrySet().iterator(); while (it.hasNext()) { Entry<String, Set<Integer>> entry = it.next(); Set<Integer> indices = entry.getValue(); if (indices.size() >= minSize && indices.size() <= maxSize) { moduleNames.add(entry.getKey()); int[] remapedIndices = new int[indices.size()]; Iterator<Integer> iit = indices.iterator(); for (int i = 0; i < indices.size(); i++) { int index = iit.next(); if (!used.get(index)) { used.set(index); indexMap[index] = lastIndex++; } remapedIndices[i] = indexMap[index]; } modulesItemIndices.add(remapedIndices); } else it.remove(); } String[] finalItemNames = new String[lastIndex]; for (int i = 0; i < itemNames.length; i++) if (used.get(i)) finalItemNames[indexMap[i]] = itemNames[i]; monitor.end(); ModuleMap mmap = new ModuleMap(); mmap.setItemNames(finalItemNames); mmap.setModuleNames(moduleNames.toArray(new String[moduleNames.size()])); mmap.setAllItemIndices(modulesItemIndices.toArray(new int[modulesItemIndices.size()][])); return mmap; }
public ModuleMap read(File file, IProgressMonitor monitor) throws PersistenceException { Map<String, Integer> itemNameToRowMapping = new TreeMap<String, Integer>(); if (isItemNamesFilterEnabled()) { String[] itemNames = getItemNames(); for (int i = 0; i < itemNames.length; i++) { if (itemNameToRowMapping.containsKey(itemNames[i])) throw new PersistenceException("Modules not mappable to heatmap due to duplicated row: " + itemNames[i]); else itemNameToRowMapping.put(itemNames[i], i); } } final Map<String, Set<Integer>> moduleItemsMap = new HashMap<String, Set<Integer>>(); try { monitor.begin("Reading modules ...", 1); Reader reader = PersistenceUtils.openReader(file); CSVParser parser = new CSVParser(reader, CSVStrategies.TSV); readModuleMappings(parser, isItemNamesFilterEnabled(), itemNameToRowMapping, moduleItemsMap); monitor.end(); } catch (Exception ex) { throw new PersistenceException(ex); } monitor.begin("Filtering modules ...", 1); int minSize = getMinSize(); int maxSize = getMaxSize(); String[] itemNames = new String[itemNameToRowMapping.size()]; for (Map.Entry<String, Integer> entry : itemNameToRowMapping.entrySet()) { itemNames[entry.getValue()] = entry.getKey(); } BitSet used = new BitSet(itemNames.length); int lastIndex = 0; int[] indexMap = new int[itemNames.length]; List<String> moduleNames = new ArrayList<String>(); List<int[]> modulesItemIndices = new ArrayList<int[]>(); Iterator<Entry<String, Set<Integer>>> it = moduleItemsMap.entrySet().iterator(); while (it.hasNext()) { Entry<String, Set<Integer>> entry = it.next(); Set<Integer> indices = entry.getValue(); if (indices.size() >= minSize && indices.size() <= maxSize) { moduleNames.add(entry.getKey()); int[] remapedIndices = new int[indices.size()]; Iterator<Integer> iit = indices.iterator(); for (int i = 0; i < indices.size(); i++) { int index = iit.next(); if (!used.get(index)) { used.set(index); indexMap[index] = lastIndex++; } remapedIndices[i] = indexMap[index]; } modulesItemIndices.add(remapedIndices); } else it.remove(); } String[] finalItemNames = new String[lastIndex]; for (int i = 0; i < itemNames.length; i++) if (used.get(i)) finalItemNames[indexMap[i]] = itemNames[i]; monitor.end(); ModuleMap mmap = new ModuleMap(); mmap.setItemNames(finalItemNames); mmap.setModuleNames(moduleNames.toArray(new String[moduleNames.size()])); mmap.setAllItemIndices(modulesItemIndices.toArray(new int[modulesItemIndices.size()][])); return mmap; }
public static Map<String, BigDecimal> computeForecastByOpportunities(BigDecimal quotaAmount, String organizationPartyId, String internalPartyId, String currencyUomId, String customTimePeriodId, GenericDelegator delegator) throws GenericEntityException { BigDecimal closedAmount = BigDecimal.ZERO; BigDecimal bestCaseAmount = BigDecimal.ZERO; BigDecimal forecastAmount = BigDecimal.ZERO; BigDecimal percentOfQuotaForecast = BigDecimal.ZERO; BigDecimal percentOfQuotaClosed = BigDecimal.ZERO; BigDecimal minimumProbability = BigDecimal.ZERO; try { minimumProbability = new BigDecimal(UtilProperties.getPropertyValue("crmsfa.properties", "crmsfa.forecast.minProbability")); } catch (NumberFormatException ne) { Debug.logWarning("Failed to parse property \"crmsfa.forecast.minProbability\": " + ne.getMessage() + "\nSetting minimum probability to 0.0.", MODULE); } EntityListIterator opportunitiesELI = UtilOpportunity.getOpportunitiesForInternalParty(organizationPartyId, internalPartyId, customTimePeriodId, null, null, delegator); List<GenericValue> opportunities = opportunitiesELI.getCompleteList(); if (opportunities.size() == 0) { Debug.logWarning("no opportunities were found for the internalParty [" + internalPartyId + "] and organizationParty [" + organizationPartyId + "] over time period id [" + customTimePeriodId + "]", MODULE); } for (Iterator<GenericValue> iter = opportunities.iterator(); iter.hasNext();) { GenericValue opportunity = iter.next(); if (Debug.verboseOn()) { Debug.logVerbose("for timePeriod [" + customTimePeriodId + "] and party [" + internalPartyId + "]. Now working with opportunity: " + opportunity, MODULE); } BigDecimal amount = opportunity.getBigDecimal("estimatedAmount"); BigDecimal probability = opportunity.getBigDecimal("estimatedProbability"); if (amount == null) { continue; } String oppCurrencyUomId = opportunity.getString("currencyUomId"); if ((oppCurrencyUomId == null) || !oppCurrencyUomId.equals(currencyUomId)) { Debug.logWarning("Forecast currency unit of measure [" + currencyUomId + "] is different from opportunity ID [" + opportunity.getString("salesOpportunityId") + "] currency which is [" + oppCurrencyUomId + "]. However, conversion is not currently implemented. Forecast will be incorrect.", MODULE); } if (opportunity.getString("opportunityStageId").equals("SOSTG_CLOSED")) { closedAmount = closedAmount.add(amount).setScale(BD_FORECAST_DECIMALS, BD_FORECAST_ROUNDING); } else { bestCaseAmount = bestCaseAmount.add(amount).setScale(BD_FORECAST_DECIMALS, BD_FORECAST_ROUNDING); if ((probability != null) && (probability.compareTo(minimumProbability) >= 0)) { forecastAmount = forecastAmount.add(probability.multiply(amount)).setScale(BD_FORECAST_DECIMALS, BD_FORECAST_ROUNDING); } } if (Debug.verboseOn()) { Debug.logVerbose("Now for timePeriod [" + customTimePeriodId + "] after opportunity [" + opportunity.getString("opportunityId") + "] " + "closedAmouont = [" + closedAmount + "] bestCaseAmount = [" + bestCaseAmount + "] forecastAmount = [" + forecastAmount + "]" , MODULE); } } bestCaseAmount = bestCaseAmount.add(closedAmount).setScale(BD_FORECAST_DECIMALS, BD_FORECAST_ROUNDING); forecastAmount = forecastAmount.add(closedAmount).setScale(BD_FORECAST_DECIMALS, BD_FORECAST_ROUNDING); if (quotaAmount != null && quotaAmount.signum() > 0) { percentOfQuotaForecast = forecastAmount.divide(quotaAmount, BD_FORECAST_PERCENT_DECIMALS, BD_FORECAST_PERCENT_ROUNDING); percentOfQuotaClosed = closedAmount.divide(quotaAmount, BD_FORECAST_PERCENT_DECIMALS, BD_FORECAST_PERCENT_ROUNDING); } return UtilMisc.toMap("closedAmount", closedAmount, "bestCaseAmount", bestCaseAmount, "forecastAmount", forecastAmount, "percentOfQuotaForecast", percentOfQuotaForecast, "percentOfQuotaClosed", percentOfQuotaClosed); }
public static Map<String, BigDecimal> computeForecastByOpportunities(BigDecimal quotaAmount, String organizationPartyId, String internalPartyId, String currencyUomId, String customTimePeriodId, GenericDelegator delegator) throws GenericEntityException { BigDecimal closedAmount = BigDecimal.ZERO; BigDecimal bestCaseAmount = BigDecimal.ZERO; BigDecimal forecastAmount = BigDecimal.ZERO; BigDecimal percentOfQuotaForecast = BigDecimal.ZERO; BigDecimal percentOfQuotaClosed = BigDecimal.ZERO; BigDecimal minimumProbability = BigDecimal.ZERO; try { minimumProbability = new BigDecimal(UtilProperties.getPropertyValue("crmsfa.properties", "crmsfa.forecast.minProbability")); } catch (NumberFormatException ne) { Debug.logWarning("Failed to parse property \"crmsfa.forecast.minProbability\": " + ne.getMessage() + "\nSetting minimum probability to 0.0.", MODULE); } EntityListIterator opportunitiesELI = UtilOpportunity.getOpportunitiesForInternalParty(organizationPartyId, internalPartyId, customTimePeriodId, null, null, delegator); List<GenericValue> opportunities = opportunitiesELI.getCompleteList(); if (opportunities.size() == 0) { Debug.logWarning("no opportunities were found for the internalParty [" + internalPartyId + "] and organizationParty [" + organizationPartyId + "] over time period id [" + customTimePeriodId + "]", MODULE); } for (Iterator<GenericValue> iter = opportunities.iterator(); iter.hasNext();) { GenericValue opportunity = iter.next(); if (Debug.verboseOn()) { Debug.logVerbose("for timePeriod [" + customTimePeriodId + "] and party [" + internalPartyId + "]. Now working with opportunity: " + opportunity, MODULE); } BigDecimal amount = opportunity.getBigDecimal("estimatedAmount"); BigDecimal probability = opportunity.getBigDecimal("estimatedProbability"); if (amount == null) { continue; } String oppCurrencyUomId = opportunity.getString("currencyUomId"); if ((oppCurrencyUomId == null) || !oppCurrencyUomId.equals(currencyUomId)) { Debug.logWarning("Forecast currency unit of measure [" + currencyUomId + "] is different from opportunity ID [" + opportunity.getString("salesOpportunityId") + "] currency which is [" + oppCurrencyUomId + "]. However, conversion is not currently implemented. Forecast will be incorrect.", MODULE); } if (opportunity.getString("opportunityStageId").equals("SOSTG_CLOSED")) { closedAmount = closedAmount.add(amount).setScale(BD_FORECAST_DECIMALS, BD_FORECAST_ROUNDING); } else { bestCaseAmount = bestCaseAmount.add(amount).setScale(BD_FORECAST_DECIMALS, BD_FORECAST_ROUNDING); if ((probability != null) && (probability.compareTo(minimumProbability) >= 0)) { forecastAmount = forecastAmount.add(probability.multiply(amount)).setScale(BD_FORECAST_DECIMALS, BD_FORECAST_ROUNDING); } } if (Debug.verboseOn()) { Debug.logVerbose("Now for timePeriod [" + customTimePeriodId + "] after opportunity [" + opportunity.getString("salesOpportunityId") + "] " + "closedAmouont = [" + closedAmount + "] bestCaseAmount = [" + bestCaseAmount + "] forecastAmount = [" + forecastAmount + "]" , MODULE); } } bestCaseAmount = bestCaseAmount.add(closedAmount).setScale(BD_FORECAST_DECIMALS, BD_FORECAST_ROUNDING); forecastAmount = forecastAmount.add(closedAmount).setScale(BD_FORECAST_DECIMALS, BD_FORECAST_ROUNDING); if (quotaAmount != null && quotaAmount.signum() > 0) { percentOfQuotaForecast = forecastAmount.divide(quotaAmount, BD_FORECAST_PERCENT_DECIMALS, BD_FORECAST_PERCENT_ROUNDING); percentOfQuotaClosed = closedAmount.divide(quotaAmount, BD_FORECAST_PERCENT_DECIMALS, BD_FORECAST_PERCENT_ROUNDING); } return UtilMisc.toMap("closedAmount", closedAmount, "bestCaseAmount", bestCaseAmount, "forecastAmount", forecastAmount, "percentOfQuotaForecast", percentOfQuotaForecast, "percentOfQuotaClosed", percentOfQuotaClosed); }
public static void main(String[] args) throws IOException, TasteException { DataModel dataModel = new GroupLensDataModel(new File("data/sample100/ratings.dat")); Evaluator evaluator = new Evaluator(dataModel); for(Similarity similarity : Similarity.values()) { for(int K = 7; K >= 1; K -= 1) { evaluator.add(new KNN(similarity, K)); } for(double T = 0.70; T <= 1.00; T += 0.05) { evaluator.add(new Threshold(similarity, T)); } } evaluator.add(new SVD()); ArrayList<EvaluationResult> results = evaluator.evaluateAll(); Collections.sort(results, new Comparator<EvaluationResult>() { public int compare(EvaluationResult a, EvaluationResult b) { return (a.RMSE > b.RMSE) ? -1 : (a.RMSE < b.RMSE) ? 1 : 0; } }); for(EvaluationResult res : results) { System.out.println(res); } }
public static void main(String[] args) throws IOException, TasteException { DataModel dataModel = new GroupLensDataModel(new File("datasets/sample100/ratings.dat.gz")); Evaluator evaluator = new Evaluator(dataModel); for(Similarity similarity : Similarity.values()) { for(int K = 7; K >= 1; K -= 1) { evaluator.add(new KNN(similarity, K)); } for(double T = 0.70; T <= 1.00; T += 0.05) { evaluator.add(new Threshold(similarity, T)); } } evaluator.add(new SVD()); ArrayList<EvaluationResult> results = evaluator.evaluateAll(); Collections.sort(results, new Comparator<EvaluationResult>() { public int compare(EvaluationResult a, EvaluationResult b) { return (a.RMSE > b.RMSE) ? -1 : (a.RMSE < b.RMSE) ? 1 : 0; } }); for(EvaluationResult res : results) { System.out.println(res); } }
protected TemplateContextType getContextType(ITextViewer viewer, IRegion region) { IDocument doc = viewer.getDocument(); try { IRegion line = doc.getLineInformationOfOffset(region.getOffset() + region.getLength()); int len = region.getOffset() + region.getLength() - line.getOffset(); String s = doc.get(line.getOffset(), len); int spaceIndex = s.lastIndexOf(' '); if (spaceIndex != -1) { s = s.substring(spaceIndex); } if (s.indexOf('.') == -1 && s.indexOf(':') == -1) { return RubyTemplateAccess .getInstance() .getContextTypeRegistry() .getContextType( RubyUniversalTemplateContextType.CONTEXT_TYPE_ID); } } catch (BadLocationException e) { e.printStackTrace(); } return null; }
protected TemplateContextType getContextType(ITextViewer viewer, IRegion region) { IDocument doc = viewer.getDocument(); try { IRegion line = doc.getLineInformationOfOffset(region.getOffset() + region.getLength()); int len = region.getOffset() + region.getLength() - line.getOffset(); String s = doc.get(line.getOffset(), len); int spaceIndex = s.lastIndexOf(' '); if (spaceIndex != -1) { s = s.substring(spaceIndex); } if (s.indexOf('.') == -1 && s.indexOf(':') == -1 && s.indexOf('@') == -1 && s.indexOf('$') == -1) { return RubyTemplateAccess .getInstance() .getContextTypeRegistry() .getContextType( RubyUniversalTemplateContextType.CONTEXT_TYPE_ID); } } catch (BadLocationException e) { e.printStackTrace(); } return null; }
protected final boolean setGLFunctionAvailability(boolean force, int major, int minor, int ctxProfileBits, boolean strictMatch) { if(null!=this.gl && null!=glProcAddressTable && !force) { return true; } if ( 0 < major && !GLContext.isValidGLVersion(major, minor) ) { throw new GLException("Invalid GL Version Request "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)); } if(null==this.gl || !verifyInstance(gl.getGLProfile(), "Impl", this.gl)) { setGL( createGL( getGLDrawable().getGLProfile() ) ); } updateGLXProcAddressTable(); final AbstractGraphicsConfiguration aconfig = drawable.getNativeSurface().getGraphicsConfiguration(); final AbstractGraphicsDevice adevice = aconfig.getScreen().getDevice(); { final boolean initGLRendererAndGLVersionStringsOK = initGLRendererAndGLVersionStrings(); if( !initGLRendererAndGLVersionStringsOK ) { final String errMsg = "Intialization of GL renderer strings failed. "+adevice+" - "+GLContext.getGLVersion(major, minor, ctxProfileBits, null); if( strictMatch ) { if(DEBUG) { System.err.println("Warning: setGLFunctionAvailability: "+errMsg); } return false; } else { throw new GLException(errMsg); } } else if(DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail: Given "+adevice+" - "+GLContext.getGLVersion(major, minor, ctxProfileBits, glVersion)); } } if (DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail: Pre version verification - expected "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)+", strictMatch "+strictMatch); } boolean versionValidated = false; boolean versionGL3IntFailed = false; { final int[] glIntMajor = new int[] { 0 }, glIntMinor = new int[] { 0 }; final boolean getGLIntVersionOK = getGLIntVersion(glIntMajor, glIntMinor, ctxProfileBits); if( !getGLIntVersionOK ) { final String errMsg = "Fetching GL Integer Version failed. "+adevice+" - "+GLContext.getGLVersion(major, minor, ctxProfileBits, null); if( strictMatch ) { if(DEBUG) { System.err.println("Warning: setGLFunctionAvailability: "+errMsg); } return false; } else { throw new GLException(errMsg); } } if (DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail: version verification (Int): "+glVersion+", "+glIntMajor[0]+"."+glIntMinor[0]); } if ( GLContext.isValidGLVersion(glIntMajor[0], glIntMinor[0]) ) { if( glIntMajor[0]<major || ( glIntMajor[0]==major && glIntMinor[0]<minor ) || 0 == major ) { if( strictMatch && 0 < major ) { if(DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.X: FAIL, GL version mismatch (Int): "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)+" -> "+glVersion+", "+glIntMajor[0]+"."+glIntMinor[0]); } return false; } major = glIntMajor[0]; minor = glIntMinor[0]; } versionValidated = true; } else { versionGL3IntFailed = true; } } if( !versionValidated ) { final VersionNumber setGLVersionNumber = new VersionNumber(major, minor, 0); final VersionNumber strGLVersionNumber = getGLVersionNumber(ctxProfileBits, glVersion); if (DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail: version verification (String): "+glVersion+", "+strGLVersionNumber); } if( null != strGLVersionNumber ) { if( strGLVersionNumber.compareTo(setGLVersionNumber) < 0 || 0 == major ) { if( strictMatch && 0 < major ) { if(DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.X: FAIL, GL version mismatch (String): "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)+" -> "+glVersion+", "+strGLVersionNumber); } return false; } major = strGLVersionNumber.getMajor(); minor = strGLVersionNumber.getMinor(); } if( strictMatch && versionGL3IntFailed && major >= 3 ) { if(DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.X: FAIL, GL3 version Int failed, String: "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)+" -> "+glVersion+", "+strGLVersionNumber); } return false; } versionValidated = true; } } if( strictMatch && !versionValidated && 0 < major ) { if(DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.X: FAIL, No GL version validation possible: "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)+" -> "+glVersion); } return false; } if (DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail: post version verification "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)+", strictMatch "+strictMatch+", versionValidated "+versionValidated+", versionGL3IntFailed "+versionGL3IntFailed); } if( 2 > major ) { ctxProfileBits &= ~GLContext.CTX_IMPL_ES2_COMPAT; } setRendererQuirks(major, minor, ctxProfileBits); if( strictMatch && glRendererQuirks.exist(GLRendererQuirks.GLNonCompliant) ) { if(DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.X: FAIL, GL is not compliant: "+GLContext.getGLVersion(major, minor, ctxProfileBits, glVersion)+", "+glRenderer); } return false; } if(!isCurrentContextHardwareRasterizer()) { ctxProfileBits |= GLContext.CTX_IMPL_ACCEL_SOFT; } contextFQN = getContextFQN(adevice, major, minor, ctxProfileBits); if (DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.0 validated FQN: "+contextFQN+" - "+GLContext.getGLVersion(major, minor, ctxProfileBits, glVersion)); } ProcAddressTable table = null; synchronized(mappedContextTypeObjectLock) { table = mappedGLProcAddress.get( contextFQN ); if(null != table && !verifyInstance(gl.getGLProfile(), "ProcAddressTable", table)) { throw new InternalError("GLContext GL ProcAddressTable mapped key("+contextFQN+" - " + GLContext.getGLVersion(major, minor, ctxProfileBits, null)+ ") -> "+ table.getClass().getName()+" not matching "+gl.getGLProfile().getGLImplBaseClassName()); } } if(null != table) { glProcAddressTable = table; if(DEBUG) { System.err.println(getThreadName() + ": GLContext GL ProcAddressTable reusing key("+contextFQN+") -> "+toHexString(table.hashCode())); } } else { glProcAddressTable = (ProcAddressTable) createInstance(gl.getGLProfile(), "ProcAddressTable", new Class[] { FunctionAddressResolver.class } , new Object[] { new GLProcAddressResolver() } ); resetProcAddressTable(getGLProcAddressTable()); synchronized(mappedContextTypeObjectLock) { mappedGLProcAddress.put(contextFQN, getGLProcAddressTable()); if(DEBUG) { System.err.println(getThreadName() + ": GLContext GL ProcAddressTable mapping key("+contextFQN+") -> "+toHexString(getGLProcAddressTable().hashCode())); } } } ExtensionAvailabilityCache eCache; synchronized(mappedContextTypeObjectLock) { eCache = mappedExtensionAvailabilityCache.get( contextFQN ); } if(null != eCache) { extensionAvailability = eCache; if(DEBUG) { System.err.println(getThreadName() + ": GLContext GL ExtensionAvailabilityCache reusing key("+contextFQN+") -> "+toHexString(eCache.hashCode()) + " - entries: "+eCache.getTotalExtensionCount()); } } else { extensionAvailability = new ExtensionAvailabilityCache(); setContextVersion(major, minor, ctxProfileBits, false); extensionAvailability.reset(this); synchronized(mappedContextTypeObjectLock) { mappedExtensionAvailabilityCache.put(contextFQN, extensionAvailability); if(DEBUG) { System.err.println(getThreadName() + ": GLContext GL ExtensionAvailabilityCache mapping key("+contextFQN+") -> "+toHexString(extensionAvailability.hashCode()) + " - entries: "+extensionAvailability.getTotalExtensionCount()); } } } if( ( 0 != ( CTX_PROFILE_ES & ctxProfileBits ) && major >= 2 ) || isExtensionAvailable(GLExtensions.ARB_ES2_compatibility) ) { ctxProfileBits |= CTX_IMPL_ES2_COMPAT; ctxProfileBits |= CTX_IMPL_FBO; } else if( hasFBOImpl(major, ctxProfileBits, extensionAvailability) ) { ctxProfileBits |= CTX_IMPL_FBO; } if(FORCE_NO_FBO_SUPPORT) { ctxProfileBits &= ~CTX_IMPL_FBO ; } setContextVersion(major, minor, ctxProfileBits, true); setDefaultSwapInterval(); final int glErrX = gl.glGetError(); if(DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.X: OK "+contextFQN+" - "+GLContext.getGLVersion(ctxVersion.getMajor(), ctxVersion.getMinor(), ctxOptions, null)+" - glErr "+toHexString(glErrX)); } return true; }
protected final boolean setGLFunctionAvailability(boolean force, int major, int minor, int ctxProfileBits, boolean strictMatch) { if(null!=this.gl && null!=glProcAddressTable && !force) { return true; } if ( 0 < major && !GLContext.isValidGLVersion(major, minor) ) { throw new GLException("Invalid GL Version Request "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)); } if(null==this.gl || !verifyInstance(gl.getGLProfile(), "Impl", this.gl)) { setGL( createGL( getGLDrawable().getGLProfile() ) ); } updateGLXProcAddressTable(); final AbstractGraphicsConfiguration aconfig = drawable.getNativeSurface().getGraphicsConfiguration(); final AbstractGraphicsDevice adevice = aconfig.getScreen().getDevice(); { final boolean initGLRendererAndGLVersionStringsOK = initGLRendererAndGLVersionStrings(); if( !initGLRendererAndGLVersionStringsOK ) { final String errMsg = "Intialization of GL renderer strings failed. "+adevice+" - "+GLContext.getGLVersion(major, minor, ctxProfileBits, null); if( strictMatch ) { if(DEBUG) { System.err.println("Warning: setGLFunctionAvailability: "+errMsg); } return false; } else { throw new GLException(errMsg); } } else if(DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail: Given "+adevice+" - "+GLContext.getGLVersion(major, minor, ctxProfileBits, glVersion)); } } if (DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail: Pre version verification - expected "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)+", strictMatch "+strictMatch); } boolean versionValidated = false; boolean versionGL3IntFailed = false; { final int[] glIntMajor = new int[] { 0 }, glIntMinor = new int[] { 0 }; final boolean getGLIntVersionOK = getGLIntVersion(glIntMajor, glIntMinor, ctxProfileBits); if( !getGLIntVersionOK ) { final String errMsg = "Fetching GL Integer Version failed. "+adevice+" - "+GLContext.getGLVersion(major, minor, ctxProfileBits, null); if( strictMatch ) { if(DEBUG) { System.err.println("Warning: setGLFunctionAvailability: "+errMsg); } return false; } else { throw new GLException(errMsg); } } if (DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail: version verification (Int): "+glVersion+", "+glIntMajor[0]+"."+glIntMinor[0]); } if ( GLContext.isValidGLVersion(glIntMajor[0], glIntMinor[0]) ) { if( glIntMajor[0]<major || ( glIntMajor[0]==major && glIntMinor[0]<minor ) || 0 == major ) { if( strictMatch && 2 < major ) { if(DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.X: FAIL, GL version mismatch (Int): "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)+" -> "+glVersion+", "+glIntMajor[0]+"."+glIntMinor[0]); } return false; } major = glIntMajor[0]; minor = glIntMinor[0]; } versionValidated = true; } else { versionGL3IntFailed = true; } } if( !versionValidated ) { final VersionNumber setGLVersionNumber = new VersionNumber(major, minor, 0); final VersionNumber strGLVersionNumber = getGLVersionNumber(ctxProfileBits, glVersion); if (DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail: version verification (String): "+glVersion+", "+strGLVersionNumber); } if( null != strGLVersionNumber ) { if( strGLVersionNumber.compareTo(setGLVersionNumber) < 0 || 0 == major ) { if( strictMatch && 2 < major ) { if(DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.X: FAIL, GL version mismatch (String): "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)+" -> "+glVersion+", "+strGLVersionNumber); } return false; } major = strGLVersionNumber.getMajor(); minor = strGLVersionNumber.getMinor(); } if( strictMatch && versionGL3IntFailed && major >= 3 ) { if(DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.X: FAIL, GL3 version Int failed, String: "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)+" -> "+glVersion+", "+strGLVersionNumber); } return false; } versionValidated = true; } } if( strictMatch && !versionValidated && 0 < major ) { if(DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.X: FAIL, No GL version validation possible: "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)+" -> "+glVersion); } return false; } if (DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail: post version verification "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)+", strictMatch "+strictMatch+", versionValidated "+versionValidated+", versionGL3IntFailed "+versionGL3IntFailed); } if( 2 > major ) { ctxProfileBits &= ~GLContext.CTX_IMPL_ES2_COMPAT; } setRendererQuirks(major, minor, ctxProfileBits); if( strictMatch && glRendererQuirks.exist(GLRendererQuirks.GLNonCompliant) ) { if(DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.X: FAIL, GL is not compliant: "+GLContext.getGLVersion(major, minor, ctxProfileBits, glVersion)+", "+glRenderer); } return false; } if(!isCurrentContextHardwareRasterizer()) { ctxProfileBits |= GLContext.CTX_IMPL_ACCEL_SOFT; } contextFQN = getContextFQN(adevice, major, minor, ctxProfileBits); if (DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.0 validated FQN: "+contextFQN+" - "+GLContext.getGLVersion(major, minor, ctxProfileBits, glVersion)); } ProcAddressTable table = null; synchronized(mappedContextTypeObjectLock) { table = mappedGLProcAddress.get( contextFQN ); if(null != table && !verifyInstance(gl.getGLProfile(), "ProcAddressTable", table)) { throw new InternalError("GLContext GL ProcAddressTable mapped key("+contextFQN+" - " + GLContext.getGLVersion(major, minor, ctxProfileBits, null)+ ") -> "+ table.getClass().getName()+" not matching "+gl.getGLProfile().getGLImplBaseClassName()); } } if(null != table) { glProcAddressTable = table; if(DEBUG) { System.err.println(getThreadName() + ": GLContext GL ProcAddressTable reusing key("+contextFQN+") -> "+toHexString(table.hashCode())); } } else { glProcAddressTable = (ProcAddressTable) createInstance(gl.getGLProfile(), "ProcAddressTable", new Class[] { FunctionAddressResolver.class } , new Object[] { new GLProcAddressResolver() } ); resetProcAddressTable(getGLProcAddressTable()); synchronized(mappedContextTypeObjectLock) { mappedGLProcAddress.put(contextFQN, getGLProcAddressTable()); if(DEBUG) { System.err.println(getThreadName() + ": GLContext GL ProcAddressTable mapping key("+contextFQN+") -> "+toHexString(getGLProcAddressTable().hashCode())); } } } ExtensionAvailabilityCache eCache; synchronized(mappedContextTypeObjectLock) { eCache = mappedExtensionAvailabilityCache.get( contextFQN ); } if(null != eCache) { extensionAvailability = eCache; if(DEBUG) { System.err.println(getThreadName() + ": GLContext GL ExtensionAvailabilityCache reusing key("+contextFQN+") -> "+toHexString(eCache.hashCode()) + " - entries: "+eCache.getTotalExtensionCount()); } } else { extensionAvailability = new ExtensionAvailabilityCache(); setContextVersion(major, minor, ctxProfileBits, false); extensionAvailability.reset(this); synchronized(mappedContextTypeObjectLock) { mappedExtensionAvailabilityCache.put(contextFQN, extensionAvailability); if(DEBUG) { System.err.println(getThreadName() + ": GLContext GL ExtensionAvailabilityCache mapping key("+contextFQN+") -> "+toHexString(extensionAvailability.hashCode()) + " - entries: "+extensionAvailability.getTotalExtensionCount()); } } } if( ( 0 != ( CTX_PROFILE_ES & ctxProfileBits ) && major >= 2 ) || isExtensionAvailable(GLExtensions.ARB_ES2_compatibility) ) { ctxProfileBits |= CTX_IMPL_ES2_COMPAT; ctxProfileBits |= CTX_IMPL_FBO; } else if( hasFBOImpl(major, ctxProfileBits, extensionAvailability) ) { ctxProfileBits |= CTX_IMPL_FBO; } if(FORCE_NO_FBO_SUPPORT) { ctxProfileBits &= ~CTX_IMPL_FBO ; } setContextVersion(major, minor, ctxProfileBits, true); setDefaultSwapInterval(); final int glErrX = gl.glGetError(); if(DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.X: OK "+contextFQN+" - "+GLContext.getGLVersion(ctxVersion.getMajor(), ctxVersion.getMinor(), ctxOptions, null)+" - glErr "+toHexString(glErrX)); } return true; }
public void testParse_SpaceEcho() { byte[] effectParameters = {4, 6, 0, 0, 2, 14, 14, 6, 0, 0, 7, 0, 0, 0, 2, 14, 2, 5, 3, 0, 7, 0, 2, 0, 2, 14, 14, 6, 0, 0, 7, 0, 0, 0, 2, 14, 4, 10, 6, 0, 7, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; TwoBandDual twoBandDual = TwoBandDualParser.parse(effectParameters); assertThat(twoBandDual.mix, is(value(100))); assertThat(twoBandDual.level, is(value(0))); assertThat(twoBandDual.gainLeft1, is(value(-30))); assertThat(twoBandDual.fcLeft1, is(value(110))); assertThat(twoBandDual.qLeft1, is(value(0.7))); assertThat(twoBandDual.modeLeft1, is(value(0))); assertThat(twoBandDual.gainLeft2, is(value(-30))); assertThat(twoBandDual.fcLeft2, is(value(850))); assertThat(twoBandDual.qLeft2, is(value(0.7))); assertThat(twoBandDual.modeLeft2, is(value(2))); assertThat(twoBandDual.gainRight1, is(value(-30))); assertThat(twoBandDual.fcRight1, is(value(110))); assertThat(twoBandDual.qRight1, is(value(0.7))); assertThat(twoBandDual.modeRight1, is(value(0))); assertThat(twoBandDual.gainRight2, is(value(-30))); assertThat(twoBandDual.fcRight2, is(value(1700))); assertThat(twoBandDual.qRight2, is(value(0.7))); assertThat(twoBandDual.modeRight2, is(value(2))); }
public void testParse_SoloRoom() { byte[] effectParameters = {4, 6, 0, 0, 2, 14, 14, 6, 0, 0, 7, 0, 0, 0, 2, 14, 2, 5, 3, 0, 7, 0, 2, 0, 2, 14, 14, 6, 0, 0, 7, 0, 0, 0, 2, 14, 4, 10, 6, 0, 7, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; TwoBandDual twoBandDual = TwoBandDualParser.parse(effectParameters); assertThat(twoBandDual.mix, is(value(100))); assertThat(twoBandDual.level, is(value(0))); assertThat(twoBandDual.gainLeft1, is(value(-30))); assertThat(twoBandDual.fcLeft1, is(value(110))); assertThat(twoBandDual.qLeft1, is(value(0.7))); assertThat(twoBandDual.modeLeft1, is(value(0))); assertThat(twoBandDual.gainLeft2, is(value(-30))); assertThat(twoBandDual.fcLeft2, is(value(850))); assertThat(twoBandDual.qLeft2, is(value(0.7))); assertThat(twoBandDual.modeLeft2, is(value(2))); assertThat(twoBandDual.gainRight1, is(value(-30))); assertThat(twoBandDual.fcRight1, is(value(110))); assertThat(twoBandDual.qRight1, is(value(0.7))); assertThat(twoBandDual.modeRight1, is(value(0))); assertThat(twoBandDual.gainRight2, is(value(-30))); assertThat(twoBandDual.fcRight2, is(value(1700))); assertThat(twoBandDual.qRight2, is(value(0.7))); assertThat(twoBandDual.modeRight2, is(value(2))); }
public void doAddMessage(TransactionContext c, long sequence, MessageId messageID, ActiveMQDestination destination, byte[] data, long expiration, byte priority) throws SQLException, IOException { PreparedStatement s = null; ResultSet rs = null; cleanupExclusiveLock.readLock().lock(); try { s = c.getConnection().prepareStatement(statements.getAddMessageStatement()); s.setLong(1, sequence); s.setString(2, messageID.getProducerId().toString()); s.setLong(3, messageID.getProducerSequenceId()); s.setString(4, destination.getQualifiedName()); s.setLong(5, expiration); s.setLong(6, priority); if (s.executeUpdate() != 1) { throw new IOException("Failed to add broker message: " + messageID + " in container."); } s.close(); s = c.getConnection().prepareStatement(statements.getFindMessageByIdStatement()); s.setLong(1, sequence); rs = s.executeQuery(); if (!rs.next()) { throw new IOException("Failed select blob for message: " + messageID + " in container."); } Blob blob = rs.getBlob(1); OutputStream stream = blob.setBinaryStream(data.length); stream.write(data); stream.close(); s.close(); s = c.getConnection().prepareStatement(statements.getUpdateMessageStatement()); s.setBlob(1, blob); s.setLong(2, sequence); } finally { cleanupExclusiveLock.readLock().unlock(); close(rs); close(s); } }
public void doAddMessage(TransactionContext c, long sequence, MessageId messageID, ActiveMQDestination destination, byte[] data, long expiration, byte priority) throws SQLException, IOException { PreparedStatement s = null; ResultSet rs = null; cleanupExclusiveLock.readLock().lock(); try { s = c.getConnection().prepareStatement(statements.getAddMessageStatement()); s.setLong(1, sequence); s.setString(2, messageID.getProducerId().toString()); s.setLong(3, messageID.getProducerSequenceId()); s.setString(4, destination.getQualifiedName()); s.setLong(5, expiration); s.setLong(6, priority); s.setString(7, " "); if (s.executeUpdate() != 1) { throw new IOException("Failed to add broker message: " + messageID + " in container."); } s.close(); s = c.getConnection().prepareStatement(statements.getFindMessageByIdStatement()); s.setLong(1, sequence); rs = s.executeQuery(); if (!rs.next()) { throw new IOException("Failed select blob for message: " + messageID + " in container."); } Blob blob = rs.getBlob(1); OutputStream stream = blob.setBinaryStream(data.length); stream.write(data); stream.close(); s.close(); s = c.getConnection().prepareStatement(statements.getUpdateMessageStatement()); s.setBlob(1, blob); s.setLong(2, sequence); } finally { cleanupExclusiveLock.readLock().unlock(); close(rs); close(s); } }
public ImportedModel importModel(ImportSettings settings) throws IOException { ImportedModel importedModel; URL modelURL = settings.getModelURL(); if (!modelURL.getProtocol().equalsIgnoreCase("file")) { final String modelURLStr = modelURL.toExternalForm(); SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showConfirmDialog(null, "Unable to load KMZ from this url "+modelURLStr+ "\nPlease use a local kmz file.", "Deploy Error", JOptionPane.OK_OPTION); } }); return null; } try { File f = new File(modelURL.getFile()); ZipFile zipFile = new ZipFile(f); ZipEntry docKmlEntry = zipFile.getEntry("doc.kml"); KmlParser parser = new KmlParser(); InputStream in = zipFile.getInputStream(docKmlEntry); try { parser.decodeKML(in); } catch (Exception ex) { Logger.getLogger(KmzLoader.class.getName()).log(Level.SEVERE, null, ex); } List<KmlParser.KmlModel> models = parser.getModels(); HashMap<URL, String> textureFilesMapping = new HashMap(); importedModel = new KmzImportedModel(modelURL, models.get(0).getHref(), textureFilesMapping); String zipHost = WlzipManager.getWlzipManager().addZip(zipFile); ZipResourceLocator zipResource = new ZipResourceLocator(zipHost, zipFile, textureFilesMapping); ResourceLocatorTool.addThreadResourceLocator( ResourceLocatorTool.TYPE_TEXTURE, zipResource); if (models.size()==1) { importedModel.setModelBG(load(zipFile, models.get(0))); } else { Node modelBG = new Node(); for(KmlParser.KmlModel model : models) { modelBG.attachChild(load(zipFile, model)); } importedModel.setModelBG(modelBG); } ResourceLocatorTool.removeThreadResourceLocator(ResourceLocatorTool.TYPE_TEXTURE, zipResource); WlzipManager.getWlzipManager().removeZip(zipHost, zipFile); } catch (ZipException ex) { logger.log(Level.SEVERE, null, ex); throw new IOException("Zip Error"); } catch (IOException ex) { logger.log(Level.SEVERE, null, ex); throw ex; } importedModel.setModelLoader(this); importedModel.setImportSettings(settings); return importedModel; }
public ImportedModel importModel(ImportSettings settings) throws IOException { ImportedModel importedModel; URL modelURL = settings.getModelURL(); if (!modelURL.getProtocol().equalsIgnoreCase("file")) { final String modelURLStr = modelURL.toExternalForm(); SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showConfirmDialog(null, "Unable to load KMZ from this url "+modelURLStr+ "\nPlease use a local kmz file.", "Deploy Error", JOptionPane.OK_OPTION); } }); return null; } try { logger.warning("kmzloader.importModel() "+modelURL.toExternalForm()); File f = new File(modelURL.getFile()); if (f==null) { logger.warning("Unable to get file for model "+modelURL.toExternalForm()); JOptionPane.showMessageDialog(null, "Unable to get file for model "+modelURL.toExternalForm(), "Error", JOptionPane.ERROR_MESSAGE); return null; } ZipFile zipFile = new ZipFile(f); ZipEntry docKmlEntry = zipFile.getEntry("doc.kml"); KmlParser parser = new KmlParser(); InputStream in = zipFile.getInputStream(docKmlEntry); try { parser.decodeKML(in); } catch (Exception ex) { Logger.getLogger(KmzLoader.class.getName()).log(Level.SEVERE, null, ex); } List<KmlParser.KmlModel> models = parser.getModels(); HashMap<URL, String> textureFilesMapping = new HashMap(); importedModel = new KmzImportedModel(modelURL, models.get(0).getHref(), textureFilesMapping); String zipHost = WlzipManager.getWlzipManager().addZip(zipFile); ZipResourceLocator zipResource = new ZipResourceLocator(zipHost, zipFile, textureFilesMapping); ResourceLocatorTool.addThreadResourceLocator( ResourceLocatorTool.TYPE_TEXTURE, zipResource); if (models.size()==1) { importedModel.setModelBG(load(zipFile, models.get(0))); } else { Node modelBG = new Node(); for(KmlParser.KmlModel model : models) { modelBG.attachChild(load(zipFile, model)); } importedModel.setModelBG(modelBG); } ResourceLocatorTool.removeThreadResourceLocator(ResourceLocatorTool.TYPE_TEXTURE, zipResource); WlzipManager.getWlzipManager().removeZip(zipHost, zipFile); } catch (ZipException ex) { logger.log(Level.SEVERE, null, ex); throw new IOException("Zip Error"); } catch (IOException ex) { logger.log(Level.SEVERE, null, ex); throw ex; } importedModel.setModelLoader(this); importedModel.setImportSettings(settings); return importedModel; }
public void commandAction(Command command, Displayable displayable) { if (displayable == Home) { if (command == startCountingCommand) { switchDisplayable(null, getLoading()); String url = urlTextField.getString(); String chars = charTextField.getString(); countingThread = new CounterThread(this, url, chars); countingThread.start(); charTextField = null; urlTextField = null; } } else if (displayable == Loading) { if (command == cancelCountingCommand) { switchDisplayable(null, getHome()); countingThread.stopCounting(); countingThread = null; completeGuage = null; } } else if (displayable == Results) { if (command == backToStartCommand) { countingThread.stopCounting(); switchDisplayable(null, getHome()); imageItem.setImage(null); imageItem = null; countingThread = null; } else if (command == exitCommand) { countingThread.stopCounting(); countingThread = null; exitMIDlet(); } } }
public void commandAction(Command command, Displayable displayable) { if (displayable == Home) { if (command == startCountingCommand) { switchDisplayable(null, getLoading()); String url = getUrlTextField().getString(); String chars = getCharTextField().getString(); countingThread = new CounterThread(this, url, chars); countingThread.start(); } } else if (displayable == Loading) { if (command == cancelCountingCommand) { switchDisplayable(null, getHome()); countingThread.stopCounting(); countingThread = null; } } else if (displayable == Results) { if (command == backToStartCommand) { countingThread.stopCounting(); switchDisplayable(null, getHome()); getImageItem().setImage(null); countingThread = null; } else if (command == exitCommand) { countingThread.stopCounting(); countingThread = null; exitMIDlet(); } } }
public void testParse() { SourceMonitorResultParser parser = new SourceMonitorResultStaxParser(); File projectDirectory = new File("target/test-classes/solution/MessyTestSolution"); File reportFile = new File("target/test-classes/solution/MessyTestSolution/target/metrics-report.xml"); File moneyFile = new File("target/test-classes/solution/MessyTestSolution/MessyTestApplication/Money.cs"); List<FileMetrics> metrics = parser.parse(projectDirectory, reportFile); assertNotNull(metrics); assertEquals(5, metrics.size()); FileMetrics firstFile = metrics.get(0); assertEquals(62, firstFile.getComplexity()); assertEquals(moneyFile.getAbsoluteFile(), firstFile.getSourcePath().getAbsoluteFile()); assertEquals(3, firstFile.getCountClasses()); assertEquals(29, firstFile.getCommentLines()); assertEquals(1.77, firstFile.getAverageComplexity(),0.00001D); assertEquals("MessyTestApplication.Money", firstFile.getClassName()); assertEquals(10, firstFile.getCountAccessors()); assertEquals(53, firstFile.getCountBlankLines()); assertEquals(3, firstFile.getCountCalls()); assertEquals(387, firstFile.getCountLines()); assertEquals(11, firstFile.getCountMethods()); assertEquals(4, firstFile.getCountMethodStatements()); assertEquals(199, firstFile.getCountStatements()); assertEquals(10, firstFile.getDocumentationLines()); }
public void testParse() { SourceMonitorResultParser parser = new SourceMonitorResultStaxParser(); File projectDirectory = new File("target/test-classes/solution/MessyTestSolution"); File reportFile = new File("target/test-classes/solution/MessyTestSolution/target/metrics-report.xml"); File moneyFile = new File("target/test-classes/solution/MessyTestSolution/MessyTestApplication/Money.cs"); List<FileMetrics> metrics = parser.parse(projectDirectory, reportFile); assertNotNull(metrics); assertEquals(5, metrics.size()); FileMetrics firstFile = metrics.get(0); assertEquals(62, firstFile.getComplexity()); assertEquals(moneyFile.getName(), firstFile.getSourcePath().getName()); assertEquals(3, firstFile.getCountClasses()); assertEquals(29, firstFile.getCommentLines()); assertEquals(1.77, firstFile.getAverageComplexity(),0.00001D); assertEquals("MessyTestApplication.Money", firstFile.getClassName()); assertEquals(10, firstFile.getCountAccessors()); assertEquals(53, firstFile.getCountBlankLines()); assertEquals(3, firstFile.getCountCalls()); assertEquals(387, firstFile.getCountLines()); assertEquals(11, firstFile.getCountMethods()); assertEquals(4, firstFile.getCountMethodStatements()); assertEquals(199, firstFile.getCountStatements()); assertEquals(10, firstFile.getDocumentationLines()); }
public void run() { if (mode == 0) { try { serverSocket = new ServerSocket(SpaceRTK.getInstance().rPort, SO_BACKLOG); serverSocket.setSoTimeout(SO_TIMEOUT); } catch(IOException e) { e.printStackTrace(); return; } while (!serverSocket.isClosed()) { try { final Socket clientSocket = serverSocket.accept(); new PanelListener(clientSocket); } catch(SocketTimeoutException e) { System.err.println("ERROR: API connection timeout! \n"+e.getMessage()); } catch (Exception e) { if (!e.getMessage().contains("socket closed")) e.printStackTrace(); } } } else { try { final BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); String string = input.readLine(); if (string == null) { return; } string = URLDecoder.decode(string, "UTF-8"); string = string.substring(5, string.length() - 9); final PrintWriter output = new PrintWriter(socket.getOutputStream()); if (string.startsWith("call") && string.contains("?method=") && string.contains("&args=")) { final String method = string.substring(12, string.indexOf("&args=")); if (string.contains("&key=" + Utilities.crypt(method + SpaceRTK.getInstance().salt))) { if (string.startsWith("call?method=DOWNLOAD_WORLD")) { final boolean wasRunning = RemoteToolkit.isRunning(); if (wasRunning) RemoteToolkit.hold(); final File file = new File(string.split("\"")[1] + ".zip"); ZIP.zip(file, new File(string.split("\"")[1])); if (file.exists()) { final FileInputStream fileInputStream = new FileInputStream(file); final byte[] fileData = new byte[65536]; int length; output.println("HTTP/1.1 200 OK"); output.println("Content-Type: application/force-download; name=" + file.getName()); output.println("Content-Transfer-Encoding: binary"); output.println("Content-Length:" + file.length()); output.println("Content-Disposition: attachment; filename=" + file.getName()); output.println("Expires: 0"); output.println("Cache-Control: no-cache, must-revalidate"); output.println("Pragma: no-cache"); while ((length = fileInputStream.read(fileData)) > 0) output.print(new String(fileData, 0, length)); fileInputStream.close(); } else output.println(Utilities.addHeader(null)); if (wasRunning) RemoteToolkit.unhold(); } else { final Object result = interpret(string); if (result != null) output.println(Utilities.addHeader(JSONValue.toJSONString(result))); else output.println(Utilities.addHeader(null)); } } else output.println(Utilities.addHeader("Incorrect Salt supplied. Access denied!")); } else if (string.startsWith("ping")) output.println(Utilities.addHeader("Pong!")); else output.println(Utilities.addHeader(null)); output.flush(); input.close(); output.close(); } catch (final Exception e) { e.printStackTrace(); } } }
public void run() { if (mode == 0) { try { serverSocket = new ServerSocket(SpaceRTK.getInstance().rPort, SO_BACKLOG); serverSocket.setSoTimeout(SO_TIMEOUT); } catch(IOException e) { e.printStackTrace(); return; } while (!serverSocket.isClosed()) { try { final Socket clientSocket = serverSocket.accept(); new PanelListener(clientSocket); } catch(SocketTimeoutException e) { } catch (Exception e) { if (!e.getMessage().contains("socket closed")) e.printStackTrace(); } } } else { try { final BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); String string = input.readLine(); if (string == null) { return; } string = URLDecoder.decode(string, "UTF-8"); string = string.substring(5, string.length() - 9); final PrintWriter output = new PrintWriter(socket.getOutputStream()); if (string.startsWith("call") && string.contains("?method=") && string.contains("&args=")) { final String method = string.substring(12, string.indexOf("&args=")); if (string.contains("&key=" + Utilities.crypt(method + SpaceRTK.getInstance().salt))) { if (string.startsWith("call?method=DOWNLOAD_WORLD")) { final boolean wasRunning = RemoteToolkit.isRunning(); if (wasRunning) RemoteToolkit.hold(); final File file = new File(string.split("\"")[1] + ".zip"); ZIP.zip(file, new File(string.split("\"")[1])); if (file.exists()) { final FileInputStream fileInputStream = new FileInputStream(file); final byte[] fileData = new byte[65536]; int length; output.println("HTTP/1.1 200 OK"); output.println("Content-Type: application/force-download; name=" + file.getName()); output.println("Content-Transfer-Encoding: binary"); output.println("Content-Length:" + file.length()); output.println("Content-Disposition: attachment; filename=" + file.getName()); output.println("Expires: 0"); output.println("Cache-Control: no-cache, must-revalidate"); output.println("Pragma: no-cache"); while ((length = fileInputStream.read(fileData)) > 0) output.print(new String(fileData, 0, length)); fileInputStream.close(); } else output.println(Utilities.addHeader(null)); if (wasRunning) RemoteToolkit.unhold(); } else { final Object result = interpret(string); if (result != null) output.println(Utilities.addHeader(JSONValue.toJSONString(result))); else output.println(Utilities.addHeader(null)); } } else output.println(Utilities.addHeader("Incorrect Salt supplied. Access denied!")); } else if (string.startsWith("ping")) output.println(Utilities.addHeader("Pong!")); else output.println(Utilities.addHeader(null)); output.flush(); input.close(); output.close(); } catch (final Exception e) { e.printStackTrace(); } } }
JobInformations(JobDetail jobDetail, JobExecutionContext jobExecutionContext, Scheduler scheduler) throws SchedulerException { super(); assert jobDetail != null; assert scheduler != null; this.group = jobDetail.getGroup(); this.name = jobDetail.getName(); this.description = jobDetail.getDescription(); this.jobClassName = jobDetail.getJobClass().getName(); if (jobExecutionContext == null) { elapsedTime = -1; } else { elapsedTime = System.currentTimeMillis() - jobExecutionContext.getFireTime().getTime(); } final Trigger[] triggers = scheduler.getTriggersOfJob(name, group); this.nextFireTime = getNextFireTime(triggers); this.previousFireTime = getPreviousFireTime(triggers); String cronTriggerExpression = null; long simpleTriggerRepeatInterval = -1; boolean jobPaused = true; for (final Trigger trigger : triggers) { if (trigger instanceof CronTrigger) { cronTriggerExpression = ((CronTrigger) trigger).getCronExpression(); } else if (trigger instanceof SimpleTrigger) { simpleTriggerRepeatInterval = ((SimpleTrigger) trigger).getRepeatInterval(); } jobPaused = jobPaused && scheduler.getTriggerState(trigger.getName(), trigger.getGroup()) != Trigger.STATE_PAUSED; } this.repeatInterval = simpleTriggerRepeatInterval; this.cronExpression = cronTriggerExpression; this.paused = jobPaused; this.globalJobId = buildGlobalJobId(jobDetail); }
JobInformations(JobDetail jobDetail, JobExecutionContext jobExecutionContext, Scheduler scheduler) throws SchedulerException { super(); assert jobDetail != null; assert scheduler != null; this.group = jobDetail.getGroup(); this.name = jobDetail.getName(); this.description = jobDetail.getDescription(); this.jobClassName = jobDetail.getJobClass().getName(); if (jobExecutionContext == null) { elapsedTime = -1; } else { elapsedTime = System.currentTimeMillis() - jobExecutionContext.getFireTime().getTime(); } final Trigger[] triggers = scheduler.getTriggersOfJob(name, group); this.nextFireTime = getNextFireTime(triggers); this.previousFireTime = getPreviousFireTime(triggers); String cronTriggerExpression = null; long simpleTriggerRepeatInterval = -1; boolean jobPaused = true; for (final Trigger trigger : triggers) { if (trigger instanceof CronTrigger) { cronTriggerExpression = ((CronTrigger) trigger).getCronExpression(); } else if (trigger instanceof SimpleTrigger) { simpleTriggerRepeatInterval = ((SimpleTrigger) trigger).getRepeatInterval(); } jobPaused = jobPaused && scheduler.getTriggerState(trigger.getName(), trigger.getGroup()) == Trigger.STATE_PAUSED; } this.repeatInterval = simpleTriggerRepeatInterval; this.cronExpression = cronTriggerExpression; this.paused = jobPaused; this.globalJobId = buildGlobalJobId(jobDetail); }
public void parse(boolean breakfast) { Elements h2Eles = doc.getElementsByTag("h2"); Elements tables = doc.select("table"); for(Element table : tables) { items = new ItemSet(); String h2 = h2Eles.get(counter).text(); items.setTitle(h2); for(Element tr : table.select("tr")) { String itemName = null; BigDecimal itemPrice = null; String itemDesc = null; String tempName = ""; String one = null; String two = null; BigDecimal priceOne = null; BigDecimal priceTwo = null; for(Element td : tr.select("td")) { String strongName = td.select("strong").text(); String description = tr.select("td").text(); if(!strongName.equals("")&&!h2.equals("Breakfast")) { if(!strongName.contains("$")) { tempName = strongName; name = true; parseDesc = false; if(strongName.contains("Combos - ")) { itemName = strongName.replace("Combos - ",""); } else if(strongName.contains("Just Burgers - ")) { itemName = strongName.replace("Just Burgers - ",""); } else if(strongName.contains("Just Sandwiches - ")) { itemName = strongName.replace("Just Sandwiches - ",""); } else if(strongName.contains("Just Sandwiches - ")) { itemName = strongName.replace("Just Sandwiches- ",""); } else if(strongName.contains("Soup and Salad")) { soupAndSalad = true; one = strongName.substring(0,5); two = strongName.substring(9,14); } else { itemName = strongName; } } else if(strongName.contains("$")) { price = true; parseDesc = true; strongName = strongName.replace(",","."); if(strongName.contains("plus tax")) { strongName = strongName.replace(" plus tax",""); strongName = strongName.replace("$",""); itemPrice = (new BigDecimal(strongName).add(new BigDecimal(strongName))).multiply(new BigDecimal(".08")); } else if(strongName.contains("per oz")) { priceOne = new BigDecimal(strongName.substring(7,11)); priceTwo = new BigDecimal(strongName.substring(26,30)); } else { strongName = strongName.replace("$",""); itemPrice = new BigDecimal(strongName); } } } else if(h2.equals("Breakfast")&&breakfast) { if(strongName.contains("$")) { parseDesc = true; itemPrice = new BigDecimal(strongName.replace("$","")); } else { parseDesc = false; itemName = strongName; } } if(parseDesc) { itemDesc = descParse(tempName,strongName,description); } } if(itemName!=null) { if(soupAndSalad) { Item itemOne = new Item(one,priceOne,itemDesc,true); Item itemTwo = new Item(two,priceTwo,itemDesc,true); itemOne.setOunces(true); itemTwo.setOunces(true); items.add(itemOne); items.add(itemTwo); soupAndSalad = false; } else if(price&&name) { items.add(new Item(itemName,itemPrice,itemDesc,true)); price = false; name = false; } else { items.add(new Item(itemName,itemPrice,itemDesc,false)); price = false; name = false; } } } listItems.add(items); counter++; } }
public void parse(boolean breakfast) { Elements h2Eles = doc.getElementsByTag("h2"); Elements tables = doc.select("table"); for(Element table : tables) { items = new ItemSet(); String h2 = h2Eles.get(counter).text(); items.setTitle(h2); for(Element tr : table.select("tr")) { String itemName = null; BigDecimal itemPrice = null; String itemDesc = null; String tempName = ""; String tempPrice = ""; String one = null; String two = null; BigDecimal priceOne = null; BigDecimal priceTwo = null; for(Element td : tr.select("td")) { String strongName = td.select("strong").text(); String description = tr.select("td").text(); if(!strongName.equals("")&&!h2.equals("Breakfast")) { if(!strongName.contains("$")) { tempName = strongName; name = true; parseDesc = false; if(strongName.contains("Combos - ")) { itemName = strongName.replace("Combos - ",""); } else if(strongName.contains("Just Burgers - ")) { itemName = strongName.replace("Just Burgers - ",""); } else if(strongName.contains("Just Sandwiches - ")) { itemName = strongName.replace("Just Sandwiches - ",""); } else if(strongName.contains("Just Sandwiches - ")) { itemName = strongName.replace("Just Sandwiches- ",""); } else if(strongName.contains("Soup and Salad")) { soupAndSalad = true; one = strongName.substring(0,5); two = strongName.substring(9,14); } else { itemName = strongName; } } else if(strongName.contains("$")) { price = true; parseDesc = true; tempPrice = strongName; strongName = strongName.replace(",","."); if(strongName.contains("plus tax")) { strongName = strongName.replace(" plus tax",""); strongName = strongName.replace("$",""); itemPrice = (new BigDecimal(strongName).multiply(new BigDecimal(".08")).add(new BigDecimal(strongName))); } else if(strongName.contains("per oz")) { priceOne = new BigDecimal(strongName.substring(7,11)); priceTwo = new BigDecimal(strongName.substring(26,30)); } else { strongName = strongName.replace("$",""); itemPrice = new BigDecimal(strongName); } } } else if(h2.equals("Breakfast")&&breakfast) { if(strongName.contains("$")) { parseDesc = true; itemPrice = new BigDecimal(strongName.replace("$","")); } else { parseDesc = false; itemName = strongName; } } if(parseDesc) { itemDesc = descParse(tempName,tempPrice,description); } } if(itemName!=null) { if(soupAndSalad) { Item itemOne = new Item(one,priceOne,itemDesc,true); Item itemTwo = new Item(two,priceTwo,itemDesc,true); itemOne.setOunces(true); itemTwo.setOunces(true); items.add(itemOne); items.add(itemTwo); soupAndSalad = false; } else if(price&&name) { items.add(new Item(itemName,itemPrice,itemDesc,true)); price = false; name = false; } else { items.add(new Item(itemName,itemPrice,itemDesc,false)); price = false; name = false; } } } listItems.add(items); counter++; } }
public MiddlePanelSelect(MainWindow gui) { super(gui); this.setLayout(new FlowLayout(FlowLayout.LEFT)); from = new JLabel("FROM TABLE :"); centralPanel = new JPanel(); centralPanel.setLayout(new CardLayout()); whereNum = new JLabel("WHERE nro_multa ="); nroMulta = new JFormattedTextField(NumberFormat.getIntegerInstance()); nroMulta.setColumns(5); initCentralPanelEmpty(); initCentralPanelFilled(); centralPanel.add(centralPanelEmpty,sPaneEmpty); centralPanel.add(centralPanelFilled,sPaneFilled); String[] cb = {"Infraccion","Multa"}; cbTable = new JComboBox(cb); cbTable.setAction(new ActionMiddlePanelSelectCbox(this,centralPanel)); ok = new JButton(new ActionMiddlePanelSelectOk(gui,nroMulta,cbTable,"OK")); this.add(from); this.add(cbTable); this.add(centralPanel); this.add(ok); }
public MiddlePanelSelect(MainWindow gui) { super(gui); this.setLayout(new FlowLayout(FlowLayout.LEFT)); from = new JLabel("FROM TABLE :"); centralPanel = new JPanel(); centralPanel.setLayout(new CardLayout()); whereNum = new JLabel("WHERE nro_multa ="); NumberFormat nroMultaFormat = NumberFormat.getIntegerInstance(); nroMultaFormat.setGroupingUsed(false); nroMulta = new JFormattedTextField(nroMultaFormat); nroMulta.setColumns(5); initCentralPanelEmpty(); initCentralPanelFilled(); centralPanel.add(centralPanelEmpty,sPaneEmpty); centralPanel.add(centralPanelFilled,sPaneFilled); String[] cb = {"Infraccion","Multa"}; cbTable = new JComboBox(cb); cbTable.setAction(new ActionMiddlePanelSelectCbox(this,centralPanel)); ok = new JButton(new ActionMiddlePanelSelectOk(gui,nroMulta,cbTable,"OK")); this.add(from); this.add(cbTable); this.add(centralPanel); this.add(ok); }
public void initializeLists(int level) { int numberOfThings = scanner.nextInt(); CollidableThing[] thingsArray = new CollidableThing[numberOfThings]; String thingType = ""; for(int k = 0; k < thingsArray.length; k++ ) { thingType = scanner.next(); if(thingType.equals("Tree")) thingsArray[k] = new CollidableTree(); else if(thingType.equals("Rock")) thingsArray[k] = new CollidableRock(); else if(thingType.equals("Cow")) thingsArray[k] = new CollidableCow(); else thingsArray[k] = new CollidableEinstein(); thingsArray[k].setX(scanner.nextInt()); thingsArray[k].setY(scanner.nextInt()); thingsArray[k].setMass(scanner.nextInt()); Log.v("EinsteinDefenseActivity", "Type: " + thingType + "\n" + "x: " + thingsArray[k].getX() + "\n " + "y: " + thingsArray[k].getY() + "\n " + "Dx: " + thingsArray[k].getDx() + "\n " + "Dy: " + thingsArray[k].getDy() + "\n " + "mass: " + thingsArray[k].getMass() + "\n "); if(thingType.equals("Einstein")) thingsArray[k].setDy(scanner.nextInt()); projectilesInactive.add(thingsArray[k]); } }
public void initializeLists(int level) { int numberOfThings = scanner.nextInt(); CollidableThing[] thingsArray = new CollidableThing[numberOfThings]; String thingType = ""; for(int k = 0; k < thingsArray.length; k++ ) { thingType = scanner.next(); if(thingType.equals("Tree")) thingsArray[k] = new CollidableTree(); else if(thingType.equals("Rock")) thingsArray[k] = new CollidableRock(); else if(thingType.equals("Cow")) thingsArray[k] = new CollidableCow(); else thingsArray[k] = new CollidableEinstein(); thingsArray[k].setX(scanner.nextInt()); thingsArray[k].setY(scanner.nextInt()); thingsArray[k].setMass(scanner.nextInt()); Log.v("EinsteinDefenseActivity", "Type: " + thingType + "\n" + "x: " + thingsArray[k].getX() + "\n " + "y: " + thingsArray[k].getY() + "\n " + "Dx: " + thingsArray[k].getDx() + "\n " + "Dy: " + thingsArray[k].getDy() + "\n " + "mass: " + thingsArray[k].getMass() + "\n "); if(thingType.equals("Einstein")) { thingsArray[k].setDy(scanner.nextInt()); invaders.add(thingsArray[k]); } else projectilesInactive.add(thingsArray[k]); } }
ConfigBean _createAndSet( final ConfigBean parent, final Class<? extends ConfigBeanProxy> childType, final List<AttributeChanges> attributes, final TransactionCallBack<WriteableView> runnable) throws TransactionFailure { ConfigBeanProxy readableView = parent.getProxy(parent.getProxyType()); ConfigBeanProxy readableChild = (ConfigBeanProxy) apply(new SingleConfigCode<ConfigBeanProxy>() { public Object run(ConfigBeanProxy param) throws PropertyVetoException, TransactionFailure { ConfigBeanProxy child = param.createChild(childType); WriteableView writeableParent = (WriteableView) Proxy.getInvocationHandler(param); Class parentProxyType = parent.getProxyType(); Class<?> targetClass = null; ConfigModel.Property element = null; for (ConfigModel.Property e : parent.model.elements.values()) { if (e.isLeaf()) { continue; } ConfigModel elementModel = ((ConfigModel.Node) e).model; if (Logger.getAnonymousLogger().isLoggable(Level.FINE)) { Logger.getAnonymousLogger().fine( "elementModel.targetTypeName = " + elementModel.targetTypeName + ", collection: " + e.isCollection() + ", childType.getName() = " + childType.getName() ); } if (elementModel.targetTypeName.equals(childType.getName())) { element = e; break; } else if ( e.isCollection() ) { try { final Class<?> tempClass = childType.getClassLoader().loadClass( elementModel.targetTypeName); if ( tempClass.isAssignableFrom( childType ) ) { element = e; targetClass = tempClass; break; } } catch (Exception ex ) { throw new TransactionFailure("EXCEPTION getting class for " + elementModel.targetTypeName, ex); } } } if (element != null) { if (element.isCollection()) { for (Method m : parentProxyType.getMethods()) { final Class returnType = m.getReturnType(); if (Collection.class.isAssignableFrom(returnType)) { if (!(m.getGenericReturnType() instanceof ParameterizedType)) throw new IllegalArgumentException("List needs to be parameterized"); final Class itemType = Types.erasure(Types.getTypeArgument(m.getGenericReturnType(), 0)); if (itemType.isAssignableFrom(childType)) { List list = null; try { list = (List) m.invoke(param, null); } catch (IllegalAccessException e) { throw new TransactionFailure("Exception while adding to the parent", e); } catch (InvocationTargetException e) { throw new TransactionFailure("Exception while adding to the parent", e); } if (list != null) { list.add(child); break; } } } } } else { writeableParent.setter(element, child, childType); } } else { throw new TransactionFailure("Parent " + parent.getProxyType() + " does not have a child of type " + childType); } WriteableView writeableChild = (WriteableView) Proxy.getInvocationHandler(child); applyProperties(writeableChild, attributes); if (runnable!=null) { runnable.performOn(writeableChild); } return child; } }, readableView); return (ConfigBean) Dom.unwrap(readableChild); }
ConfigBean _createAndSet( final ConfigBean parent, final Class<? extends ConfigBeanProxy> childType, final List<AttributeChanges> attributes, final TransactionCallBack<WriteableView> runnable) throws TransactionFailure { ConfigBeanProxy readableView = parent.getProxy(parent.getProxyType()); ConfigBeanProxy readableChild = (ConfigBeanProxy) apply(new SingleConfigCode<ConfigBeanProxy>() { public Object run(ConfigBeanProxy param) throws PropertyVetoException, TransactionFailure { ConfigBeanProxy child = param.createChild(childType); WriteableView writeableParent = (WriteableView) Proxy.getInvocationHandler(param); Class parentProxyType = parent.getProxyType(); Class<?> targetClass = null; ConfigModel.Property element = null; for (ConfigModel.Property e : parent.model.elements.values()) { if (e.isLeaf()) { continue; } ConfigModel elementModel = ((ConfigModel.Node) e).model; if (Logger.getAnonymousLogger().isLoggable(Level.FINE)) { Logger.getAnonymousLogger().fine( "elementModel.targetTypeName = " + elementModel.targetTypeName + ", collection: " + e.isCollection() + ", childType.getName() = " + childType.getName() ); } if (elementModel.targetTypeName.equals(childType.getName())) { element = e; break; } else if ( e.isCollection() ) { try { final Class<?> tempClass = elementModel.classLoaderHolder.get().loadClass(elementModel.targetTypeName); if ( tempClass.isAssignableFrom( childType ) ) { element = e; targetClass = tempClass; break; } } catch (Exception ex ) { throw new TransactionFailure("EXCEPTION getting class for " + elementModel.targetTypeName, ex); } } } if (element != null) { if (element.isCollection()) { for (Method m : parentProxyType.getMethods()) { final Class returnType = m.getReturnType(); if (Collection.class.isAssignableFrom(returnType)) { if (!(m.getGenericReturnType() instanceof ParameterizedType)) throw new IllegalArgumentException("List needs to be parameterized"); final Class itemType = Types.erasure(Types.getTypeArgument(m.getGenericReturnType(), 0)); if (itemType.isAssignableFrom(childType)) { List list = null; try { list = (List) m.invoke(param, null); } catch (IllegalAccessException e) { throw new TransactionFailure("Exception while adding to the parent", e); } catch (InvocationTargetException e) { throw new TransactionFailure("Exception while adding to the parent", e); } if (list != null) { list.add(child); break; } } } } } else { writeableParent.setter(element, child, childType); } } else { throw new TransactionFailure("Parent " + parent.getProxyType() + " does not have a child of type " + childType); } WriteableView writeableChild = (WriteableView) Proxy.getInvocationHandler(child); applyProperties(writeableChild, attributes); if (runnable!=null) { runnable.performOn(writeableChild); } return child; } }, readableView); return (ConfigBean) Dom.unwrap(readableChild); }
public String extractItem(@RequestParam String url, Model model) { log.info(String.format("Handling item request with parameter %s", url)); ItemResponse response = queryItemService.extractItem(url); ItemOrder order = createItemOrderFor(response); model.addAttribute("itemOrder", order); return "order"; }
public String extractItem(@RequestParam String url, Model model) { log.info(String.format("Handling item request with parameter %s", url)); ItemResponse response = queryItemService.extractItem(url); ItemOrder order = createItemOrderFor(response); model.addAttribute("itemOrder", order); return "order/order"; }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.settings); Preference mypref = (Preference) findPreference("setting_github"); mypref.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference mypref) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/nathanjordan/PaintMobile3D/")); startActivity(browserIntent); return true; } }); Preference mypref2 = (Preference) findPreference("setting_dev_info"); mypref2.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference mypref) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( context); alertDialogBuilder.setTitle("Developers"); alertDialogBuilder .setMessage("Nathan Jordan\nThomas Kelly\nHalim Cagri Ates") .setCancelable(false) .setPositiveButton("OK",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { dialog.cancel(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); return true; } }); }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.settings); Preference mypref = (Preference) findPreference("setting_github"); mypref.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference mypref) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/nathanjordan/PaintMobile3D/")); startActivity(browserIntent); return true; } }); Preference mypref2 = (Preference) findPreference("setting_dev_info"); mypref2.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference mypref) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( context); alertDialogBuilder.setTitle("Developers"); alertDialogBuilder .setMessage("Nathan Jordan\n\nThomas Kelly\n\nHalim Cagri Ates") .setCancelable(false) .setPositiveButton("OK",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { dialog.cancel(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); return true; } }); }
public int[] convert(float pitch, float roll, int exp) { int max = (int) Math.pow(2, exp); float[] cPitch = pitchAlgorithm.convert(pitch); float[] cRoll = rollAlgorithm.convert(roll); int lMDirection = 1; int rMDirection = 1; float lmRaw = cPitch[0] * (1 - cRoll[0]); float rmRaw = cPitch[1] * (1 - cRoll[1]); if (0f > lmRaw) { lMDirection = -1; lmRaw = -1; } if (0f > rmRaw) { rMDirection = -1; rmRaw = -1; } int lMotor = (int) Math .floor(Math.scalb(lmRaw, exp)); int rMotor = (int) Math .floor(Math.scalb(rmRaw, exp)); if (max == lMotor) { lMotor = lMotor - 1; } if (max == rMotor) { rMotor = rMotor - 1; } return new int[] { lMotor, lMDirection, rMotor, rMDirection }; }
public int[] convert(float pitch, float roll, int exp) { int max = (int) Math.pow(2, exp); float[] cPitch = pitchAlgorithm.convert(pitch); float[] cRoll = rollAlgorithm.convert(roll); int lMDirection = 1; int rMDirection = 1; float lmRaw = cPitch[0] * (1 - cRoll[0]); float rmRaw = cPitch[1] * (1 - cRoll[1]); if (0f > lmRaw) { lMDirection = -1; lmRaw = -1 * lmRaw; } if (0f > rmRaw) { rMDirection = -1; rmRaw = -1 * rmRaw; } int lMotor = (int) Math .floor(Math.scalb(lmRaw, exp)); int rMotor = (int) Math .floor(Math.scalb(rmRaw, exp)); if (max == lMotor) { lMotor = lMotor - 1; } if (max == rMotor) { rMotor = rMotor - 1; } return new int[] { lMotor, lMDirection, rMotor, rMDirection }; }
public Provider newProvider ( Map<String,String> properties) { Abdera abdera = getAbdera(); String instance = properties.get(PROVIDER); log.debug(Localizer.sprintf("CREATING.NEW.INSTANCE","Provider")); Provider provider = (Provider) Discover.locate( PROVIDER, (instance != null) ? instance : DefaultProvider.class.getName(), abdera); log.debug(Localizer.sprintf("INITIALIZING.INSTANCE", "Provider")); provider.init(abdera, properties); return provider; }
public Provider newProvider ( Map<String,String> properties) { Abdera abdera = getAbdera(); String instance = properties.get(PROVIDER); if (instance == null) { instance = DefaultProvider.class.getName(); } log.debug(Localizer.sprintf("CREATING.NEW.INSTANCE","Provider")); Provider provider = (Provider) Discover.locate(PROVIDER, instance); log.debug(Localizer.sprintf("INITIALIZING.INSTANCE", "Provider")); provider.init(abdera, properties); return provider; }
public SimpleUrlHandlerMapping bristlebackHandlerMappings() { Map<String, BristlebackHttpHandler> mappings = new HashMap<>(); mappings.put(SERVLET_MAPPING, bristlebackHttpHandler()); SimpleUrlHandlerMapping handlerMapping = new SimpleUrlHandlerMapping(); handlerMapping.setUrlMap(mappings); return handlerMapping; }
public SimpleUrlHandlerMapping bristlebackHandlerMappings() { Map<String, BristlebackHttpHandler> mappings = new HashMap<String, BristlebackHttpHandler>(); mappings.put(SERVLET_MAPPING, bristlebackHttpHandler()); SimpleUrlHandlerMapping handlerMapping = new SimpleUrlHandlerMapping(); handlerMapping.setUrlMap(mappings); return handlerMapping; }
public void load(final DataReader<RepoContentNode, Object> reader, RepoContentNode parent, final AsyncCallback<Object> callback) { int i = parent.getResourceUri().indexOf("repositories"); String url = parent.getResourceUri().substring(i); server.getResource(url).get(new RequestCallback() { public void onError(Request request, Throwable exception) { callback.onFailure(exception); } public void onResponseReceived(Request request, Response response) { List<RepoContentNode> list = new ArrayList<RepoContentNode>(); ListLoadResult<ModelData> result = (ListLoadResult<ModelData>) reader.read(null, response.getText()); for (ModelData model : result.getData()) { list.add(new RepoContentNode(model)); } callback.onSuccess(list); } }, variant); }
public void load(final DataReader<RepoContentNode, Object> reader, RepoContentNode parent, final AsyncCallback<Object> callback) { int i = parent.getResourceUri().indexOf("repositories"); String url = parent.getResourceUri().substring(i) + "/"; server.getResource(url).get(new RequestCallback() { public void onError(Request request, Throwable exception) { callback.onFailure(exception); } public void onResponseReceived(Request request, Response response) { List<RepoContentNode> list = new ArrayList<RepoContentNode>(); ListLoadResult<ModelData> result = (ListLoadResult<ModelData>) reader.read(null, response.getText()); for (ModelData model : result.getData()) { list.add(new RepoContentNode(model)); } callback.onSuccess(list); } }, variant); }
private void getConnectionArguments(Map connectionArgs) throws IllegalConnectorArgumentsException { String attribute = "port"; try { fPort = ((Connector.IntegerArgument)connectionArgs.get(attribute)).intValue(); attribute = "timeout"; fTimeout = ((Connector.IntegerArgument)connectionArgs.get(attribute)).intValue(); } catch (ClassCastException e) { throw new IllegalConnectorArgumentsException(ConnectMessages.getString("SocketListeningConnectorImpl.Connection_argument_is_not_of_the_right_type_6"), attribute); } catch (NullPointerException e) { throw new IllegalConnectorArgumentsException(ConnectMessages.getString("SocketListeningConnectorImpl.Necessary_connection_argument_is_null_7"), attribute); } catch (NumberFormatException e) { throw new IllegalConnectorArgumentsException(ConnectMessages.getString("SocketListeningConnectorImpl.Connection_argument_is_not_a_number_8"), attribute); } }
private void getConnectionArguments(Map connectionArgs) throws IllegalConnectorArgumentsException { String attribute = "port"; try { fPort = ((Connector.IntegerArgument)connectionArgs.get(attribute)).intValue(); attribute = "timeout"; IntegerArgument argument = (IntegerArgument) connectionArgs.get(attribute); if (argument != null) { fTimeout = argument.intValue(); } else { fTimeout = 0; } } catch (ClassCastException e) { throw new IllegalConnectorArgumentsException(ConnectMessages.getString("SocketListeningConnectorImpl.Connection_argument_is_not_of_the_right_type_6"), attribute); } catch (NullPointerException e) { throw new IllegalConnectorArgumentsException(ConnectMessages.getString("SocketListeningConnectorImpl.Necessary_connection_argument_is_null_7"), attribute); } catch (NumberFormatException e) { throw new IllegalConnectorArgumentsException(ConnectMessages.getString("SocketListeningConnectorImpl.Connection_argument_is_not_a_number_8"), attribute); } }
public static Config getFenixFrameworkConfig(final String[] domainModels) { final Map<String, CasConfig> casConfigMap = new HashMap<String, CasConfig>(); for (final Object key : properties.keySet()) { final String property = (String) key; int i = property.indexOf(".cas.enable"); if (i >= 0) { final String hostname = property.substring(0, i); if (getBooleanProperty(property)) { final String casLoginUrl = getProperty(hostname + ".cas.loginUrl"); final String casLogoutUrl = getProperty(hostname + ".cas.logoutUrl"); final String casValidateUrl = getProperty(hostname + ".cas.ValidateUrl"); final String serviceUrl = getProperty(hostname + ".cas.serviceUrl"); final CasConfig casConfig = new CasConfig(casLoginUrl, casLogoutUrl, casValidateUrl, serviceUrl); casConfigMap.put(hostname, casConfig); } } } return new Config() {{ domainModelPaths = domainModels; dbAlias = getProperty("db.alias"); dbUsername = getProperty("db.user"); dbPassword = getProperty("db.pass"); appName = getProperty("app.name"); appContext = getProperty("app.context"); filterRequestWithDigest = getBooleanProperty("filter.request.with.digest"); tamperingRedirect = getProperty("digest.tampering.url"); errorIfChangingDeletedObject = getBooleanProperty("error.if.changing.deleted.object"); defaultLanguage = getProperty("language"); defaultLocation = getProperty("location"); defaultVariant = getProperty("variant"); updateDataRepositoryStructure = true; updateRepositoryStructureIfNeeded = true; casConfigByHost = Collections.unmodifiableMap(casConfigMap); rootClass = MyOrg.class; }}; }
public static Config getFenixFrameworkConfig(final String[] domainModels) { final Map<String, CasConfig> casConfigMap = new HashMap<String, CasConfig>(); for (final Object key : properties.keySet()) { final String property = (String) key; int i = property.indexOf(".cas.enable"); if (i >= 0) { final String hostname = property.substring(0, i); if (getBooleanProperty(property)) { final String casLoginUrl = getProperty(hostname + ".cas.loginUrl"); final String casLogoutUrl = getProperty(hostname + ".cas.logoutUrl"); final String casValidateUrl = getProperty(hostname + ".cas.ValidateUrl"); final String serviceUrl = getProperty(hostname + ".cas.serviceUrl"); final CasConfig casConfig = new CasConfig(casLoginUrl, casLogoutUrl, casValidateUrl, serviceUrl); casConfigMap.put(hostname, casConfig); } } } return new Config() {{ domainModelPaths = domainModels; dbAlias = getProperty("db.alias"); dbUsername = getProperty("db.user"); dbPassword = getProperty("db.pass"); appName = getProperty("app.name"); appContext = getProperty("app.context"); filterRequestWithDigest = getBooleanProperty("filter.request.with.digest"); tamperingRedirect = getProperty("digest.tampering.url"); errorIfChangingDeletedObject = getBooleanProperty("error.if.changing.deleted.object"); defaultLanguage = getProperty("language"); defaultLocation = getProperty("location"); defaultVariant = getProperty("variant"); updateDataRepositoryStructure = true; updateRepositoryStructureIfNeeded = true; casConfigByHost = Collections.unmodifiableMap(casConfigMap); rootClass = MyOrg.class; javascriptValidationEnabled = true; }}; }
protected Control createContents( Composite parent ) { Composite composite = BaseWidgetUtils.createColumnContainer( parent, 1, 1 ); Preferences preferences = ConnectionCorePlugin.getDefault().getPluginPreferences(); boolean validateCertificates = preferences .getBoolean( ConnectionCoreConstants.PREFERENCE_VALIDATE_CERTIFICATES ); verifyCertificatesButton = BaseWidgetUtils.createCheckbox( composite, Messages .getString( "CertificateValidationPreferencePage.ValidateCertificates" ), 1 ); verifyCertificatesButton.setSelection( validateCertificates ); verifyCertificatesButton.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected( SelectionEvent e ) { tabFolder.setEnabled( verifyCertificatesButton.getSelection() ); } } ); tabFolder = new TabFolder( composite, SWT.TOP ); GridLayout mainLayout = new GridLayout(); mainLayout.marginWidth = 0; mainLayout.marginHeight = 0; tabFolder.setLayout( mainLayout ); tabFolder.setLayoutData( new GridData( GridData.FILL, GridData.FILL, true, true ) ); permanentCLComposite = new CertificateListComposite( tabFolder, SWT.NONE ); permanentCLComposite.setInput( ConnectionCorePlugin.getDefault().getPermanentTrustStoreManager() ); TabItem permanentTab = new TabItem( tabFolder, SWT.NONE, 0 ); permanentTab.setText( Messages.getString( "CertificateValidationPreferencePage.PermanentTrusted" ) ); permanentTab.setControl( permanentCLComposite ); sessionCLComposite = new CertificateListComposite( tabFolder, SWT.NONE ); sessionCLComposite.setInput( ConnectionCorePlugin.getDefault().getSessionTrustStoreManager() ); TabItem sessionTab = new TabItem( tabFolder, SWT.NONE, 1 ); sessionTab.setText( Messages.getString( "CertificateValidationPreferencePage.TemporaryTrusted" ) ); sessionTab.setControl( sessionCLComposite ); tabFolder.setEnabled( verifyCertificatesButton.getSelection() ); return composite; }
protected Control createContents( Composite parent ) { Composite composite = BaseWidgetUtils.createColumnContainer( parent, 1, 1 ); Preferences preferences = ConnectionCorePlugin.getDefault().getPluginPreferences(); boolean validateCertificates = preferences .getBoolean( ConnectionCoreConstants.PREFERENCE_VALIDATE_CERTIFICATES ); verifyCertificatesButton = BaseWidgetUtils.createCheckbox( composite, Messages .getString( "CertificateValidationPreferencePage.ValidateCertificates" ), 1 ); verifyCertificatesButton.setSelection( validateCertificates ); verifyCertificatesButton.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected( SelectionEvent e ) { tabFolder.setEnabled( verifyCertificatesButton.getSelection() ); } } ); tabFolder = new TabFolder( composite, SWT.TOP ); tabFolder.setLayoutData( new GridData( GridData.FILL, GridData.FILL, true, true ) ); permanentCLComposite = new CertificateListComposite( tabFolder, SWT.NONE ); permanentCLComposite.setInput( ConnectionCorePlugin.getDefault().getPermanentTrustStoreManager() ); TabItem permanentTab = new TabItem( tabFolder, SWT.NONE, 0 ); permanentTab.setText( Messages.getString( "CertificateValidationPreferencePage.PermanentTrusted" ) ); permanentTab.setControl( permanentCLComposite ); sessionCLComposite = new CertificateListComposite( tabFolder, SWT.NONE ); sessionCLComposite.setInput( ConnectionCorePlugin.getDefault().getSessionTrustStoreManager() ); TabItem sessionTab = new TabItem( tabFolder, SWT.NONE, 1 ); sessionTab.setText( Messages.getString( "CertificateValidationPreferencePage.TemporaryTrusted" ) ); sessionTab.setControl( sessionCLComposite ); tabFolder.setEnabled( verifyCertificatesButton.getSelection() ); return composite; }
public String loadForm(HttpServletRequest request, ModelMap model, @RequestParam(value = "action", required = false) String action, @RequestParam(value = "fromDate", required = false) Long fromDate, @RequestParam(value = "toDate", required = false) Long toDate, @RequestParam(value = "appointmentBlockId", required = false) Integer appointmentBlockId) { if (Context.isAuthenticated()) { if (request.getAttribute("calendarContent") != null) { String calendarContentAsString = "'" + (String) request.getAttribute("calendarContent") + "'"; model.addAttribute("calendarContent", calendarContentAsString); } else { if (action != null && action.equals("addNewAppointmentBlock")) { String getRequest = ""; Calendar cal = OpenmrsUtil.getDateTimeFormat(Context.getLocale()).getCalendar(); cal.setTimeInMillis(fromDate); Date fromDateAsDate = cal.getTime(); getRequest += "startDate=" + Context.getDateTimeFormat().format(fromDateAsDate); if (toDate != null) { cal.setTimeInMillis(toDate); Date toDateAsDate = cal.getTime(); getRequest += "&endDate=" + Context.getDateTimeFormat().format(toDateAsDate); } getRequest += "&redirectedFrom=appointmentBlockCalendar.list"; return "redirect:appointmentBlockForm.form?" + getRequest; } else if (action != null && action.equals("editAppointmentBlock")) { return "redirect:appointmentBlockForm.form?appointmentBlockId=" + appointmentBlockId + "&redirectedFrom=appointmentBlockCalendar.list"; } } } return null; }
public String loadForm(HttpServletRequest request, ModelMap model, @RequestParam(value = "action", required = false) String action, @RequestParam(value = "fromDate", required = false) Long fromDate, @RequestParam(value = "toDate", required = false) Long toDate, @RequestParam(value = "appointmentBlockId", required = false) Integer appointmentBlockId) { if (Context.isAuthenticated()) { if (request.getAttribute("calendarContent") != null) { String calendarContentAsString = "'" + (String) request.getAttribute("calendarContent") + "'"; model.addAttribute("calendarContent", calendarContentAsString); } else { if (action != null && action.equals("addNewAppointmentBlock")) { String getRequest = ""; Calendar cal = OpenmrsUtil.getDateTimeFormat(Context.getLocale()).getCalendar(); cal.setTimeInMillis(fromDate); Date fromDateAsDate = cal.getTime(); getRequest += "startDate=" + Context.getDateTimeFormat().format(fromDateAsDate); if (toDate != null && !toDate.equals(fromDate)) { cal.setTimeInMillis(toDate); Date toDateAsDate = cal.getTime(); getRequest += "&endDate=" + Context.getDateTimeFormat().format(toDateAsDate); } getRequest += "&redirectedFrom=appointmentBlockCalendar.list"; return "redirect:appointmentBlockForm.form?" + getRequest; } else if (action != null && action.equals("editAppointmentBlock")) { return "redirect:appointmentBlockForm.form?appointmentBlockId=" + appointmentBlockId + "&redirectedFrom=appointmentBlockCalendar.list"; } } } return null; }
public void csNewTurn(Random random, ChangeSet cs) { logger.finest("ServerColony.csNewTurn, for " + toString()); ServerPlayer owner = (ServerPlayer) getOwner(); Specification spec = getSpecification(); boolean tileDirty = false; boolean colonyDirty = false; List<FreeColGameObject> updates = new ArrayList<FreeColGameObject>(); GoodsContainer container = getGoodsContainer(); container.saveState(); java.util.Map<Object, ProductionInfo> info = getProductionAndConsumption(); TypeCountMap<GoodsType> netProduction = new TypeCountMap<GoodsType>(); for (Entry<Object, ProductionInfo> entry : info.entrySet()) { ProductionInfo productionInfo = entry.getValue(); if (entry.getKey() instanceof WorkLocation) { WorkLocation workLocation = (WorkLocation) entry.getKey(); ((ServerModelObject) workLocation).csNewTurn(random, cs); if (workLocation.getUnitCount() > 0) { for (AbstractGoods goods : productionInfo.getProduction()) { int experience = goods.getAmount() / workLocation.getUnitCount(); for (Unit unit : workLocation.getUnitList()) { unit.setExperience(unit.getExperience() + experience); cs.addPartial(See.only(owner), unit, "experience"); } } } } else if (entry.getKey() instanceof BuildQueue && !productionInfo.getConsumption().isEmpty()) { BuildQueue queue = (BuildQueue) entry.getKey(); BuildableType buildable = queue.getCurrentlyBuilding(); if (buildable instanceof UnitType) { tileDirty = buildUnit(queue, cs, random); } else if (buildable instanceof BuildingType) { colonyDirty = buildBuilding(queue, cs, updates); } else { throw new IllegalStateException("Bogus buildable: " + buildable); } buildable = csGetBuildable(cs); } for (AbstractGoods goods : productionInfo.getProduction()) { netProduction.incrementCount(goods.getType().getStoredAs(), goods.getAmount()); } for (AbstractGoods goods : productionInfo.getStorage()) { netProduction.incrementCount(goods.getType().getStoredAs(), goods.getAmount()); } for (AbstractGoods goods : productionInfo.getConsumption()) { netProduction.incrementCount(goods.getType().getStoredAs(), -goods.getAmount()); } } for (Entry<GoodsType, Integer> entry : netProduction.getValues().entrySet()) { GoodsType goodsType = entry.getKey(); int net = entry.getValue(); int stored = getGoodsCount(goodsType); if (net + stored < 0) { removeGoods(goodsType, stored); } else { addGoods(goodsType, net); } } int storedFood = getGoodsCount(spec.getPrimaryFoodType()); if (storedFood <= 0) { if (getUnitCount() > 1) { Unit victim = Utils.getRandomMember(logger, "Choose starver", getUnitList(), random); updates.add((FreeColGameObject) victim.getLocation()); cs.addDispose(owner, this, victim); cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.UNIT_LOST, "model.colony.colonistStarved", this) .addName("%colony%", getName())); } else { cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.UNIT_LOST, "model.colony.colonyStarved", this) .addName("%colony%", getName())); cs.addDispose(owner, getTile(), this); return; } } else { int netFood = netProduction.getCount(spec.getPrimaryFoodType()); int turns = Math.abs(storedFood / netFood); if (netFood < 0 && turns <= 3) { cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.WARNING, "model.colony.famineFeared", this) .addName("%colony%", getName()) .addName("%number%", String.valueOf(turns))); logger.finest("Famine feared in " + getName() + " food=" + storedFood + " production=" + netFood + " turns=" + turns); } } if (hasAbility("model.ability.export")) { boolean gold = false; for (Goods goods : container.getCompactGoods()) { GoodsType type = goods.getType(); ExportData data = getExportData(type); if (data.isExported() && (owner.canTrade(goods, Market.Access.CUSTOM_HOUSE))) { int amount = goods.getAmount() - data.getExportLevel(); if (amount > 0) { owner.sell(container, type, amount, random); gold = true; } } } if (gold) { cs.addPartial(See.only(owner), owner, "gold"); } } int limit = getWarehouseCapacity(); int adjustment = limit / GoodsContainer.CARGO_SIZE; for (Goods goods : container.getCompactGoods()) { GoodsType type = goods.getType(); if (!type.isStorable()) continue; ExportData exportData = getExportData(type); int low = exportData.getLowLevel() * adjustment; int high = exportData.getHighLevel() * adjustment; int amount = goods.getAmount(); int oldAmount = container.getOldGoodsCount(type); if (amount < low && oldAmount >= low) { cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.WAREHOUSE_CAPACITY, "model.building.warehouseEmpty", this, type) .add("%goods%", type.getNameKey()) .addAmount("%level%", low) .addName("%colony%", getName())); continue; } if (type.limitIgnored()) continue; String messageId = null; int waste = 0; if (amount > limit) { waste = amount - limit; container.removeGoods(type, waste); messageId = "model.building.warehouseWaste"; } else if (amount == limit && oldAmount < limit) { messageId = "model.building.warehouseOverfull"; } else if (amount > high && oldAmount <= high) { messageId = "model.building.warehouseFull"; } if (messageId != null) { cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.WAREHOUSE_CAPACITY, messageId, this, type) .add("%goods%", type.getNameKey()) .addAmount("%waste%", waste) .addAmount("%level%", high) .addName("%colony%", getName())); } if (!(exportData.isExported() && hasAbility("model.ability.export") && owner.canTrade(type, Market.Access.CUSTOM_HOUSE)) && amount <= limit) { int loss = amount + netProduction.getCount(type) - limit; if (loss > 0) { cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.WAREHOUSE_CAPACITY, "model.building.warehouseSoonFull", this, type) .add("%goods%", goods.getNameKey()) .addName("%colony%", getName()) .addAmount("%amount%", loss)); } } } for (BuildingType buildingType : spec.getBuildingTypeList()) { if (isAutomaticBuild(buildingType)) { addBuilding(new ServerBuilding(getGame(), this, buildingType)); } } updateSoL(); if (sonsOfLiberty / 10 != oldSonsOfLiberty / 10) { cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.SONS_OF_LIBERTY, (sonsOfLiberty > oldSonsOfLiberty) ? "model.colony.SoLIncrease" : "model.colony.SoLDecrease", this, spec.getGoodsType("model.goods.bells")) .addAmount("%oldSoL%", oldSonsOfLiberty) .addAmount("%newSoL%", sonsOfLiberty) .addName("%colony%", getName())); ModelMessage govMgtMessage = checkForGovMgtChangeMessage(); if (govMgtMessage != null) { cs.addMessage(See.only(owner), govMgtMessage); } } updateProductionBonus(); if (tileDirty) { cs.add(See.perhaps(), getTile()); } else { cs.add(See.only(owner), this); } }
public void csNewTurn(Random random, ChangeSet cs) { logger.finest("ServerColony.csNewTurn, for " + toString()); ServerPlayer owner = (ServerPlayer) getOwner(); Specification spec = getSpecification(); boolean tileDirty = false; boolean colonyDirty = false; List<FreeColGameObject> updates = new ArrayList<FreeColGameObject>(); GoodsContainer container = getGoodsContainer(); container.saveState(); java.util.Map<Object, ProductionInfo> info = getProductionAndConsumption(); TypeCountMap<GoodsType> netProduction = new TypeCountMap<GoodsType>(); for (Entry<Object, ProductionInfo> entry : info.entrySet()) { ProductionInfo productionInfo = entry.getValue(); if (entry.getKey() instanceof WorkLocation) { WorkLocation workLocation = (WorkLocation) entry.getKey(); ((ServerModelObject) workLocation).csNewTurn(random, cs); if (workLocation.getUnitCount() > 0) { for (AbstractGoods goods : productionInfo.getProduction()) { int experience = goods.getAmount() / workLocation.getUnitCount(); for (Unit unit : workLocation.getUnitList()) { unit.setExperience(unit.getExperience() + experience); cs.addPartial(See.only(owner), unit, "experience"); } } } } else if (entry.getKey() instanceof BuildQueue && !productionInfo.getConsumption().isEmpty()) { BuildQueue queue = (BuildQueue) entry.getKey(); BuildableType buildable = queue.getCurrentlyBuilding(); if (buildable instanceof UnitType) { tileDirty = buildUnit(queue, cs, random); } else if (buildable instanceof BuildingType) { colonyDirty = buildBuilding(queue, cs, updates); } else { throw new IllegalStateException("Bogus buildable: " + buildable); } buildable = csGetBuildable(cs); } for (AbstractGoods goods : productionInfo.getProduction()) { netProduction.incrementCount(goods.getType().getStoredAs(), goods.getAmount()); } for (AbstractGoods goods : productionInfo.getStorage()) { netProduction.incrementCount(goods.getType().getStoredAs(), goods.getAmount()); } for (AbstractGoods goods : productionInfo.getConsumption()) { netProduction.incrementCount(goods.getType().getStoredAs(), -goods.getAmount()); } } for (Entry<GoodsType, Integer> entry : netProduction.getValues().entrySet()) { GoodsType goodsType = entry.getKey(); int net = entry.getValue(); int stored = getGoodsCount(goodsType); if (net + stored < 0) { removeGoods(goodsType, stored); } else { addGoods(goodsType, net); } } int storedFood = getGoodsCount(spec.getPrimaryFoodType()); if (storedFood <= 0) { if (getUnitCount() > 1) { Unit victim = Utils.getRandomMember(logger, "Choose starver", getUnitList(), random); updates.add((FreeColGameObject) victim.getLocation()); cs.addDispose(owner, this, victim); cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.UNIT_LOST, "model.colony.colonistStarved", this) .addName("%colony%", getName())); } else { cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.UNIT_LOST, "model.colony.colonyStarved", this) .addName("%colony%", getName())); cs.addDispose(owner, getTile(), this); return; } } else { int netFood = netProduction.getCount(spec.getPrimaryFoodType()); int turns; if (netFood < 0 && (turns = storedFood / -netFood) <= 3) { cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.WARNING, "model.colony.famineFeared", this) .addName("%colony%", getName()) .addName("%number%", String.valueOf(turns))); logger.finest("Famine feared in " + getName() + " food=" + storedFood + " production=" + netFood + " turns=" + turns); } } if (hasAbility("model.ability.export")) { boolean gold = false; for (Goods goods : container.getCompactGoods()) { GoodsType type = goods.getType(); ExportData data = getExportData(type); if (data.isExported() && (owner.canTrade(goods, Market.Access.CUSTOM_HOUSE))) { int amount = goods.getAmount() - data.getExportLevel(); if (amount > 0) { owner.sell(container, type, amount, random); gold = true; } } } if (gold) { cs.addPartial(See.only(owner), owner, "gold"); } } int limit = getWarehouseCapacity(); int adjustment = limit / GoodsContainer.CARGO_SIZE; for (Goods goods : container.getCompactGoods()) { GoodsType type = goods.getType(); if (!type.isStorable()) continue; ExportData exportData = getExportData(type); int low = exportData.getLowLevel() * adjustment; int high = exportData.getHighLevel() * adjustment; int amount = goods.getAmount(); int oldAmount = container.getOldGoodsCount(type); if (amount < low && oldAmount >= low) { cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.WAREHOUSE_CAPACITY, "model.building.warehouseEmpty", this, type) .add("%goods%", type.getNameKey()) .addAmount("%level%", low) .addName("%colony%", getName())); continue; } if (type.limitIgnored()) continue; String messageId = null; int waste = 0; if (amount > limit) { waste = amount - limit; container.removeGoods(type, waste); messageId = "model.building.warehouseWaste"; } else if (amount == limit && oldAmount < limit) { messageId = "model.building.warehouseOverfull"; } else if (amount > high && oldAmount <= high) { messageId = "model.building.warehouseFull"; } if (messageId != null) { cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.WAREHOUSE_CAPACITY, messageId, this, type) .add("%goods%", type.getNameKey()) .addAmount("%waste%", waste) .addAmount("%level%", high) .addName("%colony%", getName())); } if (!(exportData.isExported() && hasAbility("model.ability.export") && owner.canTrade(type, Market.Access.CUSTOM_HOUSE)) && amount <= limit) { int loss = amount + netProduction.getCount(type) - limit; if (loss > 0) { cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.WAREHOUSE_CAPACITY, "model.building.warehouseSoonFull", this, type) .add("%goods%", goods.getNameKey()) .addName("%colony%", getName()) .addAmount("%amount%", loss)); } } } for (BuildingType buildingType : spec.getBuildingTypeList()) { if (isAutomaticBuild(buildingType)) { addBuilding(new ServerBuilding(getGame(), this, buildingType)); } } updateSoL(); if (sonsOfLiberty / 10 != oldSonsOfLiberty / 10) { cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.SONS_OF_LIBERTY, (sonsOfLiberty > oldSonsOfLiberty) ? "model.colony.SoLIncrease" : "model.colony.SoLDecrease", this, spec.getGoodsType("model.goods.bells")) .addAmount("%oldSoL%", oldSonsOfLiberty) .addAmount("%newSoL%", sonsOfLiberty) .addName("%colony%", getName())); ModelMessage govMgtMessage = checkForGovMgtChangeMessage(); if (govMgtMessage != null) { cs.addMessage(See.only(owner), govMgtMessage); } } updateProductionBonus(); if (tileDirty) { cs.add(See.perhaps(), getTile()); } else { cs.add(See.only(owner), this); } }
public void enable(MetricRegistry registry) { if (!enabled) { return; } LogFactory.getLog(MetricsServiceImpl.class).info(this); String pool = "Catalina:type=DataSource,class=javax.sql.DataSource,name=jdbc/nuxeo"; String connector = String.format( "Catalina:type=ThreadPool,name=http-%s-%s", Framework.getProperty("nuxeo.bind.address", "0.0.0.0"), Framework.getProperty("nuxeo.bind.port", "8080")); String requestProcessor = String.format( "Catalina:type=GlobalRequestProcessor,name=http-%s-%s", Framework.getProperty("nuxeo.bind.address", "0.0.0.0"), Framework.getProperty("nuxeo.bind.port", "8080")); String manager = "Catalina:type=Manager,path=/nuxeo,host=localhost"; registerGauge(pool, "numActive", registry, "jdbc-numActive"); registerGauge(pool, "numIdle", registry, "jdbc-numIdle"); registerGauge(connector, "currentThreadCount", registry, "tomcat-currentThreadCount"); registerGauge(connector, "currentThreadsBusy", registry, "tomcat-currentThreadBusy"); registerGauge(requestProcessor, "errorCount", registry, "tomcat-errorCount"); registerGauge(requestProcessor, "requestCount", registry, "tomcat-requestCount"); registerGauge(requestProcessor, "requestCount", registry, "tomcat-processingTime"); registerGauge(manager, "activeSessions", registry, "tomcat-activeSessions"); }
public void enable(MetricRegistry registry) { if (!enabled) { return; } LogFactory.getLog(MetricsServiceImpl.class).info(this); String pool = "Catalina:type=DataSource,class=javax.sql.DataSource,name=\"jdbc/nuxeo\""; String connector = String.format( "Catalina:type=ThreadPool,name=http-%s-%s", Framework.getProperty("nuxeo.bind.address", "0.0.0.0"), Framework.getProperty("nuxeo.bind.port", "8080")); String requestProcessor = String.format( "Catalina:type=GlobalRequestProcessor,name=http-%s-%s", Framework.getProperty("nuxeo.bind.address", "0.0.0.0"), Framework.getProperty("nuxeo.bind.port", "8080")); String manager = "Catalina:type=Manager,path=/nuxeo,host=localhost"; registerGauge(pool, "numActive", registry, "jdbc-numActive"); registerGauge(pool, "numIdle", registry, "jdbc-numIdle"); registerGauge(connector, "currentThreadCount", registry, "tomcat-currentThreadCount"); registerGauge(connector, "currentThreadsBusy", registry, "tomcat-currentThreadBusy"); registerGauge(requestProcessor, "errorCount", registry, "tomcat-errorCount"); registerGauge(requestProcessor, "requestCount", registry, "tomcat-requestCount"); registerGauge(requestProcessor, "requestCount", registry, "tomcat-processingTime"); registerGauge(manager, "activeSessions", registry, "tomcat-activeSessions"); }
public void getParlamentarian(Long parlamentarianId) { fireEvent(new ShowLoadingEvent()); parlamentarianService.getParlamentarian(parlamentarianId, new AsyncCallback<Parlamentarian>() { @Override public void onFailure(Throwable caught) { fireEvent(new HideLoadingEvent()); NotificationEventParams params = new NotificationEventParams(); params.setMessage(applicationMessages.getErrorParlamentarian()); params.setType(NotificationEventType.ERROR); params.setDuration(NotificationEventParams.DURATION_SHORT); fireEvent(new NotificationEvent(params)); } @Override public void onSuccess(Parlamentarian result) { parlamentarian = result; getParlamentarianComments(); getView().setParlamentarianName(parlamentarian.toString()); getView().setShare(Window.Location.getHref(), parlamentarian.toString()); if (parlamentarian.getImage() != null) { getView().setParlamentarianImage("images/parlamentarian/large/" + parlamentarian.getImage()); } else { getView().setParlamentarianImage("images/parlamentarian/large/avatar.png"); } if (parlamentarian.getParlamentarianType() != null) { if (parlamentarian.getDistrict() != null) { getView().setParlamentarianDescription(parlamentarian.getParlamentarianType().toString() + " " + applicationMessages.getGeneralBy() + " " + parlamentarian.getDistrict().toString()); } else { getView().setParlamentarianDescription(parlamentarian.getParlamentarianType().toString()); } } if (parlamentarian.getBirthDate() != null) { getView().setParlamentarianBirthDate(DateTimeFormat.getFormat(PredefinedFormat.DATE_MEDIUM).format(parlamentarian.getBirthDate())); } if (parlamentarian.getPermanentCommissions() != null && !parlamentarian.getPermanentCommissions().isEmpty()) { StringBuilder sb = new StringBuilder(); List<Commission> commissions = new ArrayList<Commission>(parlamentarian.getPermanentCommissions()); Collections.sort(commissions, new Comparator<Commission>() { @Override public int compare(Commission o1, Commission o2) { return o1.compareTo(o2); } }); Iterator<Commission> iterator = commissions.iterator(); while (iterator.hasNext()) { sb.append(iterator.next().toString()); if (iterator.hasNext()) { sb.append(", "); } else { sb.append("."); } } getView().setParlamentarianPermanentCommissions(sb.toString()); } if (parlamentarian.getSpecialCommissions() != null && !parlamentarian.getSpecialCommissions().isEmpty()) { StringBuilder sb = new StringBuilder(); List<Commission> commissions = new ArrayList<Commission>(parlamentarian.getSpecialCommissions()); Collections.sort(commissions, new Comparator<Commission>() { @Override public int compare(Commission o1, Commission o2) { return o1.compareTo(o2); } }); Iterator<Commission> iterator = commissions.iterator(); while (iterator.hasNext()) { sb.append(iterator.next().toString()); if (iterator.hasNext()) { sb.append(", "); } else { sb.append("."); } } getView().setParlamentarianSpecialCommissions(sb.toString()); } if (parlamentarian.getParty() != null) { getView().setParlamentarianParty(parlamentarian.getParty().toString()); } if (parlamentarian.getInterestDeclarationFile() != null) { interestDeclaration = true; getView().setInterestDeclarationLink(parlamentarian.getInterestDeclarationFile()); } else { interestDeclaration = false; } if (parlamentarian.getPatrimonyDeclarationFile() != null) { patrimonyDeclaration = true; getView().setPatrimonyDeclarationLink(parlamentarian.getPatrimonyDeclarationFile()); } else { patrimonyDeclaration = false; } societyData = new ListDataProvider<Society>(new ArrayList<Society>(result.getSocieties().keySet())); societyData.addDataDisplay(getView().getSocietyTable()); stockData = new ListDataProvider<Stock>(new ArrayList<Stock>(result.getStocks().keySet())); stockData.addDataDisplay(getView().getStockTable()); Double reportedSocieties = 0d; Double unreportedSocieties = 0d; for (Boolean reported : parlamentarian.getSocieties().values()) { if (reported) { reportedSocieties++; } else { unreportedSocieties++; } } Map<String, Double> chartData = new HashMap<String, Double>(); chartData.put(applicationMessages.getSocietyReported(), 100d * reportedSocieties / (reportedSocieties + unreportedSocieties)); chartData.put(applicationMessages.getSocietyUnreported(), 100d * unreportedSocieties / (reportedSocieties + unreportedSocieties)); getView().setConsistencyChartData(chartData); if (reportedSocieties == 0d && unreportedSocieties == 0d) { getView().setConsistencyIndexImageType("images/chart_without_societies.png"); } else if (reportedSocieties == 1d && unreportedSocieties == 0d) { getView().setConsistencyIndexImageType("images/chart_all_declared.png"); } else if (reportedSocieties == 0d && unreportedSocieties == 1d) { getView().setConsistencyIndexImageType("images/chart_all_undeclared.png"); } Map<String, Double> categoryChartData = new HashMap<String, Double>(); Double numCategories = 0d; for (Society parliamentarianSociety : parlamentarian.getSocieties().keySet()) { for (Category category : parliamentarianSociety.getCategories()) { Double currentCount = categoryChartData.get(category.getName()); if (currentCount == null) { currentCount = 0d; } categoryChartData.put(category.getName(), ++currentCount); numCategories++; } } for (Stock parliamentarianStock : parlamentarian.getStocks().keySet()) { for (Category category : parliamentarianStock.getCategories()) { Double currentCount = categoryChartData.get(category.getName()); if (currentCount == null) { currentCount = 0d; } categoryChartData.put(category.getName(), ++currentCount); numCategories++; } } for (String categoryName : categoryChartData.keySet()) { categoryChartData.put(categoryName, 100d * categoryChartData.get(categoryName) / numCategories); } getView().setPerAreaChartData(categoryChartData); if (numCategories == 0d) { getView().setPerAreaImageType("images/chart_without_soc_and_stocks.png"); } fireEvent(new HideLoadingEvent()); } }); }
public void getParlamentarian(Long parlamentarianId) { fireEvent(new ShowLoadingEvent()); parlamentarianService.getParlamentarian(parlamentarianId, new AsyncCallback<Parlamentarian>() { @Override public void onFailure(Throwable caught) { fireEvent(new HideLoadingEvent()); NotificationEventParams params = new NotificationEventParams(); params.setMessage(applicationMessages.getErrorParlamentarian()); params.setType(NotificationEventType.ERROR); params.setDuration(NotificationEventParams.DURATION_SHORT); fireEvent(new NotificationEvent(params)); } @Override public void onSuccess(Parlamentarian result) { parlamentarian = result; getParlamentarianComments(); getView().setParlamentarianName(parlamentarian.toString()); getView().setShare(Window.Location.getHref(), parlamentarian.toString()); if (parlamentarian.getImage() != null) { getView().setParlamentarianImage("images/parlamentarian/large/" + parlamentarian.getImage()); } else { getView().setParlamentarianImage("images/parlamentarian/large/avatar.png"); } if (parlamentarian.getParlamentarianType() != null) { if (parlamentarian.getDistrict() != null) { getView().setParlamentarianDescription(parlamentarian.getParlamentarianType().toString() + " " + applicationMessages.getGeneralBy() + " " + parlamentarian.getDistrict().toString()); } else { getView().setParlamentarianDescription(parlamentarian.getParlamentarianType().toString()); } } if (parlamentarian.getBirthDate() != null) { getView().setParlamentarianBirthDate(DateTimeFormat.getFormat(PredefinedFormat.DATE_MEDIUM).format(parlamentarian.getBirthDate())); } if (parlamentarian.getPermanentCommissions() != null && !parlamentarian.getPermanentCommissions().isEmpty()) { StringBuilder sb = new StringBuilder(); List<Commission> commissions = new ArrayList<Commission>(parlamentarian.getPermanentCommissions()); Collections.sort(commissions, new Comparator<Commission>() { @Override public int compare(Commission o1, Commission o2) { return o1.compareTo(o2); } }); Iterator<Commission> iterator = commissions.iterator(); while (iterator.hasNext()) { sb.append(iterator.next().toString()); if (iterator.hasNext()) { sb.append(", "); } else { sb.append("."); } } getView().setParlamentarianPermanentCommissions(sb.toString()); } if (parlamentarian.getSpecialCommissions() != null && !parlamentarian.getSpecialCommissions().isEmpty()) { StringBuilder sb = new StringBuilder(); List<Commission> commissions = new ArrayList<Commission>(parlamentarian.getSpecialCommissions()); Collections.sort(commissions, new Comparator<Commission>() { @Override public int compare(Commission o1, Commission o2) { return o1.compareTo(o2); } }); Iterator<Commission> iterator = commissions.iterator(); while (iterator.hasNext()) { sb.append(iterator.next().toString()); if (iterator.hasNext()) { sb.append(", "); } else { sb.append("."); } } getView().setParlamentarianSpecialCommissions(sb.toString()); } if (parlamentarian.getParty() != null) { getView().setParlamentarianParty(parlamentarian.getParty().toString()); } if (parlamentarian.getInterestDeclarationFile() != null) { interestDeclaration = true; getView().setInterestDeclarationLink(parlamentarian.getInterestDeclarationFile()); } else { interestDeclaration = false; } if (parlamentarian.getPatrimonyDeclarationFile() != null) { patrimonyDeclaration = true; getView().setPatrimonyDeclarationLink(parlamentarian.getPatrimonyDeclarationFile()); } else { patrimonyDeclaration = false; } societyData = new ListDataProvider<Society>(new ArrayList<Society>(result.getSocieties().keySet())); societyData.addDataDisplay(getView().getSocietyTable()); stockData = new ListDataProvider<Stock>(new ArrayList<Stock>(result.getStocks().keySet())); stockData.addDataDisplay(getView().getStockTable()); Double reportedSocieties = 0d; Double unreportedSocieties = 0d; for (Boolean reported : parlamentarian.getSocieties().values()) { if (reported) { reportedSocieties++; } else { unreportedSocieties++; } } Map<String, Double> chartData = new HashMap<String, Double>(); chartData.put(applicationMessages.getSocietyReported(), 100d * reportedSocieties / (reportedSocieties + unreportedSocieties)); chartData.put(applicationMessages.getSocietyUnreported(), 100d * unreportedSocieties / (reportedSocieties + unreportedSocieties)); getView().setConsistencyChartData(chartData); if (reportedSocieties == 0d && unreportedSocieties == 0d) { getView().setConsistencyIndexImageType("images/chart_without_societies.png"); } else if (reportedSocieties > 1d && unreportedSocieties == 0d) { getView().setConsistencyIndexImageType("images/chart_all_declared.png"); } else if (reportedSocieties == 0d && unreportedSocieties > 1d) { getView().setConsistencyIndexImageType("images/chart_all_undeclared.png"); } Map<String, Double> categoryChartData = new HashMap<String, Double>(); Double numCategories = 0d; for (Society parliamentarianSociety : parlamentarian.getSocieties().keySet()) { for (Category category : parliamentarianSociety.getCategories()) { Double currentCount = categoryChartData.get(category.getName()); if (currentCount == null) { currentCount = 0d; } categoryChartData.put(category.getName(), ++currentCount); numCategories++; } } for (Stock parliamentarianStock : parlamentarian.getStocks().keySet()) { for (Category category : parliamentarianStock.getCategories()) { Double currentCount = categoryChartData.get(category.getName()); if (currentCount == null) { currentCount = 0d; } categoryChartData.put(category.getName(), ++currentCount); numCategories++; } } for (String categoryName : categoryChartData.keySet()) { categoryChartData.put(categoryName, 100d * categoryChartData.get(categoryName) / numCategories); } getView().setPerAreaChartData(categoryChartData); if (numCategories == 0d) { getView().setPerAreaImageType("images/chart_without_soc_and_stocks.png"); } fireEvent(new HideLoadingEvent()); } }); }
public void shouldSupportConcurrentCreation() throws InterruptedException { int modulo = 50; ScheduledExecutorService executorService = Executors.newScheduledThreadPool(modulo); for(int i=0;i<100000;i++) { final String str=""+ (i%modulo); executorService.execute(new Runnable() { @Override public void run() { EfficientString e = EfficientString.fromString(str); assertThat(EfficientString.fromString(str), is(e)); } }); } executorService.shutdown(); executorService.awaitTermination(2, TimeUnit.SECONDS); assertThat(EfficientString.nextIndex(), is(modulo)); }
public void shouldSupportConcurrentCreation() throws InterruptedException { int modulo = 50; int startIndex = EfficientString.nextIndex(); ScheduledExecutorService executorService = Executors.newScheduledThreadPool(modulo); for(int i=0;i<100000;i++) { final String str="shouldSupportConcurrentCreation-"+ (i%modulo); executorService.execute(new Runnable() { @Override public void run() { EfficientString e = EfficientString.fromString(str); assertThat(EfficientString.fromString(str), is(e)); } }); } executorService.shutdown(); executorService.awaitTermination(2, TimeUnit.SECONDS); assertThat(EfficientString.nextIndex()-startIndex, is(modulo)); }
public String toStartString() { if (width != null) this.addCssStyle(" width=\"" + width + "\" "); if (height != null) this.addCssStyle(" height=\"" + height + "\" "); StringBuffer sb = new StringBuffer(); sb.append("<fieldset"); sb.append(getFormattedCss()); sb.append(">"); if (this.label != null) { sb.append("<legend>"); sb.append(label); sb.append("</legend>"); } return sb.toString(); }
public String toStartString() { if (width != null) this.addCssStyle(" width:" + width + "; "); if (height != null) this.addCssStyle(" height:" + height + "; "); StringBuffer sb = new StringBuffer(); sb.append("<fieldset"); sb.append(getFormattedCss()); sb.append(">"); if (this.label != null) { sb.append("<legend>"); sb.append(label); sb.append("</legend>"); } return sb.toString(); }
public void onEnable() { System.out.println("IncompatiblePlugin"); for (int id = 0; id < net.minecraft.server.v1_5_R2.Block.byId.length; id++) { if (net.minecraft.server.v1_5_R2.Block.byId[id] == null) continue; if (net.minecraft.server.v1_5_R2.Item.byId[id] == null) { System.out.println("block "+id+" has null item: "+ net.minecraft.server.v1_5_R2.Block.byId[id]); } } System.out.println("static MinecraftServer="+ net.minecraft.server.v1_5_R2.MinecraftServer.class); try { System.out.println("reflect MinecraftServer=" + Class.forName("net.minecraft.server.v1_5_R2.MinecraftServer")); } catch (ClassNotFoundException ex) { System.out.println("reflect MinecraftServer=" + ex); ex.printStackTrace(); } StringBuffer sb = new StringBuffer(); for (Biome biome : Biome.values()) { sb.append(biome.ordinal()+"="+biome.toString()+"("+biome.name()+") "); } System.out.println("Biome ("+Biome.values().length+"): " + sb.toString()); sb = new StringBuffer(); for (EntityType entityType : EntityType.values()) { sb.append(entityType.ordinal()+"="+entityType.toString()+"("+entityType.name()+") "); } System.out.println("EntityType ("+EntityType.values().length+"): " + sb.toString()); try { System.out.println("codeSource URI="+getClass().getProtectionDomain().getCodeSource().getLocation().toURI()); System.out.println(" file = ="+new File(getClass().getProtectionDomain().getCodeSource().getLocation().toURI())); System.out.println("new canonical file = ="+(new File(getClass().getProtectionDomain().getCodeSource().getLocation().toURI())).getCanonicalFile()); } catch (Throwable t) { System.out.println("codeSource URI exception="+t); t.printStackTrace(); } System.out.println("forName SQLite"); try { Object sqlite = Class.forName("org.sqlite.SQLite").newInstance(); System.out.println("org.sqlite.SQLite newInstance="+sqlite); } catch (Throwable t) { System.out.println("t="+t); t.printStackTrace(); } ShapelessRecipe shapelessRecipe = new ShapelessRecipe(new org.bukkit.inventory.ItemStack(Material.DIRT)); shapelessRecipe.addIngredient(Material.GRASS); org.bukkit.Bukkit.addRecipe(shapelessRecipe); try { Field field = TileEntityChest.class.getDeclaredField("items"); System.out.println("field="+field); } catch (Exception ex) { ex.printStackTrace(); } try { Field field = EntityTypes.class.getDeclaredField("f"); field.setAccessible(true); Map<String, Integer> map = (Map<String, Integer>) field.get(null); for (Map.Entry<String,Integer> entry: map.entrySet()) { String mobID = entry.getKey(); int entityID = entry.getValue(); EntityType bukkitEntityType = EntityType.fromId(entityID); if (bukkitEntityType == null) { System.out.println("Missing Bukkit EntityType for entityID="+entityID+", mobID="+mobID); } else { Class bukkitEntityClass = bukkitEntityType.getEntityClass(); if (bukkitEntityClass == null) { System.out.println("Missing Bukkit getEntityClass() for entityID="+entityID+", mobID="+mobID+", bukkitEntityType="+bukkitEntityType); } } } } catch (Exception e) { Bukkit.getServer().getLogger().severe("Failed to dump entity map: " + e); e.printStackTrace(); } net.minecraft.server.v1_5_R2.PlayerConnection playerConnection = null; try { System.out.println("getPlayer = "+playerConnection.getPlayer()); } catch (NoSuchMethodError ex) { System.out.println("failed to call playerConnection.getPlayer()"); ex.printStackTrace(); } catch (NullPointerException ex) { System.out.println("playerConnection.getPlayer successful"); } for (int i = 0; i < Item.byId.length; i++) { Item nmsItem = Item.byId[i]; net.minecraft.server.v1_5_R2.Block nmsBlock = i < 4096 ? net.minecraft.server.v1_5_R2.Block.byId[i] : null; org.bukkit.Material bukkitMaterial = org.bukkit.Material.getMaterial(i); if (nmsItem == null && nmsBlock == null && bukkitMaterial == null) continue; if (bukkitMaterial == null) System.out.println("Item "+i+" = item="+nmsItem+", block="+nmsBlock+", bukkit Material="+bukkitMaterial); } System.out.println("recipe iterator.."); RecipeIterator recipeIterator = new RecipeIterator(); int nulls = 0, nonVanillaRecipes = 0; while(recipeIterator.hasNext()) { Recipe recipe = recipeIterator.next(); if (recipe instanceof ShapedRecipe || recipe instanceof ShapelessRecipe || recipe instanceof FurnaceRecipe) continue; if (recipe == null) { nulls += 1; } nonVanillaRecipes += 1; } System.out.println("null recipes? " + nulls + ", non-vanilla=" + nonVanillaRecipes); System.out.println("net.minecraft.server.v1_5_R2.MinecraftServer.currentTick = "+MinecraftServer.currentTick); System.out.println("bouncycastle="+net.minecraft.v1_5_R2.org.bouncycastle.asn1.bc.BCObjectIdentifiers.class); System.out.println("SNOW.id="+net.minecraft.server.v1_5_R2.Block.SNOW.id); Block b = Bukkit.getServer().getWorlds().get(0).getBlockAt(0, 100, 0); System.out.println("a="+((CraftChunk)b.getChunk()).getHandle().a(b.getX() & 15, b.getY(), b.getZ() & 15, 48, 0)); Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { public void run() { Block b = Bukkit.getServer().getWorlds().get(0).getBlockAt(0, 99, 0); System.out.println("a(task)="+((CraftChunk)b.getChunk()).getHandle().a(b.getX() & 15, b.getY(), b.getZ() & 15, 48, 0)); } }, 0); net.minecraft.server.v1_5_R2.WorldServer worldServer = ((CraftWorld)Bukkit.getServer().getWorlds().get(0)).getHandle(); System.out.println("calling getTileEntity on nms World"); worldServer.getTileEntity(0, 0, 0); System.out.println("nms inheritance successful"); getLogger().info("creating class inheriting from NMS..."); IInventory iInventory = new SamplePluginNMSInheritor(); getLogger().info("iInventory= "+iInventory); getLogger().info("getSize="+iInventory.getSize()); PluginManager pm = getServer().getPluginManager(); pm.registerEvents(playerListener, this); pm.registerEvents(blockListener, this); getCommand("pos").setExecutor(new SamplePosCommand()); getCommand("debug").setExecutor(new SampleDebugCommand(this)); PluginDescriptionFile pdfFile = this.getDescription(); getLogger().info( pdfFile.getName() + " version " + pdfFile.getVersion() + " is enabled!" ); }
public void onEnable() { System.out.println("IncompatiblePlugin"); for (int id = 0; id < net.minecraft.server.v1_5_R2.Block.byId.length; id++) { if (net.minecraft.server.v1_5_R2.Block.byId[id] == null) continue; if (net.minecraft.server.v1_5_R2.Item.byId[id] == null) { System.out.println("block "+id+" has null item: "+ net.minecraft.server.v1_5_R2.Block.byId[id]); } } System.out.println("static MinecraftServer="+ net.minecraft.server.v1_5_R2.MinecraftServer.class); try { System.out.println("reflect MinecraftServer=" + Class.forName("net.minecraft.server.v1_5_R2.MinecraftServer")); } catch (ClassNotFoundException ex) { System.out.println("reflect MinecraftServer=" + ex); ex.printStackTrace(); } StringBuffer sb = new StringBuffer(); for (Biome biome : Biome.values()) { sb.append(biome.ordinal()+"="+biome.toString()+"("+biome.name()+") "); } System.out.println("Biome ("+Biome.values().length+"): " + sb.toString()); sb = new StringBuffer(); for (EntityType entityType : EntityType.values()) { sb.append(entityType.ordinal()+"/"+entityType.getTypeId()+"="+entityType.toString()+"("+entityType.name()+"/"+entityType.getEntityClass()+") "); } System.out.println("EntityType ("+EntityType.values().length+"): " + sb.toString()); try { System.out.println("codeSource URI="+getClass().getProtectionDomain().getCodeSource().getLocation().toURI()); System.out.println(" file = ="+new File(getClass().getProtectionDomain().getCodeSource().getLocation().toURI())); System.out.println("new canonical file = ="+(new File(getClass().getProtectionDomain().getCodeSource().getLocation().toURI())).getCanonicalFile()); } catch (Throwable t) { System.out.println("codeSource URI exception="+t); t.printStackTrace(); } System.out.println("forName SQLite"); try { Object sqlite = Class.forName("org.sqlite.SQLite").newInstance(); System.out.println("org.sqlite.SQLite newInstance="+sqlite); } catch (Throwable t) { System.out.println("t="+t); t.printStackTrace(); } ShapelessRecipe shapelessRecipe = new ShapelessRecipe(new org.bukkit.inventory.ItemStack(Material.DIRT)); shapelessRecipe.addIngredient(Material.GRASS); org.bukkit.Bukkit.addRecipe(shapelessRecipe); try { Field field = TileEntityChest.class.getDeclaredField("items"); System.out.println("field="+field); } catch (Exception ex) { ex.printStackTrace(); } try { Field field = EntityTypes.class.getDeclaredField("f"); field.setAccessible(true); Map<String, Integer> map = (Map<String, Integer>) field.get(null); for (Map.Entry<String,Integer> entry: map.entrySet()) { String mobID = entry.getKey(); int entityID = entry.getValue(); EntityType bukkitEntityType = EntityType.fromId(entityID); if (bukkitEntityType == null) { System.out.println("Missing Bukkit EntityType for entityID="+entityID+", mobID="+mobID); } else { Class bukkitEntityClass = bukkitEntityType.getEntityClass(); if (bukkitEntityClass == null) { System.out.println("Missing Bukkit getEntityClass() for entityID="+entityID+", mobID="+mobID+", bukkitEntityType="+bukkitEntityType); } } } } catch (Exception e) { Bukkit.getServer().getLogger().severe("Failed to dump entity map: " + e); e.printStackTrace(); } net.minecraft.server.v1_5_R2.PlayerConnection playerConnection = null; try { System.out.println("getPlayer = "+playerConnection.getPlayer()); } catch (NoSuchMethodError ex) { System.out.println("failed to call playerConnection.getPlayer()"); ex.printStackTrace(); } catch (NullPointerException ex) { System.out.println("playerConnection.getPlayer successful"); } for (int i = 0; i < Item.byId.length; i++) { Item nmsItem = Item.byId[i]; net.minecraft.server.v1_5_R2.Block nmsBlock = i < 4096 ? net.minecraft.server.v1_5_R2.Block.byId[i] : null; org.bukkit.Material bukkitMaterial = org.bukkit.Material.getMaterial(i); if (nmsItem == null && nmsBlock == null && bukkitMaterial == null) continue; if (bukkitMaterial == null) System.out.println("Item "+i+" = item="+nmsItem+", block="+nmsBlock+", bukkit Material="+bukkitMaterial); } System.out.println("recipe iterator.."); RecipeIterator recipeIterator = new RecipeIterator(); int nulls = 0, nonVanillaRecipes = 0; while(recipeIterator.hasNext()) { Recipe recipe = recipeIterator.next(); if (recipe instanceof ShapedRecipe || recipe instanceof ShapelessRecipe || recipe instanceof FurnaceRecipe) continue; if (recipe == null) { nulls += 1; } nonVanillaRecipes += 1; } System.out.println("null recipes? " + nulls + ", non-vanilla=" + nonVanillaRecipes); System.out.println("net.minecraft.server.v1_5_R2.MinecraftServer.currentTick = "+MinecraftServer.currentTick); System.out.println("bouncycastle="+net.minecraft.v1_5_R2.org.bouncycastle.asn1.bc.BCObjectIdentifiers.class); System.out.println("SNOW.id="+net.minecraft.server.v1_5_R2.Block.SNOW.id); Block b = Bukkit.getServer().getWorlds().get(0).getBlockAt(0, 100, 0); System.out.println("a="+((CraftChunk)b.getChunk()).getHandle().a(b.getX() & 15, b.getY(), b.getZ() & 15, 48, 0)); Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { public void run() { Block b = Bukkit.getServer().getWorlds().get(0).getBlockAt(0, 99, 0); System.out.println("a(task)="+((CraftChunk)b.getChunk()).getHandle().a(b.getX() & 15, b.getY(), b.getZ() & 15, 48, 0)); } }, 0); net.minecraft.server.v1_5_R2.WorldServer worldServer = ((CraftWorld)Bukkit.getServer().getWorlds().get(0)).getHandle(); System.out.println("calling getTileEntity on nms World"); worldServer.getTileEntity(0, 0, 0); System.out.println("nms inheritance successful"); getLogger().info("creating class inheriting from NMS..."); IInventory iInventory = new SamplePluginNMSInheritor(); getLogger().info("iInventory= "+iInventory); getLogger().info("getSize="+iInventory.getSize()); PluginManager pm = getServer().getPluginManager(); pm.registerEvents(playerListener, this); pm.registerEvents(blockListener, this); getCommand("pos").setExecutor(new SamplePosCommand()); getCommand("debug").setExecutor(new SampleDebugCommand(this)); PluginDescriptionFile pdfFile = this.getDescription(); getLogger().info( pdfFile.getName() + " version " + pdfFile.getVersion() + " is enabled!" ); }
private ItemContentsBean getQuestionBean(ItemDataIfc item, HashMap itemGradingHash, DeliveryBean delivery, HashMap publishedAnswerHash) { ItemContentsBean itemBean = new ItemContentsBean(); itemBean.setItemData(item); itemBean.setMaxPoints(item.getScore().floatValue()); itemBean.setPoints( (float) 0); if (item.getTriesAllowed() != null) { itemBean.setTriesAllowed(item.getTriesAllowed()); } if (item.getDuration() != null) { itemBean.setDuration(item.getDuration()); } itemBean.setItemGradingDataArray ( (ArrayList) itemGradingHash.get(item.getItemId())); if (itemBean.getItemGradingDataArray().size() > 0) { itemBean.setItemGradingIdForFilePicker(((ItemGradingData) itemBean.getItemGradingDataArray().get(0)).getItemGradingId()); } Iterator i = itemBean.getItemGradingDataArray().iterator(); ArrayList itemGradingAttachmentList = new ArrayList(); while (i.hasNext()) { ItemGradingData data = (ItemGradingData) i.next(); itemBean.setGradingComment(data.getComments()); if (data.getAutoScore() != null) { itemBean.setPoints(itemBean.getExactPoints() + data.getAutoScore().floatValue()); } if (data.getAttemptsRemaining() !=null ){ itemBean.setAttemptsRemaining(data.getAttemptsRemaining()); } itemGradingAttachmentList.addAll(data.getItemGradingAttachmentList()); } itemBean.setItemGradingAttachmentList(itemGradingAttachmentList); if (item.getTypeId().equals(TypeIfc.ESSAY_QUESTION) || item.getTypeId().equals(TypeIfc.FILE_UPLOAD) || item.getTypeId().equals(TypeIfc.MULTIPLE_CHOICE_SURVEY) || item.getTypeId().equals(TypeIfc.AUDIO_RECORDING) || item.getTypeId().equals(TypeIfc.MATRIX_CHOICES_SURVEY)) { itemBean.setFeedback(item.getGeneralItemFeedback()); } else if ( itemBean.getMaxPoints()>0) { if (itemBean.getExactPoints() >= itemBean.getMaxPoints()) { itemBean.setFeedback(item.getCorrectItemFeedback()); } else { itemBean.setFeedback(item.getInCorrectItemFeedback()); } } else { ArrayList itemgradingList = itemBean.getItemGradingDataArray(); Iterator iterAnswer = itemgradingList.iterator(); boolean haswronganswer =true; HashMap fibmap = new HashMap(); int mcmc_match_counter = 0; if (iterAnswer.hasNext()){ haswronganswer =false; } int correctAnswers = 0; if ((item.getTypeId().equals(TypeIfc.MULTIPLE_CORRECT) )|| (item.getTypeId().equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION) )||(item.getTypeId().equals(TypeIfc.MATCHING) )){ Iterator itemTextIter = item.getItemTextArray().iterator(); while (itemTextIter.hasNext()){ ItemTextIfc itemText = (ItemTextIfc) itemTextIter.next(); ArrayList answerArray = itemText.getAnswerArray(); if (answerArray != null){ for (int indexAnswer =0; indexAnswer<answerArray.size(); indexAnswer++){ AnswerIfc a = (AnswerIfc) answerArray.get(indexAnswer); if (a.getIsCorrect().booleanValue()) correctAnswers++; } } } } while (iterAnswer.hasNext()) { ItemGradingIfc data = (ItemGradingIfc) iterAnswer.next(); AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(data.getPublishedAnswerId()); if (item.getTypeId().equals(TypeIfc.FILL_IN_BLANK)) { GradingService gs = new GradingService(); boolean correctanswer = gs.getFIBResult( data, fibmap, item, publishedAnswerHash); if (!correctanswer){ haswronganswer =true; break; } } else if (item.getTypeId().equals(TypeIfc.FILL_IN_NUMERIC)) { GradingService gs = new GradingService(); try { boolean correctanswer = gs.getFINResult( data, item, publishedAnswerHash); if (!correctanswer){ haswronganswer =true; break; } } catch (FormatException e) { log.debug("should not come to here"); } } else if ((item.getTypeId().equals(TypeIfc.MULTIPLE_CORRECT) )||(item.getTypeId().equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION) )||(item.getTypeId().equals(TypeIfc.MATCHING) )){ if ((answer !=null) && (answer.getIsCorrect() == null || !answer.getIsCorrect().booleanValue())){ haswronganswer =true; break; } else if (answer !=null) { mcmc_match_counter++; } } else { if ((answer !=null) && (answer.getIsCorrect() == null || !answer.getIsCorrect().booleanValue())){ haswronganswer =true; break; } } } if ((item.getTypeId().equals(TypeIfc.MULTIPLE_CORRECT) )|| (item.getTypeId().equals(TypeIfc.MATCHING) )){ if (mcmc_match_counter==correctAnswers){ haswronganswer=false; } else { haswronganswer=true; } } if (haswronganswer) { itemBean.setFeedback(item.getInCorrectItemFeedback()); } else { itemBean.setFeedback(item.getCorrectItemFeedback()); } } boolean randomize = false; i = item.getItemMetaDataSet().iterator(); while (i.hasNext()) { ItemMetaDataIfc meta = (ItemMetaDataIfc) i.next(); if (meta.getLabel().equals(ItemMetaDataIfc.RANDOMIZE)) { if (meta.getEntry().equals("true")) { randomize = true; break; } } } ArrayList myanswers = new ArrayList(); ResourceLoader rb = null; String key = ""; Iterator key1 = item.getItemTextArraySorted().iterator(); int j = 1; while (key1.hasNext()) { myanswers = new ArrayList(); ItemTextIfc text = (ItemTextIfc) key1.next(); Iterator key2 = null; if (randomize && !(item.getTypeId().equals(TypeIfc.FILL_IN_BLANK)|| item.getTypeId().equals(TypeIfc.FILL_IN_NUMERIC) || item.getTypeId().equals(TypeIfc.MATRIX_CHOICES_SURVEY)) || item.getTypeId().equals(TypeIfc.MATCHING)) { ArrayList shuffled = new ArrayList(); Iterator i1 = text.getAnswerArraySorted().iterator(); while (i1.hasNext()) { shuffled.add(i1.next()); } String agentString = ""; if (delivery.getActionMode() == DeliveryBean.GRADE_ASSESSMENT) { StudentScoresBean studentscorebean = (StudentScoresBean) ContextUtil .lookupBean("studentScores"); agentString = studentscorebean.getStudentId(); } else { agentString = getAgentString(); } Collections.shuffle(shuffled, new Random( (long) item.getText().hashCode() + (getAgentString() + "_" + item.getItemId().toString()).hashCode())); key2 = shuffled.iterator(); } else { key2 = text.getAnswerArraySorted().iterator(); } int k = 0; while (key2.hasNext()) { AnswerIfc answer = (AnswerIfc) key2.next(); if ( (answer.getText() == null || answer.getText().trim().equals("")) && (item.getTypeId().equals(TypeIfc.MULTIPLE_CHOICE) || item.getTypeId().equals(TypeIfc.MULTIPLE_CORRECT) || item.getTypeId().equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION) || item.getTypeId().equals(TypeIfc.MULTIPLE_CHOICE_SURVEY) || item.getTypeId().equals(TypeIfc.MATRIX_CHOICES_SURVEY))) { } else { if ((!item.getPartialCreditFlag() && item.getTypeId().equals(TypeIfc.MULTIPLE_CHOICE)) || item.getTypeId().equals(TypeIfc.MULTIPLE_CORRECT) || item.getTypeId().equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION) || item.getTypeId().equals(TypeIfc.MATCHING)) { answer.setLabel(Character.toString(alphabet.charAt(k++))); if (answer.getIsCorrect() != null && answer.getIsCorrect().booleanValue()) { String addition = ""; if (item.getTypeId().equals(TypeIfc.MATCHING)) { addition = Integer.toString(j++) + ":"; } if ("".equals(key)) { key += addition + answer.getLabel(); } else { key += ", " + addition + answer.getLabel(); } } } if (item.getTypeId().equals(TypeIfc.MULTIPLE_CHOICE) && item.getPartialCreditFlag()){ Float pc = Float.valueOf(answer.getPartialCredit()); if (pc == null) { pc = Float.valueOf(0f); } if(pc > 0){ if (rb == null) { rb = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.DeliveryMessages"); } String correct = rb.getString("alt_correct"); if(("").equals(key)){ key = answer.getLabel() + "&nbsp;<span style='color: green'>(" + pc + "%&nbsp;" + correct + ")</span>"; }else{ key += ",&nbsp;" + answer.getLabel() + "&nbsp;<span style='color: green'>(" + pc + "%&nbsp;" + correct + ")</span>"; } } } if (item.getTypeId().equals(TypeIfc.TRUE_FALSE) && answer.getIsCorrect() != null && answer.getIsCorrect().booleanValue()) { if (rb == null) { rb = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.DeliveryMessages"); } if (answer.getText().equalsIgnoreCase("true") || answer.getText().equalsIgnoreCase(rb.getString("true_msg"))) { key = rb.getString("true_msg"); } else { key = rb.getString("false_msg"); } } if (item.getTypeId().equals(TypeIfc.FILE_UPLOAD) || item.getTypeId().equals(TypeIfc.ESSAY_QUESTION) || item.getTypeId().equals(TypeIfc.AUDIO_RECORDING)) { key += answer.getText(); } if (item.getTypeId().equals(TypeIfc.FILL_IN_BLANK)||item.getTypeId().equals(TypeIfc.FILL_IN_NUMERIC)) { if ("".equals(key)) { key += answer.getText(); } else { key += ", " + answer.getText(); } } myanswers.add(answer); } } } itemBean.setKey(key); itemBean.setShuffledAnswers(myanswers); ArrayList answers = new ArrayList(); if (item.getTypeId().equals(TypeIfc.MULTIPLE_CHOICE) || item.getTypeId().equals(TypeIfc.MULTIPLE_CORRECT) || item.getTypeId().equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION) || item.getTypeId().equals(TypeIfc.MULTIPLE_CHOICE_SURVEY) || item.getTypeId().equals(TypeIfc.TRUE_FALSE) || item.getTypeId().equals(TypeIfc.MATCHING)) { Iterator iter = myanswers.iterator(); while (iter.hasNext()) { SelectionBean selectionBean = new SelectionBean(); selectionBean.setItemContentsBean(itemBean); AnswerIfc answer = (AnswerIfc) iter.next(); selectionBean.setAnswer(answer); if (item.getTypeId().equals(TypeIfc.TRUE_FALSE) && answer.getText().equals("true")) { answer.setText(rb.getString("true_msg")); } if (item.getTypeId().equals(TypeIfc.TRUE_FALSE) && answer.getText().equals("false")) { answer.setText(rb.getString("false_msg")); } String label = ""; if (answer.getLabel() == null) { answer.setLabel(""); } if (!answer.getLabel().equals("")) { label += answer.getLabel() + ". " + answer.getText(); } else { label = answer.getText(); } selectionBean.setResponse(false); Iterator iter1 = itemBean.getItemGradingDataArray().iterator(); while (iter1.hasNext()) { ItemGradingData data = (ItemGradingData) iter1.next(); AnswerIfc pubAnswer = (AnswerIfc) publishedAnswerHash. get(data.getPublishedAnswerId()); if (pubAnswer != null && (pubAnswer.equals(answer) || data.getPublishedAnswerId().equals(answer.getId()))) { selectionBean.setItemGradingData(data); selectionBean.setResponse(true); } } if (delivery.getFeedbackComponent() != null && delivery.getFeedback().equals("true") && delivery.getFeedbackComponent().getShowSelectionLevel()) { if (answer.getIsCorrect() == null) { selectionBean.setFeedback(answer.getGeneralAnswerFeedback()); } else if (selectionBean.getResponse() && answer.getIsCorrect().booleanValue() || !selectionBean.getResponse() && !answer.getIsCorrect().booleanValue()) { selectionBean.setFeedback(answer.getCorrectAnswerFeedback()); } else { selectionBean.setFeedback(answer.getInCorrectAnswerFeedback()); } } String description = ""; if (delivery.getFeedback().equals("true") && delivery.getFeedbackComponent().getShowCorrectResponse() && answer.getIsCorrect() != null) { description = answer.getIsCorrect().toString(); } SelectItem newItem = new SelectItem(answer.getId().toString(), label, description); if (item.getTypeId().equals(TypeIfc.TRUE_FALSE)) { answers.add(newItem); } else { answers.add(selectionBean); } } } itemBean.setAnswers(answers); itemBean.setSelectionArray(answers); if (item.getTypeId().equals(TypeIfc.MATCHING)) { populateMatching(item, itemBean, publishedAnswerHash); } else if (item.getTypeId().equals(TypeIfc.FILL_IN_BLANK)) { populateFib(item, itemBean); } else if (item.getTypeId().equals(TypeIfc.FILL_IN_NUMERIC)) { populateFin(item, itemBean); } else if (item.getTypeId().equals(TypeIfc.ESSAY_QUESTION)) { String responseText = itemBean.getResponseText(); itemBean.setResponseText(ContextUtil.stringWYSIWYG(responseText)); } else if (item.getTypeId().equals(TypeIfc.MATRIX_CHOICES_SURVEY)) { populateMatrixChoices(item, itemBean, publishedAnswerHash); } return itemBean; }
private ItemContentsBean getQuestionBean(ItemDataIfc item, HashMap itemGradingHash, DeliveryBean delivery, HashMap publishedAnswerHash) { ItemContentsBean itemBean = new ItemContentsBean(); itemBean.setItemData(item); itemBean.setMaxPoints(item.getScore().floatValue()); itemBean.setPoints( (float) 0); if (item.getTriesAllowed() != null) { itemBean.setTriesAllowed(item.getTriesAllowed()); } if (item.getDuration() != null) { itemBean.setDuration(item.getDuration()); } itemBean.setItemGradingDataArray ( (ArrayList) itemGradingHash.get(item.getItemId())); if (itemBean.getItemGradingDataArray().size() > 0) { itemBean.setItemGradingIdForFilePicker(((ItemGradingData) itemBean.getItemGradingDataArray().get(0)).getItemGradingId()); } Iterator i = itemBean.getItemGradingDataArray().iterator(); ArrayList itemGradingAttachmentList = new ArrayList(); while (i.hasNext()) { ItemGradingData data = (ItemGradingData) i.next(); itemBean.setGradingComment(data.getComments()); if (data.getAutoScore() != null) { itemBean.setPoints(itemBean.getExactPoints() + data.getAutoScore().floatValue()); } if (data.getAttemptsRemaining() !=null ){ itemBean.setAttemptsRemaining(data.getAttemptsRemaining()); } itemGradingAttachmentList.addAll(data.getItemGradingAttachmentList()); } itemBean.setItemGradingAttachmentList(itemGradingAttachmentList); if (item.getTypeId().equals(TypeIfc.ESSAY_QUESTION) || item.getTypeId().equals(TypeIfc.FILE_UPLOAD) || item.getTypeId().equals(TypeIfc.MULTIPLE_CHOICE_SURVEY) || item.getTypeId().equals(TypeIfc.AUDIO_RECORDING) || item.getTypeId().equals(TypeIfc.MATRIX_CHOICES_SURVEY)) { itemBean.setFeedback(item.getGeneralItemFeedback()); } else if ( itemBean.getMaxPoints()>0) { if (itemBean.getExactPoints() >= itemBean.getMaxPoints()) { itemBean.setFeedback(item.getCorrectItemFeedback()); } else { itemBean.setFeedback(item.getInCorrectItemFeedback()); } } else { ArrayList itemgradingList = itemBean.getItemGradingDataArray(); Iterator iterAnswer = itemgradingList.iterator(); boolean haswronganswer =true; HashMap fibmap = new HashMap(); int mcmc_match_counter = 0; if (iterAnswer.hasNext()){ haswronganswer =false; } int correctAnswers = 0; if ((item.getTypeId().equals(TypeIfc.MULTIPLE_CORRECT) )|| (item.getTypeId().equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION) )||(item.getTypeId().equals(TypeIfc.MATCHING) )){ Iterator itemTextIter = item.getItemTextArray().iterator(); while (itemTextIter.hasNext()){ ItemTextIfc itemText = (ItemTextIfc) itemTextIter.next(); ArrayList answerArray = itemText.getAnswerArray(); if (answerArray != null){ for (int indexAnswer =0; indexAnswer<answerArray.size(); indexAnswer++){ AnswerIfc a = (AnswerIfc) answerArray.get(indexAnswer); if (a.getIsCorrect().booleanValue()) correctAnswers++; } } } } while (iterAnswer.hasNext()) { ItemGradingIfc data = (ItemGradingIfc) iterAnswer.next(); AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(data.getPublishedAnswerId()); if (item.getTypeId().equals(TypeIfc.FILL_IN_BLANK)) { GradingService gs = new GradingService(); boolean correctanswer = gs.getFIBResult( data, fibmap, item, publishedAnswerHash); if (!correctanswer){ haswronganswer =true; break; } } else if (item.getTypeId().equals(TypeIfc.FILL_IN_NUMERIC)) { GradingService gs = new GradingService(); try { boolean correctanswer = gs.getFINResult( data, item, publishedAnswerHash); if (!correctanswer){ haswronganswer =true; break; } } catch (FormatException e) { log.debug("should not come to here"); } } else if ((item.getTypeId().equals(TypeIfc.MULTIPLE_CORRECT) )||(item.getTypeId().equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION) )||(item.getTypeId().equals(TypeIfc.MATCHING) )){ if ((answer !=null) && (answer.getIsCorrect() == null || !answer.getIsCorrect().booleanValue())){ haswronganswer =true; break; } else if (answer !=null) { mcmc_match_counter++; } } else { if ((answer !=null) && (answer.getIsCorrect() == null || !answer.getIsCorrect().booleanValue())){ haswronganswer =true; break; } } } if ((item.getTypeId().equals(TypeIfc.MULTIPLE_CORRECT) )|| (item.getTypeId().equals(TypeIfc.MATCHING) )){ if (mcmc_match_counter==correctAnswers){ haswronganswer=false; } else { haswronganswer=true; } } if (haswronganswer) { itemBean.setFeedback(item.getInCorrectItemFeedback()); } else { itemBean.setFeedback(item.getCorrectItemFeedback()); } } boolean randomize = false; i = item.getItemMetaDataSet().iterator(); while (i.hasNext()) { ItemMetaDataIfc meta = (ItemMetaDataIfc) i.next(); if (meta.getLabel().equals(ItemMetaDataIfc.RANDOMIZE)) { if (meta.getEntry().equals("true")) { randomize = true; break; } } } ArrayList myanswers = new ArrayList(); ResourceLoader rb = null; String key = ""; Iterator key1 = item.getItemTextArraySorted().iterator(); int j = 0; while (key1.hasNext()) { j++; myanswers = new ArrayList(); ItemTextIfc text = (ItemTextIfc) key1.next(); Iterator key2 = null; if (randomize && !(item.getTypeId().equals(TypeIfc.FILL_IN_BLANK)|| item.getTypeId().equals(TypeIfc.FILL_IN_NUMERIC) || item.getTypeId().equals(TypeIfc.MATRIX_CHOICES_SURVEY)) || item.getTypeId().equals(TypeIfc.MATCHING)) { ArrayList shuffled = new ArrayList(); Iterator i1 = text.getAnswerArraySorted().iterator(); while (i1.hasNext()) { shuffled.add(i1.next()); } String agentString = ""; if (delivery.getActionMode() == DeliveryBean.GRADE_ASSESSMENT) { StudentScoresBean studentscorebean = (StudentScoresBean) ContextUtil .lookupBean("studentScores"); agentString = studentscorebean.getStudentId(); } else { agentString = getAgentString(); } Collections.shuffle(shuffled, new Random( (long) item.getText().hashCode() + (getAgentString() + "_" + item.getItemId().toString()).hashCode())); key2 = shuffled.iterator(); } else { key2 = text.getAnswerArraySorted().iterator(); } int k = 0; while (key2.hasNext()) { AnswerIfc answer = (AnswerIfc) key2.next(); if ( (answer.getText() == null || answer.getText().trim().equals("")) && (item.getTypeId().equals(TypeIfc.MULTIPLE_CHOICE) || item.getTypeId().equals(TypeIfc.MULTIPLE_CORRECT) || item.getTypeId().equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION) || item.getTypeId().equals(TypeIfc.MULTIPLE_CHOICE_SURVEY) || item.getTypeId().equals(TypeIfc.MATRIX_CHOICES_SURVEY))) { } else { if ((!item.getPartialCreditFlag() && item.getTypeId().equals(TypeIfc.MULTIPLE_CHOICE)) || item.getTypeId().equals(TypeIfc.MULTIPLE_CORRECT) || item.getTypeId().equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION) || item.getTypeId().equals(TypeIfc.MATCHING)) { answer.setLabel(Character.toString(alphabet.charAt(k++))); if (answer.getIsCorrect() != null && answer.getIsCorrect().booleanValue()) { String addition = ""; if (item.getTypeId().equals(TypeIfc.MATCHING)) { addition = Integer.toString(j) + ":"; } if ("".equals(key)) { key += addition + answer.getLabel(); } else { key += ", " + addition + answer.getLabel(); } } } if (item.getTypeId().equals(TypeIfc.MULTIPLE_CHOICE) && item.getPartialCreditFlag()){ Float pc = Float.valueOf(answer.getPartialCredit()); if (pc == null) { pc = Float.valueOf(0f); } if(pc > 0){ if (rb == null) { rb = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.DeliveryMessages"); } String correct = rb.getString("alt_correct"); if(("").equals(key)){ key = answer.getLabel() + "&nbsp;<span style='color: green'>(" + pc + "%&nbsp;" + correct + ")</span>"; }else{ key += ",&nbsp;" + answer.getLabel() + "&nbsp;<span style='color: green'>(" + pc + "%&nbsp;" + correct + ")</span>"; } } } if (item.getTypeId().equals(TypeIfc.TRUE_FALSE) && answer.getIsCorrect() != null && answer.getIsCorrect().booleanValue()) { if (rb == null) { rb = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.DeliveryMessages"); } if (answer.getText().equalsIgnoreCase("true") || answer.getText().equalsIgnoreCase(rb.getString("true_msg"))) { key = rb.getString("true_msg"); } else { key = rb.getString("false_msg"); } } if (item.getTypeId().equals(TypeIfc.FILE_UPLOAD) || item.getTypeId().equals(TypeIfc.ESSAY_QUESTION) || item.getTypeId().equals(TypeIfc.AUDIO_RECORDING)) { key += answer.getText(); } if (item.getTypeId().equals(TypeIfc.FILL_IN_BLANK)||item.getTypeId().equals(TypeIfc.FILL_IN_NUMERIC)) { if ("".equals(key)) { key += answer.getText(); } else { key += ", " + answer.getText(); } } myanswers.add(answer); } } } itemBean.setKey(key); itemBean.setShuffledAnswers(myanswers); ArrayList answers = new ArrayList(); if (item.getTypeId().equals(TypeIfc.MULTIPLE_CHOICE) || item.getTypeId().equals(TypeIfc.MULTIPLE_CORRECT) || item.getTypeId().equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION) || item.getTypeId().equals(TypeIfc.MULTIPLE_CHOICE_SURVEY) || item.getTypeId().equals(TypeIfc.TRUE_FALSE) || item.getTypeId().equals(TypeIfc.MATCHING)) { Iterator iter = myanswers.iterator(); while (iter.hasNext()) { SelectionBean selectionBean = new SelectionBean(); selectionBean.setItemContentsBean(itemBean); AnswerIfc answer = (AnswerIfc) iter.next(); selectionBean.setAnswer(answer); if (item.getTypeId().equals(TypeIfc.TRUE_FALSE) && answer.getText().equals("true")) { answer.setText(rb.getString("true_msg")); } if (item.getTypeId().equals(TypeIfc.TRUE_FALSE) && answer.getText().equals("false")) { answer.setText(rb.getString("false_msg")); } String label = ""; if (answer.getLabel() == null) { answer.setLabel(""); } if (!answer.getLabel().equals("")) { label += answer.getLabel() + ". " + answer.getText(); } else { label = answer.getText(); } selectionBean.setResponse(false); Iterator iter1 = itemBean.getItemGradingDataArray().iterator(); while (iter1.hasNext()) { ItemGradingData data = (ItemGradingData) iter1.next(); AnswerIfc pubAnswer = (AnswerIfc) publishedAnswerHash. get(data.getPublishedAnswerId()); if (pubAnswer != null && (pubAnswer.equals(answer) || data.getPublishedAnswerId().equals(answer.getId()))) { selectionBean.setItemGradingData(data); selectionBean.setResponse(true); } } if (delivery.getFeedbackComponent() != null && delivery.getFeedback().equals("true") && delivery.getFeedbackComponent().getShowSelectionLevel()) { if (answer.getIsCorrect() == null) { selectionBean.setFeedback(answer.getGeneralAnswerFeedback()); } else if (selectionBean.getResponse() && answer.getIsCorrect().booleanValue() || !selectionBean.getResponse() && !answer.getIsCorrect().booleanValue()) { selectionBean.setFeedback(answer.getCorrectAnswerFeedback()); } else { selectionBean.setFeedback(answer.getInCorrectAnswerFeedback()); } } String description = ""; if (delivery.getFeedback().equals("true") && delivery.getFeedbackComponent().getShowCorrectResponse() && answer.getIsCorrect() != null) { description = answer.getIsCorrect().toString(); } SelectItem newItem = new SelectItem(answer.getId().toString(), label, description); if (item.getTypeId().equals(TypeIfc.TRUE_FALSE)) { answers.add(newItem); } else { answers.add(selectionBean); } } } itemBean.setAnswers(answers); itemBean.setSelectionArray(answers); if (item.getTypeId().equals(TypeIfc.MATCHING)) { populateMatching(item, itemBean, publishedAnswerHash); } else if (item.getTypeId().equals(TypeIfc.FILL_IN_BLANK)) { populateFib(item, itemBean); } else if (item.getTypeId().equals(TypeIfc.FILL_IN_NUMERIC)) { populateFin(item, itemBean); } else if (item.getTypeId().equals(TypeIfc.ESSAY_QUESTION)) { String responseText = itemBean.getResponseText(); itemBean.setResponseText(ContextUtil.stringWYSIWYG(responseText)); } else if (item.getTypeId().equals(TypeIfc.MATRIX_CHOICES_SURVEY)) { populateMatrixChoices(item, itemBean, publishedAnswerHash); } return itemBean; }
private void initComponents() { nameTextField = new JTextField(); nameTextField.requestFocusInWindow(); numberTextField = new JTextField() { @Override public String getText() { String text = super.getText(); if (!text.startsWith("+")) text = config.getCountryPrefix() + text; return text; } } ; operatorComboBox = new OperatorComboBox(); nameLabel = new JLabel(); numberLabel = new JLabel(); gatewayLabel = new JLabel(); suggestOperatorButton = new JButton(); jPanel1 = new JPanel(); countryInfoLabel = new InfoLabel(); credentialsInfoLabel = new InfoLabel(); nameTextField.setToolTipText(l10n.getString("EditContactPanel.nameTextField.toolTipText")); nameTextField.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent evt) { nameTextFieldFocusLost(evt); } }); numberTextField.setColumns(13); numberTextField.setToolTipText(l10n.getString("EditContactPanel.numberTextField.toolTipText")); numberTextField.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent evt) { numberTextFieldFocusLost(evt); } }); operatorComboBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent evt) { operatorComboBoxItemStateChanged(evt); } }); nameLabel.setLabelFor(nameTextField); Mnemonics.setLocalizedText(nameLabel, l10n.getString("EditContactPanel.nameLabel.text")); nameLabel.setToolTipText(nameTextField.getToolTipText()); numberLabel.setLabelFor(numberTextField); Mnemonics.setLocalizedText(numberLabel, l10n.getString("EditContactPanel.numberLabel.text")); numberLabel.setToolTipText(numberTextField.getToolTipText()); gatewayLabel.setLabelFor(operatorComboBox); Mnemonics.setLocalizedText(gatewayLabel, l10n.getString("EditContactPanel.gatewayLabel.text")); gatewayLabel.setToolTipText(operatorComboBox.getToolTipText()); suggestOperatorButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { suggestOperatorButtonActionPerformed(evt); } }); Mnemonics.setLocalizedText(countryInfoLabel, l10n.getString("EditContactPanel.countryInfoLabel.text")); countryInfoLabel.setVisible(false); Mnemonics.setLocalizedText(credentialsInfoLabel,l10n.getString( "EditContactPanel.credentialsInfoLabel.text")); credentialsInfoLabel.setText(MessageFormat.format( l10n.getString("EditContactPanel.credentialsInfoLabel.text"), Links.CONFIG_CREDENTIALS)); credentialsInfoLabel.setVisible(false); GroupLayout jPanel1Layout = new GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(Alignment.LEADING) .addComponent(credentialsInfoLabel, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 440, Short.MAX_VALUE) .addComponent(countryInfoLabel) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(credentialsInfoLabel) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(countryInfoLabel)) ); GroupLayout layout = new GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(Alignment.LEADING) .addComponent(jPanel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(Alignment.LEADING) .addComponent(numberLabel) .addComponent(nameLabel) .addComponent(gatewayLabel)) .addPreferredGap(ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(Alignment.LEADING) .addGroup(Alignment.TRAILING, layout.createSequentialGroup() .addComponent(operatorComboBox, GroupLayout.DEFAULT_SIZE, 295, Short.MAX_VALUE) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(suggestOperatorButton)) .addComponent(nameTextField, GroupLayout.DEFAULT_SIZE, 329, Short.MAX_VALUE) .addComponent(numberTextField, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 329, Short.MAX_VALUE)))) .addContainerGap()) ); layout.linkSize(SwingConstants.HORIZONTAL, new Component[] {gatewayLabel, nameLabel, numberLabel}); layout.setVerticalGroup( layout.createParallelGroup(Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(nameLabel) .addComponent(nameTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addPreferredGap(ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(numberLabel) .addComponent(numberTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addPreferredGap(ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(Alignment.TRAILING) .addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(gatewayLabel) .addComponent(operatorComboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addComponent(suggestOperatorButton)) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(jPanel1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addContainerGap(74, Short.MAX_VALUE)) ); layout.linkSize(SwingConstants.VERTICAL, new Component[] {nameTextField, numberTextField}); }
private void initComponents() { nameTextField = new JTextField(); nameTextField.requestFocusInWindow(); numberTextField = new JTextField() { @Override public String getText() { String text = super.getText(); if (StringUtils.isNotEmpty(text) && !text.startsWith("+")) text = config.getCountryPrefix() + text; return text; } } ; operatorComboBox = new OperatorComboBox(); nameLabel = new JLabel(); numberLabel = new JLabel(); gatewayLabel = new JLabel(); suggestOperatorButton = new JButton(); jPanel1 = new JPanel(); countryInfoLabel = new InfoLabel(); credentialsInfoLabel = new InfoLabel(); nameTextField.setToolTipText(l10n.getString("EditContactPanel.nameTextField.toolTipText")); nameTextField.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent evt) { nameTextFieldFocusLost(evt); } }); numberTextField.setColumns(13); numberTextField.setToolTipText(l10n.getString("EditContactPanel.numberTextField.toolTipText")); numberTextField.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent evt) { numberTextFieldFocusLost(evt); } }); operatorComboBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent evt) { operatorComboBoxItemStateChanged(evt); } }); nameLabel.setLabelFor(nameTextField); Mnemonics.setLocalizedText(nameLabel, l10n.getString("EditContactPanel.nameLabel.text")); nameLabel.setToolTipText(nameTextField.getToolTipText()); numberLabel.setLabelFor(numberTextField); Mnemonics.setLocalizedText(numberLabel, l10n.getString("EditContactPanel.numberLabel.text")); numberLabel.setToolTipText(numberTextField.getToolTipText()); gatewayLabel.setLabelFor(operatorComboBox); Mnemonics.setLocalizedText(gatewayLabel, l10n.getString("EditContactPanel.gatewayLabel.text")); gatewayLabel.setToolTipText(operatorComboBox.getToolTipText()); suggestOperatorButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { suggestOperatorButtonActionPerformed(evt); } }); Mnemonics.setLocalizedText(countryInfoLabel, l10n.getString("EditContactPanel.countryInfoLabel.text")); countryInfoLabel.setVisible(false); Mnemonics.setLocalizedText(credentialsInfoLabel,l10n.getString( "EditContactPanel.credentialsInfoLabel.text")); credentialsInfoLabel.setText(MessageFormat.format( l10n.getString("EditContactPanel.credentialsInfoLabel.text"), Links.CONFIG_CREDENTIALS)); credentialsInfoLabel.setVisible(false); GroupLayout jPanel1Layout = new GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(Alignment.LEADING) .addComponent(credentialsInfoLabel, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 440, Short.MAX_VALUE) .addComponent(countryInfoLabel) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(credentialsInfoLabel) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(countryInfoLabel)) ); GroupLayout layout = new GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(Alignment.LEADING) .addComponent(jPanel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(Alignment.LEADING) .addComponent(numberLabel) .addComponent(nameLabel) .addComponent(gatewayLabel)) .addPreferredGap(ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(Alignment.LEADING) .addGroup(Alignment.TRAILING, layout.createSequentialGroup() .addComponent(operatorComboBox, GroupLayout.DEFAULT_SIZE, 295, Short.MAX_VALUE) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(suggestOperatorButton)) .addComponent(nameTextField, GroupLayout.DEFAULT_SIZE, 329, Short.MAX_VALUE) .addComponent(numberTextField, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 329, Short.MAX_VALUE)))) .addContainerGap()) ); layout.linkSize(SwingConstants.HORIZONTAL, new Component[] {gatewayLabel, nameLabel, numberLabel}); layout.setVerticalGroup( layout.createParallelGroup(Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(nameLabel) .addComponent(nameTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addPreferredGap(ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(numberLabel) .addComponent(numberTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addPreferredGap(ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(Alignment.TRAILING) .addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(gatewayLabel) .addComponent(operatorComboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addComponent(suggestOperatorButton)) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(jPanel1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addContainerGap(74, Short.MAX_VALUE)) ); layout.linkSize(SwingConstants.VERTICAL, new Component[] {nameTextField, numberTextField}); }
public void failedAddInstallTemplates() throws Exception { TemplatesFolderHandler folderHandler = templatesHandler.createNewTemplatesFolderHandler(); TemplateDetails template = folderHandler.addTempalteForServiceInstallation(); String templateName = template.getTemplateName(); templatesHandler.addTemplatesToCloud(folderHandler); String templateRemotePath = getTemplateRemoteDirFullPath(templateName) + template.getTemplateFile().getName(); SSHUtils.runCommand(mngMachinesIP[0], AbstractTestSupport.OPERATION_TIMEOUT, "rm -f " + templateRemotePath, USER, PASSWORD); int plannedNumberOfRestInstances = getService().getNumberOfManagementMachines(); ProcessingUnit restPu = admin.getProcessingUnits().getProcessingUnit("rest"); AssertUtils.assertTrue("Failed to discover " + plannedNumberOfRestInstances + " before grid service container restart", restPu.waitFor(plannedNumberOfRestInstances, AbstractTestSupport.OPERATION_TIMEOUT, TimeUnit.MILLISECONDS)); final ProcessingUnitInstance restInstance = restPu.getInstances()[0]; if (restInstance.isDiscovered()) { final CountDownLatch latch = new CountDownLatch(1); ProcessingUnitInstanceRemovedEventListener eventListener = new ProcessingUnitInstanceRemovedEventListener() { @Override public void processingUnitInstanceRemoved( ProcessingUnitInstance processingUnitInstance) { if (processingUnitInstance.equals(restInstance)) { latch.countDown(); } } }; restPu.getProcessingUnitInstanceRemoved().add(eventListener); try { GsmTestUtils.restartContainer(restInstance.getGridServiceContainer(), true); org.testng.Assert.assertTrue(latch.await(AbstractTestSupport.OPERATION_TIMEOUT,TimeUnit.MILLISECONDS)); } catch (InterruptedException e) { org.testng.Assert.fail("Interrupted while killing container", e); } finally { restPu.getProcessingUnitInstanceRemoved().remove(eventListener); } } AssertUtils.assertTrue("Failed to discover " + plannedNumberOfRestInstances + " after grid service container restart", restPu.waitFor(plannedNumberOfRestInstances, AbstractTestSupport.OPERATION_TIMEOUT, TimeUnit.MILLISECONDS)); String serviceName = templateName + "_service"; String output = installServiceWithCoputeTemplate(serviceName, templateName, true); AssertUtils.assertNotNull(output); AssertUtils.assertTrue("installation with non-existent template [" + templateName + "] succeeded, output was " + output, output.contains("template [" + templateName + "] does not exist at clouds template list")); }
public void failedAddInstallTemplates() throws Exception { TemplatesFolderHandler folderHandler = templatesHandler.createNewTemplatesFolderHandler(); TemplateDetails template = folderHandler.addTempalteForServiceInstallation(); String templateName = template.getTemplateName(); templatesHandler.addTemplatesToCloud(folderHandler); String templateRemotePath = getTemplateRemoteDirFullPath(templateName) + template.getTemplateFile().getName(); SSHUtils.runCommand(mngMachinesIP[0], AbstractTestSupport.OPERATION_TIMEOUT, "rm -f " + templateRemotePath, USER, PASSWORD); int plannedNumberOfRestInstances = getService().getNumberOfManagementMachines(); ProcessingUnit restPu = admin.getProcessingUnits().getProcessingUnit("rest"); AssertUtils.assertTrue("Failed to discover " + plannedNumberOfRestInstances + " before grid service container restart", restPu.waitFor(plannedNumberOfRestInstances, AbstractTestSupport.OPERATION_TIMEOUT, TimeUnit.MILLISECONDS)); final ProcessingUnitInstance restInstance = restPu.getInstances()[0]; if (restInstance.isDiscovered()) { final CountDownLatch latch = new CountDownLatch(1); ProcessingUnitInstanceRemovedEventListener eventListener = new ProcessingUnitInstanceRemovedEventListener() { @Override public void processingUnitInstanceRemoved( ProcessingUnitInstance processingUnitInstance) { if (processingUnitInstance.equals(restInstance)) { latch.countDown(); } } }; restPu.getProcessingUnitInstanceRemoved().add(eventListener); try { GsmTestUtils.restartContainer(restInstance.getGridServiceContainer(), true); org.testng.Assert.assertTrue(latch.await(AbstractTestSupport.OPERATION_TIMEOUT,TimeUnit.MILLISECONDS)); } catch (InterruptedException e) { org.testng.Assert.fail("Interrupted while killing container", e); } finally { restPu.getProcessingUnitInstanceRemoved().remove(eventListener); } } AssertUtils.assertTrue("Failed to discover " + plannedNumberOfRestInstances + " after grid service container restart", restPu.waitFor(plannedNumberOfRestInstances, AbstractTestSupport.OPERATION_TIMEOUT, TimeUnit.MILLISECONDS)); String serviceName = templateName + "_service"; String output = installServiceWithCoputeTemplate(serviceName, templateName, true); AssertUtils.assertNotNull(output); AssertUtils.assertTrue("installation with non-existent template [" + templateName + "] succeeded, output was " + output, output.contains("template [" + templateName + "] does not exist at cloud templates list")); }
public void process(String sParam, String[] token) { String sMessage = ""; if (token[0].charAt(0) == ':') { sMessage = token[0].substring(1); } else { sMessage = token[0]; } if (myParser.getIgnoreList().matches(sMessage) > -1) { return; } ChannelClientInfo iChannelClient = null; ChannelInfo iChannel = null; ClientInfo iClient = null; sMessage = token[token.length-1]; String bits[] = sMessage.split(" ", 2); Character Char1 = Character.valueOf((char)1); String sCTCP = ""; boolean isAction = false; boolean isCTCP = false; if (sParam.equalsIgnoreCase("PRIVMSG")) { if (bits[0].equalsIgnoreCase(Char1+"ACTION") && Character.valueOf(sMessage.charAt(sMessage.length()-1)).equals(Char1)) { isAction = true; if (bits.length > 1) { sMessage = bits[1]; sMessage = sMessage.substring(0, sMessage.length()-1); } else { sMessage = ""; } } } if (!isAction) { if (Character.valueOf(sMessage.charAt(0)).equals(Char1) && Character.valueOf(sMessage.charAt(sMessage.length()-1)).equals(Char1)) { isCTCP = true; if (bits.length > 1) { sMessage = bits[1]; } else { sMessage = ""; } bits = bits[0].split(Char1.toString()); sCTCP = bits[1]; if (!sMessage.equals("")) { sMessage = sMessage.split(Char1.toString())[0]; } else { sCTCP = sCTCP.split(Char1.toString())[0]; } callDebugInfo(myParser.DEBUG_INFO, "CTCP: \"%s\" \"%s\"",sCTCP,sMessage); } } iClient = getClientInfo(token[0]); if (myParser.ALWAYS_UPDATECLIENT && iClient != null) { if (iClient.getHost().equals("")) {iClient.setUserBits(token[0],false); } } if (isValidChannelName(token[2])) { iChannel = getChannelInfo(token[2]); if (iClient != null && iChannel != null) { iChannelClient = iChannel.getUser(iClient); } if (sParam.equalsIgnoreCase("PRIVMSG")) { if (!isAction) { if (isCTCP) { callChannelCTCP(iChannel, iChannelClient, sCTCP, sMessage, token[0]); } else { callChannelMessage(iChannel, iChannelClient, sMessage, token[0]); } } else { callChannelAction(iChannel, iChannelClient, sMessage, token[0]); } } else if (sParam.equalsIgnoreCase("NOTICE")) { if (isCTCP) { callChannelCTCPReply(iChannel, iChannelClient, sCTCP, sMessage, token[0]); } else { callChannelNotice(iChannel, iChannelClient, sMessage, token[0]); } } } else if (token[2].equalsIgnoreCase(myParser.cMyself.getNickname())) { if (sParam.equalsIgnoreCase("PRIVMSG")) { if (!isAction) { if (isCTCP) { callPrivateCTCP(sCTCP, sMessage, token[0]); } else { callPrivateMessage(sMessage, token[0]); } } else { callPrivateAction(sMessage, token[0]); } } else if (sParam.equalsIgnoreCase("NOTICE")) { if (isCTCP) { callPrivateCTCPReply(sCTCP, sMessage, token[0]); } else { callPrivateNotice(sMessage, token[0]); } } } else { callDebugInfo(myParser.DEBUG_INFO, "Message for Other ("+token[2]+")"); if (sParam.equalsIgnoreCase("PRIVMSG")) { if (!isAction) { if (isCTCP) { callUnknownCTCP(sCTCP, sMessage, token[2], token[0]); } else { callUnknownMessage(sMessage, token[2], token[0]); } } else { callUnknownAction(sMessage, token[2], token[0]); } } else if (sParam.equalsIgnoreCase("NOTICE")) { if (isCTCP) { callUnknownCTCPReply(sCTCP, sMessage, token[2], token[0]); } else { callUnknownNotice(sMessage, token[2], token[0]); } } } }
public void process(String sParam, String[] token) { String sMessage = ""; if (token[0].charAt(0) == ':') { sMessage = token[0].substring(1); } else { sMessage = token[0]; } if (myParser.getIgnoreList().matches(sMessage) > -1) { return; } ChannelClientInfo iChannelClient = null; ChannelInfo iChannel = null; ClientInfo iClient = null; sMessage = token[token.length-1]; String bits[] = sMessage.split(" ", 2); Character Char1 = Character.valueOf((char)1); String sCTCP = ""; boolean isAction = false; boolean isCTCP = false; if (sParam.equalsIgnoreCase("PRIVMSG")) { if (bits[0].equalsIgnoreCase(Char1+"ACTION") && Character.valueOf(sMessage.charAt(sMessage.length()-1)).equals(Char1)) { isAction = true; if (bits.length > 1) { sMessage = bits[1]; sMessage = sMessage.substring(0, sMessage.length()-1); } else { sMessage = ""; } } } if (!isAction) { if (Character.valueOf(sMessage.charAt(0)).equals(Char1) && Character.valueOf(sMessage.charAt(sMessage.length()-1)).equals(Char1)) { isCTCP = true; if (bits.length > 1) { sMessage = bits[1]; } else { sMessage = ""; } bits = bits[0].split(Char1.toString(),2); sCTCP = bits[1]; if (!sMessage.equals("")) { sMessage = sMessage.split(Char1.toString(),2)[0]; } else { sCTCP = sCTCP.split(Char1.toString(),2)[0]; } callDebugInfo(myParser.DEBUG_INFO, "CTCP: \"%s\" \"%s\"",sCTCP,sMessage); } } iClient = getClientInfo(token[0]); if (myParser.ALWAYS_UPDATECLIENT && iClient != null) { if (iClient.getHost().equals("")) {iClient.setUserBits(token[0],false); } } if (isValidChannelName(token[2])) { iChannel = getChannelInfo(token[2]); if (iClient != null && iChannel != null) { iChannelClient = iChannel.getUser(iClient); } if (sParam.equalsIgnoreCase("PRIVMSG")) { if (!isAction) { if (isCTCP) { callChannelCTCP(iChannel, iChannelClient, sCTCP, sMessage, token[0]); } else { callChannelMessage(iChannel, iChannelClient, sMessage, token[0]); } } else { callChannelAction(iChannel, iChannelClient, sMessage, token[0]); } } else if (sParam.equalsIgnoreCase("NOTICE")) { if (isCTCP) { callChannelCTCPReply(iChannel, iChannelClient, sCTCP, sMessage, token[0]); } else { callChannelNotice(iChannel, iChannelClient, sMessage, token[0]); } } } else if (token[2].equalsIgnoreCase(myParser.cMyself.getNickname())) { if (sParam.equalsIgnoreCase("PRIVMSG")) { if (!isAction) { if (isCTCP) { callPrivateCTCP(sCTCP, sMessage, token[0]); } else { callPrivateMessage(sMessage, token[0]); } } else { callPrivateAction(sMessage, token[0]); } } else if (sParam.equalsIgnoreCase("NOTICE")) { if (isCTCP) { callPrivateCTCPReply(sCTCP, sMessage, token[0]); } else { callPrivateNotice(sMessage, token[0]); } } } else { callDebugInfo(myParser.DEBUG_INFO, "Message for Other ("+token[2]+")"); if (sParam.equalsIgnoreCase("PRIVMSG")) { if (!isAction) { if (isCTCP) { callUnknownCTCP(sCTCP, sMessage, token[2], token[0]); } else { callUnknownMessage(sMessage, token[2], token[0]); } } else { callUnknownAction(sMessage, token[2], token[0]); } } else if (sParam.equalsIgnoreCase("NOTICE")) { if (isCTCP) { callUnknownCTCPReply(sCTCP, sMessage, token[2], token[0]); } else { callUnknownNotice(sMessage, token[2], token[0]); } } } }
public boolean select(Viewer viewer, Object parentElement, Object element) { if (element instanceof IContainer) { try { IProject project = ((IContainer) element).getProject(); if (project.isOpen() && project.hasNature(RegistryArtifactConstants.GENERAL_PROJECT_NATURE)) { return true; } } catch (Exception e) { log.warn(e); } } return false; }
public boolean select(Viewer viewer, Object parentElement, Object element) { if (element instanceof IContainer) { try { IContainer iContainer = (IContainer) element; IProject project = iContainer.getProject(); if (!iContainer.getFullPath().toPortableString().endsWith("/target")) { if (project.isOpen() && project.hasNature(RegistryArtifactConstants.GENERAL_PROJECT_NATURE)) { return true; } }else{ return false; } } catch (Exception e) { log.warn(e); } } return false; }
public static void createCell(CellServerState state) throws CellCreationException { if (state == null) { logger.fine("Creating cell with null server state. Returning."); return; } ViewManager vm = ViewManager.getViewManager(); ViewCell viewCell = vm.getPrimaryViewCell(); CellTransform viewTransform = viewCell.getWorldTransform(); ServerSessionManager manager = viewCell.getCellCache().getSession().getSessionManager(); CellTransform transform = null; BoundingVolumeHint hint = state.getBoundingVolumeHint(); logger.info("Using bounding volume hint " + hint.getBoundsHint() + ", do placement=" + hint.isDoSystemPlacement()); if (hint != null && hint.isDoSystemPlacement() == true) { BoundingVolume boundsHint = hint.getBoundsHint(); transform = CellPlacementUtils.getCellTransform(manager, boundsHint, viewTransform); } else if (hint == null) { BoundingVolume boundsHint = new BoundingSphere(DEFAULT_RADIUS, Vector3f.ZERO); transform = CellPlacementUtils.getCellTransform(manager, boundsHint, viewTransform); } else if (hint != null && hint.isDoSystemPlacement() == false) { transform = new CellTransform(); } CellID parentID = null; Cell parent = CellCreationParentRegistry.getCellCreationParent(); if (parent != null) { parentID = parent.getCellID(); logger.info("Using parent with Cell ID " + parentID.toString()); } if (parentID != null) { CellTransform worldTransform = new CellTransform(null, null); CellTransform parentTransform = parent.getWorldTransform(); logger.info("Transform of the parent cell: translation=" + parentTransform.getTranslation(null).toString() + ", rotation=" + parentTransform.getRotation(null).toString()); transform = CellPlacementUtils.transform(transform, worldTransform, parentTransform); } logger.info("Final adjusted origin " + transform.getTranslation(null).toString()); PositionComponentServerState position = new PositionComponentServerState(); position.setTranslation(transform.getTranslation(null)); position.setRotation(transform.getRotation(null)); position.setScaling(transform.getScaling(null)); state.addComponentServerState(position); if (hint != null && hint.isDoSystemPlacement() == false) { state.addComponentServerState(new ViewComponentServerState(viewTransform)); } WonderlandSession session = manager.getPrimarySession(); CellEditChannelConnection connection = (CellEditChannelConnection) session.getConnection(CellEditConnectionType.CLIENT_TYPE); CellCreateMessage msg = new CellCreateMessage(parentID, state); connection.send(msg); }
public static void createCell(CellServerState state) throws CellCreationException { if (state == null) { logger.fine("Creating cell with null server state. Returning."); return; } ViewManager vm = ViewManager.getViewManager(); ViewCell viewCell = vm.getPrimaryViewCell(); CellTransform viewTransform = viewCell.getWorldTransform(); ServerSessionManager manager = viewCell.getCellCache().getSession().getSessionManager(); CellTransform transform = null; BoundingVolumeHint hint = state.getBoundingVolumeHint(); logger.info("Using bounding volume hint " + hint.getBoundsHint() + ", do placement=" + hint.isDoSystemPlacement()); if (hint != null && hint.isDoSystemPlacement() == true) { BoundingVolume boundsHint = hint.getBoundsHint(); transform = CellPlacementUtils.getCellTransform(manager, boundsHint, viewTransform); } else if (hint == null) { BoundingVolume boundsHint = new BoundingSphere(DEFAULT_RADIUS, Vector3f.ZERO); transform = CellPlacementUtils.getCellTransform(manager, boundsHint, viewTransform); } else if (hint != null && hint.isDoSystemPlacement() == false) { transform = new CellTransform(); } CellID parentID = null; Cell parent = CellCreationParentRegistry.getCellCreationParent(); if (parent != null) { parentID = parent.getCellID(); logger.info("Using parent with Cell ID " + parentID.toString()); } if (parentID != null) { CellTransform worldTransform = new CellTransform(null, null); CellTransform parentTransform = parent.getWorldTransform(); logger.info("Transform of the parent cell: translation=" + parentTransform.getTranslation(null).toString() + ", rotation=" + parentTransform.getRotation(null).toString()); transform = CellPlacementUtils.transform(transform, worldTransform, parentTransform); } logger.info("Final adjusted origin " + transform.getTranslation(null).toString()); PositionComponentServerState position = new PositionComponentServerState(); position.setTranslation(transform.getTranslation(null)); position.setRotation(transform.getRotation(null)); position.setScaling(transform.getScaling(null)); state.addComponentServerState(position); state.addComponentServerState(new ViewComponentServerState(viewTransform)); WonderlandSession session = manager.getPrimarySession(); CellEditChannelConnection connection = (CellEditChannelConnection) session.getConnection(CellEditConnectionType.CLIENT_TYPE); CellCreateMessage msg = new CellCreateMessage(parentID, state); connection.send(msg); }
private void sendMessage(HTTPRequest req, ToadletContext ctx, PageNode page) throws ToadletContextClosedException, IOException { Set<String> identities = new HashSet<String>(); Bucket b = req.getPart("to"); BufferedReader data; try { data = new BufferedReader(new InputStreamReader(b.getInputStream(), "UTF-8")); } catch(UnsupportedEncodingException e) { throw new AssertionError(); } catch(IOException e) { throw new AssertionError(); } String line = data.readLine(); while(line != null) { String[] parts = line.split("\\s"); for(String part : parts) { identities.add(part); } line = data.readLine(); } IdentityMatcher messageSender = new IdentityMatcher(wotConnection); Map<String, List<Identity>> matches; try { EnumSet<IdentityMatcher.MatchMethod> methods = EnumSet.allOf(IdentityMatcher.MatchMethod.class); matches = messageSender.matchIdentities(identities, sessionManager.useSession(ctx).getUserID(), methods); } catch(PluginNotFoundException e) { addWoTNotLoadedMessage(page.content); writeHTMLReply(ctx, 200, "OK", page.outer.generate()); return; } List<String> failedRecipients = new LinkedList<String>(); for(Map.Entry<String, List<Identity>> entry : matches.entrySet()) { if(entry.getValue().size() != 1) { failedRecipients.add(entry.getKey()); } } if(failedRecipients.size() != 0) { HTMLNode pageNode = page.outer; HTMLNode contentNode = page.content; HTMLNode errorBox = addErrorbox(contentNode, FreemailL10n.getString("Freemail.NewMessageToadlet.ambigiousIdentitiesTitle")); HTMLNode errorPara = errorBox.addChild("p", FreemailL10n.getString("Freemail.NewMessageToadlet.ambigiousIdentities", "count", "" + failedRecipients.size())); HTMLNode identityList = errorPara.addChild("ul"); for(String s : failedRecipients) { identityList.addChild("li", s); } writeHTMLReply(ctx, 200, "OK", pageNode.generate()); return; } SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy HH:mm:ss Z"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); String dateHeader = "Date: " + sdf.format(new Date()) + "\r\n"; FreemailAccount account = freemail.getAccountManager().getAccount(sessionManager.useSession(ctx).getUserID()); Bucket messageHeader = new ArrayBucket( ("Subject: " + getBucketAsString(req.getPart("subject")) + "\r\n" + "From: " + account.getNickname() + " <" + account.getNickname() + "@" + account.getDomain() + ".freemail>\r\n" + "To: " + getBucketAsString(b) + "\r\n" + dateHeader + "Message-ID: <" + UUID.randomUUID() + "@" + account.getDomain() + ">\r\n" + "\r\n").getBytes("UTF-8")); Bucket messageText = req.getPart("message-text"); Bucket message = new ArrayBucket(); OutputStream messageOutputStream = message.getOutputStream(); BucketTools.copyTo(messageHeader, messageOutputStream, -1); BucketTools.copyTo(messageText, messageOutputStream, -1); messageOutputStream.close(); List<Identity> recipients = new LinkedList<Identity>(); for(List<Identity> identityList : matches.values()) { assert (identityList.size() == 1); recipients.add(identityList.get(0)); } account.getMessageHandler().sendMessage(recipients, message); message.free(); HTMLNode pageNode = page.outer; HTMLNode contentNode = page.content; HTMLNode infobox = addInfobox(contentNode, FreemailL10n.getString("Freemail.NewMessageToadlet.messageQueuedTitle")); infobox.addChild("p", FreemailL10n.getString("Freemail.NewMessageToadlet.messageQueued")); writeHTMLReply(ctx, 200, "OK", pageNode.generate()); }
private void sendMessage(HTTPRequest req, ToadletContext ctx, PageNode page) throws ToadletContextClosedException, IOException { Set<String> identities = new HashSet<String>(); Bucket b = req.getPart("to"); BufferedReader data; try { data = new BufferedReader(new InputStreamReader(b.getInputStream(), "UTF-8")); } catch(UnsupportedEncodingException e) { throw new AssertionError(); } catch(IOException e) { throw new AssertionError(); } String line = data.readLine(); while(line != null) { String[] parts = line.split("\\s"); for(String part : parts) { identities.add(part); } line = data.readLine(); } IdentityMatcher messageSender = new IdentityMatcher(wotConnection); Map<String, List<Identity>> matches; try { EnumSet<IdentityMatcher.MatchMethod> methods = EnumSet.allOf(IdentityMatcher.MatchMethod.class); matches = messageSender.matchIdentities(identities, sessionManager.useSession(ctx).getUserID(), methods); } catch(PluginNotFoundException e) { addWoTNotLoadedMessage(page.content); writeHTMLReply(ctx, 200, "OK", page.outer.generate()); return; } List<String> failedRecipients = new LinkedList<String>(); for(Map.Entry<String, List<Identity>> entry : matches.entrySet()) { if(entry.getValue().size() != 1) { failedRecipients.add(entry.getKey()); } } if(failedRecipients.size() != 0) { HTMLNode pageNode = page.outer; HTMLNode contentNode = page.content; HTMLNode errorBox = addErrorbox(contentNode, FreemailL10n.getString("Freemail.NewMessageToadlet.ambigiousIdentitiesTitle")); HTMLNode errorPara = errorBox.addChild("p", FreemailL10n.getString("Freemail.NewMessageToadlet.ambigiousIdentities", "count", "" + failedRecipients.size())); HTMLNode identityList = errorPara.addChild("ul"); for(String s : failedRecipients) { identityList.addChild("li", s); } writeHTMLReply(ctx, 200, "OK", pageNode.generate()); return; } SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy HH:mm:ss Z"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); String dateHeader = "Date: " + sdf.format(new Date()) + "\r\n"; FreemailAccount account = freemail.getAccountManager().getAccount(sessionManager.useSession(ctx).getUserID()); Bucket messageHeader = new ArrayBucket( ("Subject: " + getBucketAsString(req.getPart("subject")) + "\r\n" + "From: " + account.getNickname() + " <" + account.getNickname() + "@" + account.getDomain() + ".freemail>\r\n" + "To: " + getBucketAsString(b) + "\r\n" + dateHeader + "Message-ID: <" + UUID.randomUUID() + "@" + account.getDomain() + ".freemail>\r\n" + "\r\n").getBytes("UTF-8")); Bucket messageText = req.getPart("message-text"); Bucket message = new ArrayBucket(); OutputStream messageOutputStream = message.getOutputStream(); BucketTools.copyTo(messageHeader, messageOutputStream, -1); BucketTools.copyTo(messageText, messageOutputStream, -1); messageOutputStream.close(); List<Identity> recipients = new LinkedList<Identity>(); for(List<Identity> identityList : matches.values()) { assert (identityList.size() == 1); recipients.add(identityList.get(0)); } account.getMessageHandler().sendMessage(recipients, message); message.free(); HTMLNode pageNode = page.outer; HTMLNode contentNode = page.content; HTMLNode infobox = addInfobox(contentNode, FreemailL10n.getString("Freemail.NewMessageToadlet.messageQueuedTitle")); infobox.addChild("p", FreemailL10n.getString("Freemail.NewMessageToadlet.messageQueued")); writeHTMLReply(ctx, 200, "OK", pageNode.generate()); }
protected List<File> getGuideScreenshots(File dir) { if (!dir.isDirectory()) { System.out.println("Screenshots directory missing: " + dir); return Lists.newArrayList(); } File doneFile = getDoneFileForScreenshotsDir(dir); if (doneFile.exists()) { System.out.println("Already uploaded: " + dir); System.out.println("(Delete " + dir.getAbsolutePath() + " if incorrect.)"); return Lists.newArrayList(); } List<File> images = Lists.newArrayList(dir.listFiles()); Collections.sort(images); return Lists.newArrayList( Iterators.filter(images.iterator(), new Predicate<File>() { @Override public boolean apply(File file) { return file != null && file.getName().endsWith(".png"); } })); }
protected List<File> getGuideScreenshots(File dir) { if (!dir.isDirectory()) { System.out.println("Screenshots directory missing: " + dir); return Lists.newArrayList(); } File doneFile = getDoneFileForScreenshotsDir(dir); if (doneFile.exists()) { System.out.println("Already uploaded: " + dir); System.out.println("(Delete " + doneFile.getAbsolutePath() + " if incorrect.)"); return Lists.newArrayList(); } List<File> images = Lists.newArrayList(dir.listFiles()); Collections.sort(images); return Lists.newArrayList( Iterators.filter(images.iterator(), new Predicate<File>() { @Override public boolean apply(File file) { return file != null && file.getName().endsWith(".png"); } })); }
protected Vector3f calculateForce(PhysicalObject obj) { if (obj.isNodeNull() || obj.getVelocity().length() == 0) { return new Vector3f(); } Vector3f v = new Vector3f(obj.getVelocity()); Vector3f p = new Vector3f(obj.getPosition()); p.negate(); Vector3f c = new Vector3f(); c.sub(new Vector3f(0, 1, 0), v); Quat4f r = new Quat4f(c.x, c.y, c.z, 0); r.normalize(); Vector3f com = new Vector3f(-obj.getCenterOfMass().x, -obj.getCenterOfMass().y, -obj.getCenterOfMass().z); com.negate(); Transform3D tmp = new Transform3D(); tmp.setTranslation(com); Transform3D tmp2 = new Transform3D(); tmp2.setRotation(r); com.negate(); com.add(p); tmp2.setTranslation(com); tmp2.mul(tmp); ArrayList<Vector3f> vertices = obj.getVertices(); ArrayList<Vector2f> points = new ArrayList<Vector2f>(); for (Vector3f point : vertices) { tmp2.transform(point); Vector2f newPoint = new Vector2f(point.x, point.z); if (points.size() == 0) { points.add(newPoint); } else if (newPoint.y < points.get(0).y || (newPoint.y == points.get(0).y && newPoint.x < points.get(0).x)) { Vector2f oldPoint = points.get(0); points.set(0, newPoint); points.add(oldPoint); } else { points.add(newPoint); } } List<Vector2f> hull = convexHull(points); float surfaceArea = areaOfHull(hull); float force = 0.5f * v.lengthSquared() * COEFFICIENT * surfaceArea; v.normalize(); v.scale(-force); return new Vector3f(); }
protected Vector3f calculateForce(PhysicalObject obj) { if (obj.isNodeNull() || obj.getVelocity().length() == 0) { return new Vector3f(); } Vector3f v = new Vector3f(obj.getVelocity()); Vector3f p = new Vector3f(obj.getPosition()); p.negate(); Vector3f c = new Vector3f(); c.sub(new Vector3f(0, 1, 0), v); Quat4f r = new Quat4f(c.x, c.y, c.z, 0); r.normalize(); Vector3f com = new Vector3f(-obj.getCenterOfMass().x, -obj.getCenterOfMass().y, -obj.getCenterOfMass().z); com.negate(); Transform3D tmp = new Transform3D(); tmp.setTranslation(com); Transform3D tmp2 = new Transform3D(); tmp2.setRotation(r); com.negate(); com.add(p); tmp2.setTranslation(com); tmp2.mul(tmp); ArrayList<Vector3f> vertices = obj.getVertices(); ArrayList<Vector2f> points = new ArrayList<Vector2f>(); for (Vector3f point : vertices) { tmp2.transform(point); Vector2f newPoint = new Vector2f(point.x, point.z); if (points.size() == 0) { points.add(newPoint); } else if (newPoint.y < points.get(0).y || (newPoint.y == points.get(0).y && newPoint.x < points.get(0).x)) { Vector2f oldPoint = points.get(0); points.set(0, newPoint); points.add(oldPoint); } else { points.add(newPoint); } } List<Vector2f> hull = convexHull(points); float surfaceArea = areaOfHull(hull); float force = 0.5f * v.lengthSquared() * COEFFICIENT * surfaceArea; v.normalize(); v.scale(-force); return v; }
public void exitExpressionMethodExpressionList(JavaParser.ExpressionMethodExpressionListContext ctx) { String[] ss = ctx.getText().split("\\."); currentCall = currentCall + " )"; if(ss.length == 1) { currentCallClass = classID; currentCall = ss[0].replaceAll("\\(.*\\)", "") + currentCall; } else { currentCallClass = getVariableType(ss[ss.length-2]); if(currentCallClass == null) { currentCallClass = getCurrentCallClassType(prevCallClass, prevCall); currentCall = currentCall.replace(prevCall, "("); } currentCall = ss[ss.length-1].replaceAll("\\(.*\\)", "") + currentCall; } graph.addEdge(classID, methodID, currentCallClass, currentCall); prevCall = currentCall; prevCallClass = currentCallClass; }
public void exitExpressionMethodExpressionList(JavaParser.ExpressionMethodExpressionListContext ctx) { String[] ss = ctx.getText().split("\\."); currentCall = currentCall + " )"; if(ss.length == 1) { currentCallClass = classID; currentCall = ss[0].replaceAll("\\(.*\\)", "") + currentCall; } else { currentCallClass = getVariableType(ss[ss.length-2]); if(currentCallClass == null && prevCall != null) { currentCallClass = getCurrentCallClassType(prevCallClass, prevCall); currentCall = currentCall.replace(prevCall, "("); } currentCall = ss[ss.length-1].replaceAll("\\(.*\\)", "") + currentCall; } graph.addEdge(classID, methodID, currentCallClass, currentCall); prevCall = currentCall; prevCallClass = currentCallClass; }
public void testBadRequestStringsDescribeSensor() { System.out.println("\n------" + getCurrentMethod() + "------"); try { String valid_response_format = URLEncoder.encode("text/xml;subtype=\"sensorML/1.0.1\"", "UTF-8"); NetcdfDataset dataset = NetcdfDataset.openDataset(baseLocalDir + bad_requests_set); SOSParser parser = new SOSParser(); Writer writer = new CharArrayWriter(); String testOut = null; writeOutput(parser.enhanceGETRequest(dataset, baseQuery + bad_request_control_query, bad_requests_set), writer); fileWriter(outputDir, getCurrentMethod() + ".xml", writer, false); assertFalse("exception in output", writer.toString().contains("Exception")); writer.close(); writer = new CharArrayWriter(); writeOutput(parser.enhanceGETRequest(dataset, bad_request_responseformat_query + "&" + bad_request_control_query, bad_requests_set), writer); fileWriter(outputDir, getCurrentMethod() + ".xml", writer, true); testOut = writer.toString(); assertTrue("no exception in output - bad_request_responseformat_query", testOut.contains("Exception")); assertTrue("unexpected exception - bad_request_responseformat_query", testOut.contains("responseFormat")); writer.close(); writer = new CharArrayWriter(); writeOutput(parser.enhanceGETRequest(dataset, bad_request_responseformat_mispelled_query + valid_response_format + "&" + bad_request_control_query, bad_requests_set), writer); fileWriter(outputDir, getCurrentMethod() + ".xml", writer, true); testOut = writer.toString(); assertTrue("no exception in output - bad_request_responseformat_mispelled_query", testOut.contains("Exception")); assertTrue("unexpected exception - bad_request_responseformat_mispelled_query", testOut.contains("responseformat")); writer.close(); writer = new CharArrayWriter(); writeOutput(parser.enhanceGETRequest(dataset, bad_request_request_query + valid_response_format + "&" + bad_request_control_query, bad_requests_set), writer); fileWriter(outputDir, getCurrentMethod() + ".xml", writer, true); testOut = writer.toString(); assertTrue("no exception in output - bad_request_request_query", testOut.contains("Exception")); assertTrue("unexpected exception - bad_request_request_query", testOut.contains("Error in request.")); writer.close(); writer = new CharArrayWriter(); writeOutput(parser.enhanceGETRequest(dataset, bad_request_request_mispelled_query + valid_response_format + "&" + bad_request_control_query, bad_requests_set), writer); fileWriter(outputDir, getCurrentMethod() + ".xml", writer, true); testOut = writer.toString(); assertTrue("no exception in output - bad_request_request_mispelled_query", testOut.contains("Exception")); assertTrue("unexpected exception - bad_request_request_mispelled_query", testOut.contains("request")); writer.close(); writer = new CharArrayWriter(); writeOutput(parser.enhanceGETRequest(dataset, bad_request_version_query + valid_response_format + "&" + bad_request_control_query, bad_requests_set), writer); fileWriter(outputDir, getCurrentMethod() + ".xml", writer, true); testOut = writer.toString(); assertTrue("no exception in output - bad_request_version_query", testOut.contains("Exception")); assertTrue("unexpected exception - bad_request_version_query", testOut.contains("'version'")); writer.close(); writer = new CharArrayWriter(); writeOutput(parser.enhanceGETRequest(dataset, bad_request_version_misspelled_query + valid_response_format + "&" + bad_request_control_query, bad_requests_set), writer); fileWriter(outputDir, getCurrentMethod() + ".xml", writer, true); testOut = writer.toString(); assertTrue("no exception in output - bad_request_version_misspelled_query", testOut.contains("Exception")); assertTrue("unexpected exception - bad_request_version_misspelled_query", testOut.contains("version")); writer.close(); writer = new CharArrayWriter(); writeOutput(parser.enhanceGETRequest(dataset, bad_request_service_query + valid_response_format + "&" + bad_request_control_query, bad_requests_set), writer); fileWriter(outputDir, getCurrentMethod() + ".xml", writer, true); testOut = writer.toString(); assertTrue("no exception in output - bad_request_service_query", testOut.contains("Exception")); assertTrue("unexpected exception - bad_request_service_query", testOut.contains("service")); writer.close(); writer = new CharArrayWriter(); writeOutput(parser.enhanceGETRequest(dataset, bad_request_service_misspelled_query + valid_response_format + "&" + bad_request_control_query, bad_requests_set), writer); fileWriter(outputDir, getCurrentMethod() + ".xml", writer, true); testOut = writer.toString(); assertTrue("no exception in output - bad_request_service_misspelled_query", testOut.contains("Exception")); assertTrue("unexpected exception - bad_request_service_misspelled_query", testOut.contains("service")); writer.close(); writer = new CharArrayWriter(); writeOutput(parser.enhanceGETRequest(dataset, bad_request_procedure_query + valid_response_format, bad_requests_set), writer); fileWriter(outputDir, getCurrentMethod() + ".xml", writer, true); testOut = writer.toString(); assertTrue("no exception in output - bad_request_procedure_query", testOut.contains("Exception")); assertTrue("unexpected exception - bad_request_procedure_query", testOut.contains("procedure")); writer.close(); writer = new CharArrayWriter(); writeOutput(parser.enhanceGETRequest(dataset, bad_request_procedure_misspelled_query + valid_response_format, bad_requests_set), writer); fileWriter(outputDir, getCurrentMethod() + ".xml", writer, true); testOut = writer.toString(); assertTrue("no exception in output - bad_request_procedure_misspelled_query", testOut.contains("Exception")); assertTrue("unexpected exception - bad_request_procedure_misspelled_query", testOut.contains("procedure")); } catch (IOException ex) { System.out.println(ex.getMessage()); } finally { System.out.println("------END " + getCurrentMethod() + "------"); } }
public void testBadRequestStringsDescribeSensor() { System.out.println("\n------" + getCurrentMethod() + "------"); try { String valid_response_format = URLEncoder.encode("text/xml;subtype=\"sensorML/1.0.1\"", "UTF-8"); NetcdfDataset dataset = NetcdfDataset.openDataset(baseLocalDir + bad_requests_set); SOSParser parser = new SOSParser(); Writer writer = new CharArrayWriter(); String testOut = null; writeOutput(parser.enhanceGETRequest(dataset, baseQuery + bad_request_control_query, bad_requests_set), writer); fileWriter(outputDir, getCurrentMethod() + ".xml", writer, false); assertFalse("exception in output", writer.toString().contains("Exception")); writer.close(); writer = new CharArrayWriter(); writeOutput(parser.enhanceGETRequest(dataset, bad_request_responseformat_query + "&" + bad_request_control_query, bad_requests_set), writer); fileWriter(outputDir, getCurrentMethod() + ".xml", writer, true); testOut = writer.toString(); assertTrue("no exception in output - bad_request_responseformat_query", testOut.contains("Exception")); assertTrue("unexpected exception - bad_request_responseformat_query", testOut.contains("responseFormat")); writer.close(); writer = new CharArrayWriter(); writeOutput(parser.enhanceGETRequest(dataset, bad_request_responseformat_mispelled_query + valid_response_format + "&" + bad_request_control_query, bad_requests_set), writer); fileWriter(outputDir, getCurrentMethod() + ".xml", writer, true); testOut = writer.toString(); assertTrue("no exception in output - bad_request_responseformat_mispelled_query", testOut.contains("Exception")); assertTrue("unexpected exception - bad_request_responseformat_mispelled_query", testOut.contains("responseformat")); writer.close(); writer = new CharArrayWriter(); writeOutput(parser.enhanceGETRequest(dataset, bad_request_request_query + valid_response_format + "&" + bad_request_control_query, bad_requests_set), writer); fileWriter(outputDir, getCurrentMethod() + ".xml", writer, true); testOut = writer.toString(); assertTrue("no exception in output - bad_request_request_query", testOut.contains("Exception")); assertTrue("unexpected exception - bad_request_request_query", testOut.contains("Error in request.")); writer.close(); writer = new CharArrayWriter(); writeOutput(parser.enhanceGETRequest(dataset, bad_request_request_mispelled_query + valid_response_format + "&" + bad_request_control_query, bad_requests_set), writer); fileWriter(outputDir, getCurrentMethod() + ".xml", writer, true); testOut = writer.toString(); assertTrue("no exception in output - bad_request_request_mispelled_query", testOut.contains("Exception")); assertTrue("unexpected exception - bad_request_request_mispelled_query", testOut.contains("request")); writer.close(); writer = new CharArrayWriter(); writeOutput(parser.enhanceGETRequest(dataset, bad_request_version_query + valid_response_format + "&" + bad_request_control_query, bad_requests_set), writer); fileWriter(outputDir, getCurrentMethod() + ".xml", writer, true); testOut = writer.toString(); assertTrue("no exception in output - bad_request_version_query", testOut.contains("Exception")); assertTrue("unexpected exception - bad_request_version_query", testOut.contains("version")); writer.close(); writer = new CharArrayWriter(); writeOutput(parser.enhanceGETRequest(dataset, bad_request_version_misspelled_query + valid_response_format + "&" + bad_request_control_query, bad_requests_set), writer); fileWriter(outputDir, getCurrentMethod() + ".xml", writer, true); testOut = writer.toString(); assertTrue("no exception in output - bad_request_version_misspelled_query", testOut.contains("Exception")); assertTrue("unexpected exception - bad_request_version_misspelled_query", testOut.contains("version")); writer.close(); writer = new CharArrayWriter(); writeOutput(parser.enhanceGETRequest(dataset, bad_request_service_query + valid_response_format + "&" + bad_request_control_query, bad_requests_set), writer); fileWriter(outputDir, getCurrentMethod() + ".xml", writer, true); testOut = writer.toString(); assertTrue("no exception in output - bad_request_service_query", testOut.contains("Exception")); assertTrue("unexpected exception - bad_request_service_query", testOut.contains("service")); writer.close(); writer = new CharArrayWriter(); writeOutput(parser.enhanceGETRequest(dataset, bad_request_service_misspelled_query + valid_response_format + "&" + bad_request_control_query, bad_requests_set), writer); fileWriter(outputDir, getCurrentMethod() + ".xml", writer, true); testOut = writer.toString(); assertTrue("no exception in output - bad_request_service_misspelled_query", testOut.contains("Exception")); assertTrue("unexpected exception - bad_request_service_misspelled_query", testOut.contains("service")); writer.close(); writer = new CharArrayWriter(); writeOutput(parser.enhanceGETRequest(dataset, bad_request_procedure_query + valid_response_format, bad_requests_set), writer); fileWriter(outputDir, getCurrentMethod() + ".xml", writer, true); testOut = writer.toString(); assertTrue("no exception in output - bad_request_procedure_query", testOut.contains("Exception")); assertTrue("unexpected exception - bad_request_procedure_query", testOut.contains("procedure")); writer.close(); writer = new CharArrayWriter(); writeOutput(parser.enhanceGETRequest(dataset, bad_request_procedure_misspelled_query + valid_response_format, bad_requests_set), writer); fileWriter(outputDir, getCurrentMethod() + ".xml", writer, true); testOut = writer.toString(); assertTrue("no exception in output - bad_request_procedure_misspelled_query", testOut.contains("Exception")); assertTrue("unexpected exception - bad_request_procedure_misspelled_query", testOut.contains("procedure")); } catch (IOException ex) { System.out.println(ex.getMessage()); } finally { System.out.println("------END " + getCurrentMethod() + "------"); } }
public void saveEvaluation(EvalEvaluation evaluation, String userId) { log.debug("evalId: " + evaluation.getId() + ",userId: " + userId); evaluation.setLastModified( new Date() ); if (evaluation.getStartDate().compareTo(evaluation.getDueDate()) >= 0 ) { throw new IllegalArgumentException( "due date (" + evaluation.getDueDate() + ") must occur after start date (" + evaluation.getStartDate() + "), can occur on the same date but not at the same time"); } else if (evaluation.getDueDate().compareTo(evaluation.getStopDate()) < 0 ) { throw new IllegalArgumentException( "stop date (" + evaluation.getStopDate() + ") must occur on or after due date (" + evaluation.getDueDate() + "), can be identical"); } else if (evaluation.getViewDate().compareTo(evaluation.getStopDate()) <= 0 ) { throw new IllegalArgumentException( "view date (" + evaluation.getViewDate() + ") must occur after stop date (" + evaluation.getStopDate() + "), can occur on the same date but not at the same time"); } Calendar calendar = GregorianCalendar.getInstance(); calendar.add(Calendar.MINUTE, -15); Date today = calendar.getTime(); if (evaluation.getId() == null) { if (evaluation.getStartDate().before(today)) { throw new IllegalArgumentException( "start date (" + evaluation.getStartDate() + ") cannot occur in the past for new evaluations"); } else if (evaluation.getDueDate().before(today)) { throw new IllegalArgumentException( "due date (" + evaluation.getDueDate() + ") cannot occur in the past for new evaluations"); } else if (evaluation.getStopDate().before(today)) { throw new IllegalArgumentException( "stop date (" + evaluation.getStopDate() + ") cannot occur in the past for new evaluations"); } fixReturnEvalState(evaluation, false); if (! canBeginEvaluation(userId) ) { throw new SecurityException("User ("+userId+") attempted to create evaluation without permissions"); } } else { if (evaluation.getClass() == EvalEvaluation.class) { throw new IllegalStateException("Attempt to save non-persistent instance of Evaluation with id " + evaluation.getId() + ": to continue working with this entity you must refetch it using getEvaluationById"); } if (! canUserControlEvaluation(userId, evaluation) ) { throw new SecurityException("User ("+userId+") attempted to update existing evaluation ("+evaluation.getId()+") without permissions"); } } if (evaluation.getTemplate() == null || evaluation.getTemplate().getTemplateItems() == null || evaluation.getTemplate().getTemplateItems().size() <= 0) { throw new IllegalArgumentException("Evaluations must include a template and the template must have at least one item in it"); } if (evaluation.getLocked() == null) { evaluation.setLocked( Boolean.FALSE ); } Boolean systemBlankResponses = (Boolean) settings.get( EvalSettings.STUDENT_ALLOWED_LEAVE_UNANSWERED ); if ( systemBlankResponses == null ) { if (evaluation.getBlankResponsesAllowed() == null) { evaluation.setBlankResponsesAllowed( Boolean.FALSE ); } } else { evaluation.setBlankResponsesAllowed( systemBlankResponses ); } dao.save(evaluation); log.info("User ("+userId+") saved evaluation ("+evaluation.getId()+"), title: " + evaluation.getTitle()); if (evaluation.getLocked().booleanValue()) { log.info("Locking evaluation ("+evaluation.getId()+") and associated template ("+evaluation.getTemplate().getId()+")"); dao.lockEvaluation(evaluation); } }
public void saveEvaluation(EvalEvaluation evaluation, String userId) { log.debug("evalId: " + evaluation.getId() + ",userId: " + userId); evaluation.setLastModified( new Date() ); if (evaluation.getStartDate().compareTo(evaluation.getDueDate()) >= 0 ) { throw new IllegalArgumentException( "due date (" + evaluation.getDueDate() + ") must occur after start date (" + evaluation.getStartDate() + "), can occur on the same date but not at the same time"); } else if (evaluation.getDueDate().compareTo(evaluation.getStopDate()) < 0 ) { throw new IllegalArgumentException( "stop date (" + evaluation.getStopDate() + ") must occur on or after due date (" + evaluation.getDueDate() + "), can be identical"); } else if (evaluation.getViewDate().compareTo(evaluation.getStopDate()) <= 0 ) { throw new IllegalArgumentException( "view date (" + evaluation.getViewDate() + ") must occur after stop date (" + evaluation.getStopDate() + "), can occur on the same date but not at the same time"); } Calendar calendar = GregorianCalendar.getInstance(); calendar.add(Calendar.MINUTE, -15); Date today = calendar.getTime(); if (evaluation.getId() == null) { if (evaluation.getStartDate().before(today)) { throw new IllegalArgumentException( "start date (" + evaluation.getStartDate() + ") cannot occur in the past for new evaluations"); } else if (evaluation.getDueDate().before(today)) { throw new IllegalArgumentException( "due date (" + evaluation.getDueDate() + ") cannot occur in the past for new evaluations"); } else if (evaluation.getStopDate().before(today)) { throw new IllegalArgumentException( "stop date (" + evaluation.getStopDate() + ") cannot occur in the past for new evaluations"); } fixReturnEvalState(evaluation, false); if (! canBeginEvaluation(userId) ) { throw new SecurityException("User ("+userId+") attempted to create evaluation without permissions"); } } else { if (! canUserControlEvaluation(userId, evaluation) ) { throw new SecurityException("User ("+userId+") attempted to update existing evaluation ("+evaluation.getId()+") without permissions"); } } if (evaluation.getTemplate() == null || evaluation.getTemplate().getTemplateItems() == null || evaluation.getTemplate().getTemplateItems().size() <= 0) { throw new IllegalArgumentException("Evaluations must include a template and the template must have at least one item in it"); } if (evaluation.getLocked() == null) { evaluation.setLocked( Boolean.FALSE ); } Boolean systemBlankResponses = (Boolean) settings.get( EvalSettings.STUDENT_ALLOWED_LEAVE_UNANSWERED ); if ( systemBlankResponses == null ) { if (evaluation.getBlankResponsesAllowed() == null) { evaluation.setBlankResponsesAllowed( Boolean.FALSE ); } } else { evaluation.setBlankResponsesAllowed( systemBlankResponses ); } dao.save(evaluation); log.info("User ("+userId+") saved evaluation ("+evaluation.getId()+"), title: " + evaluation.getTitle()); if (evaluation.getLocked().booleanValue()) { log.info("Locking evaluation ("+evaluation.getId()+") and associated template ("+evaluation.getTemplate().getId()+")"); dao.lockEvaluation(evaluation); } }
private void handlePreciseCallStateChange(Connection connection) { int oldNumActive = mNumActive; int oldNumHeld = mNumHeld; Call.State oldRingingCallState = mRingingCallState; Call.State oldForegroundCallState = mForegroundCallState; CallNumber oldRingNumber = mRingNumber; Call foregroundCall = mCM.getActiveFgCall(); if (VDBG) Log.d(TAG, " handlePreciseCallStateChange: foreground: " + foregroundCall + " background: " + mCM.getFirstActiveBgCall() + " ringing: " + mCM.getFirstActiveRingingCall()); mForegroundCallState = foregroundCall.getState(); if (mForegroundCallState == Call.State.DISCONNECTING) { Log.d(TAG, "handlePreciseCallStateChange. Call disconnecting, wait before update"); return; } else mNumActive = (mForegroundCallState == Call.State.ACTIVE) ? 1 : 0; Call ringingCall = mCM.getFirstActiveRingingCall(); mRingingCallState = ringingCall.getState(); mRingNumber = getCallNumber(connection, ringingCall); if (mCM.getDefaultPhone().getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) { mNumHeld = getNumHeldCdma(); PhoneApp app = PhoneApp.getInstance(); if (app.cdmaPhoneCallState != null) { CdmaPhoneCallState.PhoneCallState currCdmaThreeWayCallState = app.cdmaPhoneCallState.getCurrentCallState(); CdmaPhoneCallState.PhoneCallState prevCdmaThreeWayCallState = app.cdmaPhoneCallState.getPreviousCallState(); log("CDMA call state: " + currCdmaThreeWayCallState + " prev state:" + prevCdmaThreeWayCallState); if (mCdmaThreeWayCallState != currCdmaThreeWayCallState) { log("CDMA 3way call state change. mNumActive: " + mNumActive + " mNumHeld: " + mNumHeld + " IsThreeWayCallOrigStateDialing: " + app.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing()); if ((currCdmaThreeWayCallState == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) && app.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing()) { mBluetoothHeadset.phoneStateChanged(0, mNumHeld, convertCallState(Call.State.IDLE, Call.State.DIALING), mRingNumber.mNumber, mRingNumber.mType); mBluetoothHeadset.phoneStateChanged(0, mNumHeld, convertCallState(Call.State.IDLE, Call.State.ALERTING), mRingNumber.mNumber, mRingNumber.mType); } if (currCdmaThreeWayCallState == CdmaPhoneCallState.PhoneCallState.CONF_CALL && prevCdmaThreeWayCallState == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) { log("CDMA 3way conf call. mNumActive: " + mNumActive + " mNumHeld: " + mNumHeld); mBluetoothHeadset.phoneStateChanged(mNumActive, mNumHeld, convertCallState(Call.State.IDLE, mForegroundCallState), mRingNumber.mNumber, mRingNumber.mType); } } mCdmaThreeWayCallState = currCdmaThreeWayCallState; } } else { mNumHeld = getNumHeldUmts(); } boolean callsSwitched = false; if (mCM.getDefaultPhone().getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA && mCdmaThreeWayCallState == CdmaPhoneCallState.PhoneCallState.CONF_CALL) { callsSwitched = mCdmaCallsSwapped; } else { Call backgroundCall = mCM.getFirstActiveBgCall(); callsSwitched = (mNumHeld == 1 && ! (backgroundCall.getEarliestConnectTime() == mBgndEarliestConnectionTime)); mBgndEarliestConnectionTime = backgroundCall.getEarliestConnectTime(); } if (mNumActive != oldNumActive || mNumHeld != oldNumHeld || mRingingCallState != oldRingingCallState || mForegroundCallState != oldForegroundCallState || !mRingNumber.equalTo(oldRingNumber) || callsSwitched) { if (mBluetoothHeadset != null) { mBluetoothHeadset.phoneStateChanged(mNumActive, mNumHeld, convertCallState(mRingingCallState, mForegroundCallState), mRingNumber.mNumber, mRingNumber.mType); } } }
private void handlePreciseCallStateChange(Connection connection) { int oldNumActive = mNumActive; int oldNumHeld = mNumHeld; Call.State oldRingingCallState = mRingingCallState; Call.State oldForegroundCallState = mForegroundCallState; CallNumber oldRingNumber = mRingNumber; Call foregroundCall = mCM.getActiveFgCall(); if (VDBG) Log.d(TAG, " handlePreciseCallStateChange: foreground: " + foregroundCall + " background: " + mCM.getFirstActiveBgCall() + " ringing: " + mCM.getFirstActiveRingingCall()); mForegroundCallState = foregroundCall.getState(); if (mForegroundCallState == Call.State.DISCONNECTING) { Log.d(TAG, "handlePreciseCallStateChange. Call disconnecting, wait before update"); return; } else mNumActive = (mForegroundCallState == Call.State.ACTIVE) ? 1 : 0; Call ringingCall = mCM.getFirstActiveRingingCall(); mRingingCallState = ringingCall.getState(); mRingNumber = getCallNumber(connection, ringingCall); if (mCM.getDefaultPhone().getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) { mNumHeld = getNumHeldCdma(); PhoneApp app = PhoneApp.getInstance(); if (app.cdmaPhoneCallState != null) { CdmaPhoneCallState.PhoneCallState currCdmaThreeWayCallState = app.cdmaPhoneCallState.getCurrentCallState(); CdmaPhoneCallState.PhoneCallState prevCdmaThreeWayCallState = app.cdmaPhoneCallState.getPreviousCallState(); log("CDMA call state: " + currCdmaThreeWayCallState + " prev state:" + prevCdmaThreeWayCallState); if ((mBluetoothHeadset != null) && (mCdmaThreeWayCallState != currCdmaThreeWayCallState)) { log("CDMA 3way call state change. mNumActive: " + mNumActive + " mNumHeld: " + mNumHeld + " IsThreeWayCallOrigStateDialing: " + app.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing()); if ((currCdmaThreeWayCallState == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) && app.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing()) { mBluetoothHeadset.phoneStateChanged(0, mNumHeld, convertCallState(Call.State.IDLE, Call.State.DIALING), mRingNumber.mNumber, mRingNumber.mType); mBluetoothHeadset.phoneStateChanged(0, mNumHeld, convertCallState(Call.State.IDLE, Call.State.ALERTING), mRingNumber.mNumber, mRingNumber.mType); } if (currCdmaThreeWayCallState == CdmaPhoneCallState.PhoneCallState.CONF_CALL && prevCdmaThreeWayCallState == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) { log("CDMA 3way conf call. mNumActive: " + mNumActive + " mNumHeld: " + mNumHeld); mBluetoothHeadset.phoneStateChanged(mNumActive, mNumHeld, convertCallState(Call.State.IDLE, mForegroundCallState), mRingNumber.mNumber, mRingNumber.mType); } } mCdmaThreeWayCallState = currCdmaThreeWayCallState; } } else { mNumHeld = getNumHeldUmts(); } boolean callsSwitched = false; if (mCM.getDefaultPhone().getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA && mCdmaThreeWayCallState == CdmaPhoneCallState.PhoneCallState.CONF_CALL) { callsSwitched = mCdmaCallsSwapped; } else { Call backgroundCall = mCM.getFirstActiveBgCall(); callsSwitched = (mNumHeld == 1 && ! (backgroundCall.getEarliestConnectTime() == mBgndEarliestConnectionTime)); mBgndEarliestConnectionTime = backgroundCall.getEarliestConnectTime(); } if (mNumActive != oldNumActive || mNumHeld != oldNumHeld || mRingingCallState != oldRingingCallState || mForegroundCallState != oldForegroundCallState || !mRingNumber.equalTo(oldRingNumber) || callsSwitched) { if (mBluetoothHeadset != null) { mBluetoothHeadset.phoneStateChanged(mNumActive, mNumHeld, convertCallState(mRingingCallState, mForegroundCallState), mRingNumber.mNumber, mRingNumber.mType); } } }
private BvhNode createTree(int left, int right) { Point3 minB = new Point3(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY); Point3 maxB = new Point3(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY); for (int i = left; i < right; i++) { Point3 surfMinB = surfaces[i].getMinBound(); Point3 surfMaxB = surfaces[i].getMaxBound(); for (int j = 0; j < 3; j++) { if (surfMinB.getE(j) < minB.getE(j)) { minB.setE(j, surfMinB.getE(j)); } if (surfMaxB.getE(j) > maxB.getE(j)) { maxB.setE(j, surfMaxB.getE(j)); } } } if (right - left == 10) { return new BvhNode(minB, maxB, null, null, left, right); } int widestDim = 0; double[] dims = new double[3]; for (int i = 0; i < 3; i++) { dims[i] = maxB.getE(i) - minB.getE(i); } for (int i = 0; i < 3; i++) { if (dims[widestDim] < dims[i]) { widestDim = i; } } cmp.setIndex(widestDim); Arrays.sort(surfaces, left, right, cmp); int mid = (right-left)/2; BvhNode leftChild = createTree(left, mid); BvhNode rightChild = createTree(mid, right); return new BvhNode(minB, maxB, leftChild, rightChild, left, right); }
private BvhNode createTree(int left, int right) { Point3 minB = new Point3(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY); Point3 maxB = new Point3(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY); for (int i = left; i < right; i++) { Point3 surfMinB = surfaces[i].getMinBound(); Point3 surfMaxB = surfaces[i].getMaxBound(); for (int j = 0; j < 3; j++) { if (surfMinB.getE(j) < minB.getE(j)) { minB.setE(j, surfMinB.getE(j)); } if (surfMaxB.getE(j) > maxB.getE(j)) { maxB.setE(j, surfMaxB.getE(j)); } } } if (right - left <= 10) { return new BvhNode(minB, maxB, null, null, left, right); } int widestDim = 0; double[] dims = new double[3]; for (int i = 0; i < 3; i++) { dims[i] = maxB.getE(i) - minB.getE(i); } for (int i = 0; i < 3; i++) { if (dims[widestDim] < dims[i]) { widestDim = i; } } cmp.setIndex(widestDim); Arrays.sort(surfaces, left, right, cmp); int mid = (right-left)/2; BvhNode leftChild = createTree(left, mid); BvhNode rightChild = createTree(mid, right); return new BvhNode(minB, maxB, leftChild, rightChild, left, right); }
public void toJava(CodeWriter w) { if (assignment_right != null) w.writeLine(assignment_left.getType().toJava() + " = " + assignment_right.toJava() + ";"); else w.writeLine(assignment_left.getType().toJava() + " " + assignment_left.toJava() + ";"); }
public void toJava(CodeWriter w) { if (assignment_right != null) w.writeLine(assignment_left.toJava() + " = " + assignment_right.toJava() + ";"); else w.writeLine(assignment_left.getType().toJava() + " " + assignment_left.toJava() + ";"); }
public int run(String[] args) throws Exception { Options options = new Options(); options.addOption(OptionBuilder.withArgName("path") .hasArg().withDescription("bz2 input path").create(INPUT)); options.addOption(OptionBuilder.withArgName("path") .hasArg().withDescription("output path").create(OUTPUT)); options.addOption(OptionBuilder.withArgName("en|sv|de|cs|es|zh|ar|tr").hasArg() .withDescription("two-letter language code").create(LANGUAGE_OPTION)); options.addOption(OptionBuilder.withArgName("num").hasArg() .withDescription("number of reducers").create(NUM_REDUCERS)); CommandLine cmdline; CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); return -1; } if (!cmdline.hasOption(INPUT) || !cmdline.hasOption(OUTPUT)) { HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); formatter.printHelp(this.getClass().getName(), options); ToolRunner.printGenericCommandUsage(System.out); return -1; } String language = "en"; if (cmdline.hasOption(LANGUAGE_OPTION)) { language = cmdline.getOptionValue(LANGUAGE_OPTION); if(language.length()!=2){ System.err.println("Error: \"" + language + "\" unknown language!"); return -1; } } String inputPath = cmdline.getOptionValue(INPUT); String outputPath = cmdline.getOptionValue(OUTPUT); int reduceTasks = cmdline.hasOption(NUM_REDUCERS) ? Integer.parseInt(cmdline.getOptionValue(NUM_REDUCERS)) : 1; LOG.info("Tool name: " + this.getClass().getName()); LOG.info(" - bz2 file: " + inputPath); LOG.info(" - output file: " + outputPath); LOG.info(" - language: " + language); JobConf conf = new JobConf(getConf(), MinhashWikipediaPages.class); conf.setJobName(String.format("MinhashWikipediaPages[%s: %s, %s: %s, %s: %s]", INPUT, inputPath, OUTPUT, outputPath, LANGUAGE_OPTION, language)); conf.setLong("rseed", 1123456); conf.setInt("NHASH", 20); conf.setInt("NHASHOUTPUTBITS", 30); conf.setInt("MINLEN", 20); conf.setInt("MAXLEN", 600); conf.setInt("K", 8); conf.setInt("N", 5); conf.setInt("SHINGLELEN",15); conf.setNumMapTasks(4); conf.setNumReduceTasks(reduceTasks); FileInputFormat.setInputPaths(conf, new Path(inputPath)); FileOutputFormat.setOutputPath(conf, new Path(outputPath)); if(language != null){ conf.set("wiki.language", language); } conf.setMapperClass(SignatureMapper.class); conf.setReducerClass(SignatureReducer.class); conf.setInputFormat(WikipediaPageInputFormat.class); conf.setOutputFormat(SequenceFileOutputFormat.class); conf.set("mapred.job.map.memory.mb", "2048"); conf.set("mapred.map.child.java.opts", "-Xmx2048m"); conf.set("mapred.job.reduce.memory.mb", "2048"); conf.set("mapred.reduce.child.java.opts", "-Xmx2048m"); conf.setMapOutputKeyClass(ArrayListOfLongsWritable.class); conf.setMapOutputValueClass(PairOfStringInt.class); conf.setOutputKeyClass(PairOfStringInt.class); conf.setOutputValueClass(PairOfStringInt.class); Path outputDir = new Path(outputPath); FileSystem.get(conf).delete(outputDir, true); JobClient.runJob(conf); return 0; }
public int run(String[] args) throws Exception { Options options = new Options(); options.addOption(OptionBuilder.withArgName("path") .hasArg().withDescription("bz2 input path").create(INPUT)); options.addOption(OptionBuilder.withArgName("path") .hasArg().withDescription("output path").create(OUTPUT)); options.addOption(OptionBuilder.withArgName("en|sv|de|cs|es|zh|ar|tr").hasArg() .withDescription("two-letter language code").create(LANGUAGE_OPTION)); options.addOption(OptionBuilder.withArgName("num").hasArg() .withDescription("number of reducers").create(NUM_REDUCERS)); CommandLine cmdline; CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); return -1; } if (!cmdline.hasOption(INPUT) || !cmdline.hasOption(OUTPUT)) { HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); formatter.printHelp(this.getClass().getName(), options); ToolRunner.printGenericCommandUsage(System.out); return -1; } String language = "en"; if (cmdline.hasOption(LANGUAGE_OPTION)) { language = cmdline.getOptionValue(LANGUAGE_OPTION); if(language.length()!=2){ System.err.println("Error: \"" + language + "\" unknown language!"); return -1; } } String inputPath = cmdline.getOptionValue(INPUT); String outputPath = cmdline.getOptionValue(OUTPUT); int reduceTasks = cmdline.hasOption(NUM_REDUCERS) ? Integer.parseInt(cmdline.getOptionValue(NUM_REDUCERS)) : 1; LOG.info("Tool name: " + this.getClass().getName()); LOG.info(" - bz2 file: " + inputPath); LOG.info(" - output file: " + outputPath); LOG.info(" - language: " + language); JobConf conf = new JobConf(getConf(), MinhashWikipediaPages.class); conf.setJobName(String.format("MinhashWikipediaPages[%s: %s, %s: %s, %s: %s]", INPUT, inputPath, OUTPUT, outputPath, LANGUAGE_OPTION, language)); conf.setLong("rseed", 1123456); conf.setInt("NHASH", 20); conf.setInt("NHASHOUTPUTBITS", 30); conf.setInt("MINLEN", 20); conf.setInt("MAXLEN", 600); conf.setInt("K", 8); conf.setInt("N", 5); conf.setInt("SHINGLELEN",15); conf.setNumMapTasks(4); conf.setNumReduceTasks(reduceTasks); FileInputFormat.setInputPaths(conf, new Path(inputPath)); FileOutputFormat.setOutputPath(conf, new Path(outputPath)); if(language != null){ conf.set("wiki.language", language); } conf.setMapperClass(SignatureMapper.class); conf.setReducerClass(SignatureReducer.class); conf.setInputFormat(WikipediaPageInputFormat.class); conf.setOutputFormat(SequenceFileOutputFormat.class); conf.set("mapred.job.map.memory.mb", "2048"); conf.set("mapred.map.child.java.opts", "-Xmx2048m"); conf.set("mapred.job.reduce.memory.mb", "2048"); conf.set("mapred.reduce.child.java.opts", "-Xmx2048m"); conf.setMapOutputKeyClass(ArrayListOfLongsWritable.class); conf.setMapOutputValueClass(PairOfStringInt.class); conf.setOutputKeyClass(ArrayListOfLongsWritable.class); conf.setOutputValueClass(ArrayListWritable.class); Path outputDir = new Path(outputPath); FileSystem.get(conf).delete(outputDir, true); JobClient.runJob(conf); return 0; }
public static String translateMessage (String message, Object... args) { if (message == null) { if (args.length > 0) { StringBuilder errorBuilder = new StringBuilder(); errorBuilder.append("A null format can't apply to arguments "); errorBuilder.append(Arrays.toString(args)); throw new MessageFormattingException(errorBuilder.toString()); } return null; } else if (args.length == 0) { return message; } else { try { return String.format(message, args); } catch (IllegalFormatException illegalFormatException) { StringBuilder errorBuilder = new StringBuilder(); errorBuilder.append("Error applying format ("); errorBuilder.append(message); errorBuilder.append(") to arguments "); errorBuilder.append(Arrays.toString(args)); throw new MessageFormattingException(illegalFormatException, errorBuilder.toString()); } } }
public static String translateMessage (String message, Object... args) { if (message == null) { if ((args != null) && (args.length > 0)) { StringBuilder errorBuilder = new StringBuilder(); errorBuilder.append("A null format can't apply to arguments "); errorBuilder.append(Arrays.toString(args)); throw new MessageFormattingException(errorBuilder.toString()); } return null; } else if ((args == null) || (args.length == 0)) { return message; } else { try { return String.format(message, args); } catch (IllegalFormatException illegalFormatException) { StringBuilder errorBuilder = new StringBuilder(); errorBuilder.append("Error applying format ("); errorBuilder.append(message); errorBuilder.append(") to arguments "); errorBuilder.append(Arrays.toString(args)); throw new MessageFormattingException(illegalFormatException, errorBuilder.toString()); } } }
public void testMuleLookup() throws Exception { AbderaClient client = new AbderaClient(abdera); String url = "http://localhost:9002/api/registry"; String search = UrlEncoding.encode("select artifact where mule2.service = 'GreeterUMO'"); url = url + "?q=" + search; RequestOptions defaultOpts = client.getDefaultRequestOptions(); defaultOpts.setAuthorization("Basic " + Base64.encode("admin:admin".getBytes())); ClientResponse res = client.get(url, defaultOpts); assertEquals(200, res.getStatus()); Document<Feed> feedDoc = res.getDocument(); List<Entry> entries = feedDoc.getRoot().getEntries(); assertEquals(1, entries.size()); Entry entry = entries.get(0); String muleConfigUrlLink = entry.getContentSrc().toString(); System.out.println(muleConfigUrlLink); res = client.get(muleConfigUrlLink, defaultOpts); assertEquals(200, res.getStatus()); InputStream is = res.getInputStream(); IOUtils.copy(is, System.out); }
public void testMuleLookup() throws Exception { AbderaClient client = new AbderaClient(abdera); String url = "http://localhost:9002/api/registry"; String search = UrlEncoding.encode("select artifact where mule.descriptor = 'GreeterUMO'"); url = url + "?q=" + search; RequestOptions defaultOpts = client.getDefaultRequestOptions(); defaultOpts.setAuthorization("Basic " + Base64.encode("admin:admin".getBytes())); ClientResponse res = client.get(url, defaultOpts); assertEquals(200, res.getStatus()); Document<Feed> feedDoc = res.getDocument(); List<Entry> entries = feedDoc.getRoot().getEntries(); assertEquals(1, entries.size()); Entry entry = entries.get(0); String muleConfigUrlLink = entry.getContentSrc().toString(); System.out.println(muleConfigUrlLink); res = client.get(muleConfigUrlLink, defaultOpts); assertEquals(200, res.getStatus()); InputStream is = res.getInputStream(); IOUtils.copy(is, System.out); }
public void handleMessage(Message msg) { switch (msg.what) { case MESSAGE_CONNECT: { BluetoothDevice device = (BluetoothDevice) msg.obj; if (!connectHidNative(Utils.getByteAddress(device)) ) { broadcastConnectionState(device, BluetoothProfile.STATE_DISCONNECTING); broadcastConnectionState(device, BluetoothProfile.STATE_DISCONNECTED); break; } } break; case MESSAGE_DISCONNECT: { BluetoothDevice device = (BluetoothDevice) msg.obj; if (!disconnectHidNative(Utils.getByteAddress(device)) ) { broadcastConnectionState(device, BluetoothProfile.STATE_DISCONNECTING); broadcastConnectionState(device, BluetoothProfile.STATE_DISCONNECTED); break; } } break; case MESSAGE_CONNECT_STATE_CHANGED: { BluetoothDevice device = getDevice((byte[]) msg.obj); int halState = msg.arg1; broadcastConnectionState(device, convertHalState(halState)); } break; case MESSAGE_GET_PROTOCOL_MODE: { BluetoothDevice device = (BluetoothDevice) msg.obj; if(!getProtocolModeNative(Utils.getByteAddress(device)) ) { Log.e(TAG, "Error: get protocol mode native returns false"); } } break; case MESSAGE_ON_GET_PROTOCOL_MODE: { BluetoothDevice device = getDevice((byte[]) msg.obj); int protocolMode = msg.arg1; broadcastProtocolMode(device, protocolMode); } break; case MESSAGE_VIRTUAL_UNPLUG: { BluetoothDevice device = (BluetoothDevice) msg.obj; if(!virtualUnPlugNative(Utils.getByteAddress(device))) { Log.e(TAG, "Error: virtual unplug native returns false"); } } break; case MESSAGE_SET_PROTOCOL_MODE: { BluetoothDevice device = (BluetoothDevice) msg.obj; byte protocolMode = (byte) msg.arg1; log("sending set protocol mode(" + protocolMode + ")"); if(!setProtocolModeNative(Utils.getByteAddress(device), protocolMode)) { Log.e(TAG, "Error: set protocol mode native returns false"); } } break; case MESSAGE_GET_REPORT: { BluetoothDevice device = (BluetoothDevice) msg.obj; Bundle data = msg.getData(); byte reportType = data.getByte(BluetoothInputDevice.EXTRA_REPORT_TYPE); byte reportId = data.getByte(BluetoothInputDevice.EXTRA_REPORT_ID); int bufferSize = data.getInt(BluetoothInputDevice.EXTRA_REPORT_BUFFER_SIZE); if(!getReportNative(Utils.getByteAddress(device), reportType, reportId, bufferSize)) { Log.e(TAG, "Error: get report native returns false"); } } break; case MESSAGE_SET_REPORT: { BluetoothDevice device = (BluetoothDevice) msg.obj; Bundle data = msg.getData(); byte reportType = data.getByte(BluetoothInputDevice.EXTRA_REPORT_TYPE); String report = data.getString(BluetoothInputDevice.EXTRA_REPORT); if(!setReportNative(Utils.getByteAddress(device), reportType, report)) { Log.e(TAG, "Error: set report native returns false"); } } break; case MESSAGE_SEND_DATA: { BluetoothDevice device = (BluetoothDevice) msg.obj; Bundle data = msg.getData(); String report = data.getString(BluetoothInputDevice.EXTRA_REPORT); if(!sendDataNative(Utils.getByteAddress(device), report)) { Log.e(TAG, "Error: send data native returns false"); } } break; case MESSAGE_ON_VIRTUAL_UNPLUG: { BluetoothDevice device = getDevice((byte[]) msg.obj); int status = msg.arg1; broadcastVirtualUnplugStatus(device, status); } break; } }
public void handleMessage(Message msg) { switch (msg.what) { case MESSAGE_CONNECT: { BluetoothDevice device = (BluetoothDevice) msg.obj; if (!connectHidNative(Utils.getByteAddress(device)) ) { broadcastConnectionState(device, BluetoothProfile.STATE_DISCONNECTING); broadcastConnectionState(device, BluetoothProfile.STATE_DISCONNECTED); break; } } break; case MESSAGE_DISCONNECT: { BluetoothDevice device = (BluetoothDevice) msg.obj; if (!disconnectHidNative(Utils.getByteAddress(device)) ) { broadcastConnectionState(device, BluetoothProfile.STATE_DISCONNECTING); broadcastConnectionState(device, BluetoothProfile.STATE_DISCONNECTED); break; } } break; case MESSAGE_CONNECT_STATE_CHANGED: { BluetoothDevice device = getDevice((byte[]) msg.obj); int halState = msg.arg1; Integer prevStateInteger = mInputDevices.get(device); int prevState = (prevStateInteger == null) ? BluetoothInputDevice.STATE_DISCONNECTED :prevStateInteger; if(DBG) Log.d(TAG, "MESSAGE_CONNECT_STATE_CHANGED newState:"+ convertHalState(halState)+", prevState:"+prevState); if(halState == CONN_STATE_CONNECTED && prevState == BluetoothInputDevice.STATE_DISCONNECTED && BluetoothProfile.PRIORITY_OFF >= getPriority(device)) { Log.d(TAG,"Incoming HID connection rejected"); disconnectHidNative(Utils.getByteAddress(device)); } else { broadcastConnectionState(device, convertHalState(halState)); } } break; case MESSAGE_GET_PROTOCOL_MODE: { BluetoothDevice device = (BluetoothDevice) msg.obj; if(!getProtocolModeNative(Utils.getByteAddress(device)) ) { Log.e(TAG, "Error: get protocol mode native returns false"); } } break; case MESSAGE_ON_GET_PROTOCOL_MODE: { BluetoothDevice device = getDevice((byte[]) msg.obj); int protocolMode = msg.arg1; broadcastProtocolMode(device, protocolMode); } break; case MESSAGE_VIRTUAL_UNPLUG: { BluetoothDevice device = (BluetoothDevice) msg.obj; if(!virtualUnPlugNative(Utils.getByteAddress(device))) { Log.e(TAG, "Error: virtual unplug native returns false"); } } break; case MESSAGE_SET_PROTOCOL_MODE: { BluetoothDevice device = (BluetoothDevice) msg.obj; byte protocolMode = (byte) msg.arg1; log("sending set protocol mode(" + protocolMode + ")"); if(!setProtocolModeNative(Utils.getByteAddress(device), protocolMode)) { Log.e(TAG, "Error: set protocol mode native returns false"); } } break; case MESSAGE_GET_REPORT: { BluetoothDevice device = (BluetoothDevice) msg.obj; Bundle data = msg.getData(); byte reportType = data.getByte(BluetoothInputDevice.EXTRA_REPORT_TYPE); byte reportId = data.getByte(BluetoothInputDevice.EXTRA_REPORT_ID); int bufferSize = data.getInt(BluetoothInputDevice.EXTRA_REPORT_BUFFER_SIZE); if(!getReportNative(Utils.getByteAddress(device), reportType, reportId, bufferSize)) { Log.e(TAG, "Error: get report native returns false"); } } break; case MESSAGE_SET_REPORT: { BluetoothDevice device = (BluetoothDevice) msg.obj; Bundle data = msg.getData(); byte reportType = data.getByte(BluetoothInputDevice.EXTRA_REPORT_TYPE); String report = data.getString(BluetoothInputDevice.EXTRA_REPORT); if(!setReportNative(Utils.getByteAddress(device), reportType, report)) { Log.e(TAG, "Error: set report native returns false"); } } break; case MESSAGE_SEND_DATA: { BluetoothDevice device = (BluetoothDevice) msg.obj; Bundle data = msg.getData(); String report = data.getString(BluetoothInputDevice.EXTRA_REPORT); if(!sendDataNative(Utils.getByteAddress(device), report)) { Log.e(TAG, "Error: send data native returns false"); } } break; case MESSAGE_ON_VIRTUAL_UNPLUG: { BluetoothDevice device = getDevice((byte[]) msg.obj); int status = msg.arg1; broadcastVirtualUnplugStatus(device, status); } break; } }
public void onReceive(final Context context, Intent intent) { TickleServiceHelper.registerForPush(context, new Callback<Void>() { @Override public void onCallback(Void result) { try { TickleServiceHelper.registerWebConnect(context); } catch (Exception e) { e.printStackTrace(); } } }); }
public void onReceive(Context context, Intent intent) { TickleServiceHelper.registerForPush(context, null); }
public static String translateAgentMessage(Identifier id){ String message = null; String type = WMUtil.getValueOfAttribute(id, "type"); System.out.println(type); Identifier fieldsId = WMUtil.getIdentifierOfAttribute(id, "fields"); if(type == null){ return null; } else if(type.equals("different-attribute-question")){ message = translateDifferentAttributeQuestion(fieldsId); } else if(type.equals("value-question")){ message = translateValueQuestion(fieldsId); } else if(type.equals("common-attribute-question")){ message = translateCommonAttributeQuestion(fieldsId); } else if(type.equals("attribute-presence-question")){ message = translateAttributePresenceQuestion(fieldsId); } else if(type.equals("ask-property-name")){ message = translateCategoryQuestion(fieldsId); } else if(type.equals("category-of-property")){ message = translateCategoryPropertyQuestion(fieldsId); } else if(type.equals("how-to-measure")){ message = String.format("How do I measure %s?", WMUtil.getValueOfAttribute(fieldsId, "property")); } else if(type.equals("ambiguous-category")){ message = translateAmbiguousCategory(fieldsId); } else if(type.equals("describe-object")){ message = translateDescription(fieldsId); } else if(type.equals("dont-know")){ message = "I don't know"; } else if(type.equals("no-prep")){ message = "I don't know that preposition."; } else if(type.equals("single-word-response")){ message = WMUtil.getValueOfAttribute(fieldsId, "word"); } else if(type.equals("no-object")){ message = "I do not see the object you are talking about"; } else if(type.equals("count-response")){ int count = Integer.parseInt(WMUtil.getValueOfAttribute(fieldsId, "count")); message = "There " + (count == 1 ? "is" : "are") + " " + count; } else if(type.equals("unknown-message")){ message = "I was not able to understand your last message"; } else if(type.equals("teaching-request")){ message = translateTeachingRequest(fieldsId); } else if(type.equals("which-question")){ message = translateWhichQuestion(fieldsId); } else if(type.equals("get-next-task")){ message = "Waiting for next command..."; } else if(type.equals("get-next-subaction")){ message = "What action should I take next?"; } else if(type.equals("confirmation")){ message = "Okay."; } else if (type.equals("get-goal")){ message = "What is the goal of the action?"; } else if (type.equals("restart-task-instruction")){ message = "The provided instruction sequence does not lead to the provided goal. Please give the instructions again."; } else if(type.equals("request-index-confirmation")){ message = translateRequestIndexConfirmation(fieldsId); } else if(type.equals("describe-scene")){ message = translateSceneQuestion(fieldsId); } else if(type.equals("describe-scene-objects")){ message = translateSceneObjectsQuestion(fieldsId); } else if(type.equals("list-objects")){ message = translateObjectsQuestion(fieldsId); } else if(type.equals("location-unknown")){ message = "Relative location of object unknown"; } else if(type.equals("play-game")){ message = "Shall we play a game?"; } else if(type.equals("game-start")){ message = "Ok I know that game. Tell me \"your turn\" when it's my turn."; } else if(type.equals("game-new-action2")){ message = "Ok tell me the name of a legal action in this game, or finished."; } else if(type.equals("game-new-action")){ String gameName = WMUtil.getValueOfAttribute(fieldsId, "game-name"); message = "I do not know how to play " + gameName + ". Is it a multiplayer game (true/false)?"; } else if(type.equals("game-new-verb")){ message = "What is the associated verb for this action. (ex: move 2 on 3)"; } else if(type.equals("game-new-goal")){ message = "Ok tell me the name of the goal in the game."; } else if(type.equals("game-new-failure")){ message = "Ok tell me the name of a failure state in the game. (or none)"; } else if(type.equals("game-new-parameter1")){ message = "Ok list a parameter (block/location/either) for this action.\n"; } else if(type.equals("game-new-parameter")){ message = "Ok list a parameter (block/location/either), or finished."; } else if(type.equals("game-new-condition")){ message = "Ok list a condition for this parameter, or finished."; } else if(type.equals("game-learned")){ message = "Ok I have now learned the basics of the game."; } else if(type.equals("game-over")){ message = "Game Over. Shall we play another?"; } return message; }
public static String translateAgentMessage(Identifier id){ String message = null; String type = WMUtil.getValueOfAttribute(id, "type"); System.out.println(type); Identifier fieldsId = WMUtil.getIdentifierOfAttribute(id, "fields"); if(type == null){ return null; } else if(type.equals("different-attribute-question")){ message = translateDifferentAttributeQuestion(fieldsId); } else if(type.equals("value-question")){ message = translateValueQuestion(fieldsId); } else if(type.equals("common-attribute-question")){ message = translateCommonAttributeQuestion(fieldsId); } else if(type.equals("attribute-presence-question")){ message = translateAttributePresenceQuestion(fieldsId); } else if(type.equals("ask-property-name")){ message = translateCategoryQuestion(fieldsId); } else if(type.equals("category-of-property")){ message = translateCategoryPropertyQuestion(fieldsId); } else if(type.equals("how-to-measure")){ message = String.format("How do I measure %s?", WMUtil.getValueOfAttribute(fieldsId, "property")); } else if(type.equals("ambiguous-category")){ message = translateAmbiguousCategory(fieldsId); } else if(type.equals("describe-object")){ message = translateDescription(fieldsId); } else if(type.equals("dont-know")){ message = "I don't know"; } else if(type.equals("no-prep")){ message = "I don't know that preposition."; } else if(type.equals("single-word-response")){ message = WMUtil.getValueOfAttribute(fieldsId, "word"); } else if(type.equals("no-object")){ message = "I do not see the object you are talking about"; } else if(type.equals("count-response")){ int count = Integer.parseInt(WMUtil.getValueOfAttribute(fieldsId, "count")); message = "There " + (count == 1 ? "is" : "are") + " " + count; } else if(type.equals("unknown-message")){ message = "I was not able to understand your last message"; } else if(type.equals("teaching-request")){ message = translateTeachingRequest(fieldsId); } else if(type.equals("which-question")){ message = translateWhichQuestion(fieldsId); } else if(type.equals("get-next-task")){ message = "Waiting for next command..."; } else if(type.equals("get-next-subaction")){ message = "What action should I take next?"; } else if(type.equals("confirmation")){ message = "Okay."; } else if (type.equals("get-goal")){ message = "What is the goal of the action?"; } else if (type.equals("restart-task-instruction")){ message = "The provided instruction sequence does not lead to the provided goal. Please give the instructions again."; } else if(type.equals("request-index-confirmation")){ message = translateRequestIndexConfirmation(fieldsId); } else if(type.equals("describe-scene")){ message = translateSceneQuestion(fieldsId); } else if(type.equals("describe-scene-objects")){ message = translateSceneObjectsQuestion(fieldsId); } else if(type.equals("list-objects")){ message = translateObjectsQuestion(fieldsId); } else if(type.equals("location-unknown")){ message = "Relative location of object unknown"; } else if(type.equals("play-game")){ message = "Shall we play a game?"; } else if(type.equals("game-start")){ message = "Ok I know that game. Tell me \"your turn\" when it's my turn."; } else if(type.equals("game-new-action2")){ message = "Ok tell me the name of a legal action in this game, or finished."; } else if(type.equals("game-new-action")){ String gameName = WMUtil.getValueOfAttribute(fieldsId, "game-name"); message = "I do not know how to play " + gameName + ". This is a multiplayer game (true/false)?"; } else if(type.equals("game-new-verb")){ message = "What is an associated verb for this action, or finished"; } else if(type.equals("game-new-goal")){ message = "Ok tell me the name of the goal in the game."; } else if(type.equals("game-new-failure")){ message = "Ok tell me the name of a failure state in the game. (or none)"; } else if(type.equals("game-new-parameter1")){ message = "Ok describe an object for this action.\n"; } else if(type.equals("game-new-parameter")){ message = "Ok list an object, or finished."; } else if(type.equals("game-new-condition")){ message = "Ok list a condition for this parameter, or finished."; } else if(type.equals("game-learned")){ message = "Ok I have now learned the basics of the game."; } else if(type.equals("game-over")){ message = "Game Over. Shall we play another?"; } return message; }
public void test() throws ClassNotFoundException { String className = "activeweb.mock.MockController"; ControllerClassLoader cl1 = new ControllerClassLoader(ControllerClassLoaderSpec.class.getClassLoader(), "target/test-classes"); ControllerClassLoader cl2 = new ControllerClassLoader(ControllerClassLoaderSpec.class.getClassLoader(), "target/test-classes"); Class clazz1 = cl1.loadClass(className); Class clazz2 = cl2.loadClass(className); a(clazz1 == clazz2).shouldBeFalse(); className = "java.lang.String"; cl1 = new ControllerClassLoader(ControllerClassLoaderSpec.class.getClassLoader(), "target/test-classes"); cl2 = new ControllerClassLoader(ControllerClassLoaderSpec.class.getClassLoader(), "target/test-classes"); clazz1 = cl1.loadClass(className); clazz2 = cl2.loadClass(className); a(clazz1 == clazz2).shouldBeTrue(); }
public void test() throws ClassNotFoundException { String className = "app.controllers.BlahController"; ControllerClassLoader cl1 = new ControllerClassLoader(ControllerClassLoaderSpec.class.getClassLoader(), "target/test-classes"); ControllerClassLoader cl2 = new ControllerClassLoader(ControllerClassLoaderSpec.class.getClassLoader(), "target/test-classes"); Class clazz1 = cl1.loadClass(className); Class clazz2 = cl2.loadClass(className); a(clazz1 == clazz2).shouldBeFalse(); className = "java.lang.String"; cl1 = new ControllerClassLoader(ControllerClassLoaderSpec.class.getClassLoader(), "target/test-classes"); cl2 = new ControllerClassLoader(ControllerClassLoaderSpec.class.getClassLoader(), "target/test-classes"); clazz1 = cl1.loadClass(className); clazz2 = cl2.loadClass(className); a(clazz1 == clazz2).shouldBeTrue(); }
public IResource getEclipseResource() { if (resource != null || hasSearchFailed) return resource; synchronized (this) { if (resource == null) { ComponentResource moduleResource = (ComponentResource) getTarget(); IPath sourcePath = moduleResource.getSourcePath(); IProject container = StructureEdit.getContainingProject(moduleResource.getComponent()); resource = container.findMember(sourcePath); if(resource == null) resource = ResourcesPlugin.getWorkspace().getRoot().findMember(sourcePath); hasSearchFailed = resource == null; } } return resource; }
public IResource getEclipseResource() { if (resource != null || hasSearchFailed) return resource; synchronized (this) { if (resource == null) { ComponentResource moduleResource = (ComponentResource) getTarget(); IPath sourcePath = moduleResource.getSourcePath(); IProject container = StructureEdit.getContainingProject(moduleResource.getComponent()); if (container != null) resource = container.findMember(sourcePath); if(resource == null) resource = ResourcesPlugin.getWorkspace().getRoot().findMember(sourcePath); hasSearchFailed = resource == null; } } return resource; }
private FloatingPointPosition checkAndMaxMove(FloatingPointPosition from, FloatingPointPosition to) { if (!arc) { Vector oldtargetVec = new Vector(target.x() - from.x(), target.y() - from.y()); Vector newtargetVec = new Vector(target.x() - to.x(), target.y() - to.y()); if (oldtargetVec.isOpposite(newtargetVec)) { to = target.toFPP(); } } else { if (movedTetha >= tethaDist) { to = target.toFPP(); } } lastObstacle = null; colliding = false; List<Moveable> possibleCollisions = moveMap.moversAroundPoint(caster2.getPrecisePosition(), caster2.getRadius() + 10, caster2.getMyPoly()); possibleCollisions.remove(caster2); Vector ortho = new Vector(to.getfY() - from.getfY(), from.getfX() - to.getfX()); ortho.normalizeMe(); ortho.multiplyMe(caster2.getRadius()); Vector fromv = from.toVector(); Vector tov = to.toVector(); Polygon poly = new Polygon(); poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y()); poly.addPoint((float) fromv.add(ortho.getInverted()).x(), (float) fromv.add(ortho.getInverted()).y()); poly.addPoint((float) tov.add(ortho.getInverted()).x(), (float) tov.add(ortho.getInverted()).y()); poly.addPoint((float) tov.add(ortho).x(), (float) tov.add(ortho).y()); poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y()); for (Moveable t : possibleCollisions) { float radius = (float) (t.getRadius() + MIN_DISTANCE / 2); Circle c = new Circle((float) t.getPrecisePosition().x(), (float) t.getPrecisePosition().y(), radius); boolean arcCol = collidesOnArc(t, around, radius, from, to); if (!arc && (poly.intersects(c)) || (!arc && poly.includes(c.getCenterX(), c.getCenterY())) || to.getDistance(t.getPrecisePosition()) < caster2.getRadius() + radius || (arc && arcCol)) { System.out.println("COL! with: " + t + " at " + t.getPrecisePosition() + " (dist: " + to.getDistance(t.getPrecisePosition()) + ") on route to " + target + " critical point is " + to); if (!arc) { float distanceToObstacle = (float) (this.caster2.getRadius() + radius + MIN_DISTANCE / 2); Vector dirVec = new Vector(to.getfX() - from.getfX(), to.getfY() - from.getfY()); Vector origin = new Vector(-dirVec.getY(), dirVec.getX()); Edge edge = new Edge(t.getPrecisePosition().toNode(), t.getPrecisePosition().add(origin.toFPP()).toNode()); Edge edge2 = new Edge(caster2.getPrecisePosition().toNode(), caster2.getPrecisePosition().add(dirVec.toFPP()).toNode()); SimplePosition p = edge.endlessIntersection(edge2); if (p == null) { System.out.println("ERROR: " + caster2 + " " + edge + " " + edge2 + " " + t.getPrecisePosition() + " " + origin + " " + dirVec + " " + distanceToObstacle); } double distance = t.getPrecisePosition().getDistance(p.toFPP()); double b = Math.sqrt((distanceToObstacle * distanceToObstacle) - (distance * distance)); FloatingPointPosition nextnewpos = p.toVector().add(dirVec.getInverted().normalize().multiply(b)).toFPP(); if (new Vector(nextnewpos.getfX() - fromv.x(), nextnewpos.getfY() - fromv.y()).isOpposite(dirVec)) { colliding = true; lastObstacle = t; return from; } to = nextnewpos; tov = nextnewpos.toVector(); poly = new Polygon(); poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y()); poly.addPoint((float) fromv.add(ortho.getInverted()).x(), (float) fromv.add(ortho.getInverted()).y()); poly.addPoint((float) tov.add(ortho.getInverted()).x(), (float) tov.add(ortho.getInverted()).y()); poly.addPoint((float) tov.add(ortho).x(), (float) tov.add(ortho).y()); poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y()); } else { Vector obst = t.getPrecisePosition().toVector(); Vector direct = new Vector(around.x() - obst.x(), around.y() - obst.y()); double moveRad = from.toFPP().getDistance(around.toFPP()); Vector z1 = direct.normalize().multiply(caster2.getRadius() + radius); Vector z2 = direct.normalize().multiply(moveRad); Vector mid = direct.normalize().multiply((z1.length() + z2.length()) / 2.0); Vector ortho2 = new Vector(direct.y(), -direct.x()); ortho2 = ortho2.normalize().multiply(Math.sqrt(((caster2.getRadius() + radius) * (caster2.getRadius() + radius)) - (mid.length() * mid.length()))); Vector posMid = new Vector(obst.x() + mid.x(), obst.y() + mid.y()); Vector s1 = posMid.add(ortho2); Vector s2 = posMid.add(ortho2.getInverted()); Vector newPosVec = null; double fromTetha = Math.atan2(around.y() - from.y(), around.x() - from.x()); if (fromTetha < 0) { fromTetha += 2 * Math.PI; } double s1tetha = Math.atan2(around.y() - s1.y(), around.x() - s1.x()); if (s1tetha < 0) { s1tetha += 2 * Math.PI; } double s2tetha = Math.atan2(around.y() - s2.y(), around.x() - s2.x()); if (s2tetha < 0) { s2tetha += 2 * Math.PI; } if (s1tetha < fromTetha) { s1tetha += 2 * Math.PI; } if (s2tetha < fromTetha) { s2tetha += 2 * Math.PI; } if (s1tetha < s2tetha) { if (arcDirection) { newPosVec = s1; } else { newPosVec = s2; } } else { if (arcDirection) { newPosVec = s2; } else { newPosVec = s1; } } to = around.toVector().add(newPosVec).toFPP(); tov = to.toVector(); } colliding = true; lastObstacle = t; if (from.equals(to)) { return from; } } } return to; }
private FloatingPointPosition checkAndMaxMove(FloatingPointPosition from, FloatingPointPosition to) { if (!arc) { Vector oldtargetVec = new Vector(target.x() - from.x(), target.y() - from.y()); Vector newtargetVec = new Vector(target.x() - to.x(), target.y() - to.y()); if (oldtargetVec.isOpposite(newtargetVec)) { to = target.toFPP(); } } else { if (movedTetha >= tethaDist) { to = target.toFPP(); } } lastObstacle = null; colliding = false; List<Moveable> possibleCollisions = moveMap.moversAroundPoint(caster2.getPrecisePosition(), caster2.getRadius() + 10, caster2.getMyPoly()); possibleCollisions.remove(caster2); Vector ortho = new Vector(to.getfY() - from.getfY(), from.getfX() - to.getfX()); ortho.normalizeMe(); ortho.multiplyMe(caster2.getRadius()); Vector fromv = from.toVector(); Vector tov = to.toVector(); Polygon poly = new Polygon(); poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y()); poly.addPoint((float) fromv.add(ortho.getInverted()).x(), (float) fromv.add(ortho.getInverted()).y()); poly.addPoint((float) tov.add(ortho.getInverted()).x(), (float) tov.add(ortho.getInverted()).y()); poly.addPoint((float) tov.add(ortho).x(), (float) tov.add(ortho).y()); poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y()); for (Moveable t : possibleCollisions) { float radius = (float) (t.getRadius() + MIN_DISTANCE / 2); Circle c = new Circle((float) t.getPrecisePosition().x(), (float) t.getPrecisePosition().y(), radius); boolean arcCol = collidesOnArc(t, around, radius, from, to); if (!arc && (poly.intersects(c)) || (!arc && poly.includes(c.getCenterX(), c.getCenterY())) || to.getDistance(t.getPrecisePosition()) < caster2.getRadius() + radius || (arc && arcCol)) { System.out.println("COL! with: " + t + " at " + t.getPrecisePosition() + " (dist: " + to.getDistance(t.getPrecisePosition()) + ") on route to " + target + " critical point is " + to); if (!arc) { float distanceToObstacle = (float) (this.caster2.getRadius() + radius + MIN_DISTANCE / 2); Vector dirVec = new Vector(to.getfX() - from.getfX(), to.getfY() - from.getfY()); Vector origin = new Vector(-dirVec.getY(), dirVec.getX()); Edge edge = new Edge(t.getPrecisePosition().toNode(), t.getPrecisePosition().add(origin.toFPP()).toNode()); Edge edge2 = new Edge(caster2.getPrecisePosition().toNode(), caster2.getPrecisePosition().add(dirVec.toFPP()).toNode()); SimplePosition p = edge.endlessIntersection(edge2); if (p == null) { System.out.println("ERROR: " + caster2 + " " + edge + " " + edge2 + " " + t.getPrecisePosition() + " " + origin + " " + dirVec + " " + distanceToObstacle); } double distance = t.getPrecisePosition().getDistance(p.toFPP()); double b = Math.sqrt((distanceToObstacle * distanceToObstacle) - (distance * distance)); FloatingPointPosition nextnewpos = p.toVector().add(dirVec.getInverted().normalize().multiply(b)).toFPP(); if (new Vector(nextnewpos.getfX() - fromv.x(), nextnewpos.getfY() - fromv.y()).isOpposite(dirVec)) { colliding = true; lastObstacle = t; return from; } to = nextnewpos; tov = nextnewpos.toVector(); poly = new Polygon(); poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y()); poly.addPoint((float) fromv.add(ortho.getInverted()).x(), (float) fromv.add(ortho.getInverted()).y()); poly.addPoint((float) tov.add(ortho.getInverted()).x(), (float) tov.add(ortho.getInverted()).y()); poly.addPoint((float) tov.add(ortho).x(), (float) tov.add(ortho).y()); poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y()); } else { Vector obst = t.getPrecisePosition().toVector(); Vector direct = new Vector(around.x() - obst.x(), around.y() - obst.y()); double moveRad = from.toFPP().getDistance(around.toFPP()); Vector z1 = direct.normalize().multiply(caster2.getRadius() + radius); Vector z2 = direct.normalize().multiply(direct.length() - moveRad); Vector mid = direct.normalize().multiply((z1.length() + z2.length()) / 2.0); Vector ortho2 = new Vector(direct.y(), -direct.x()); ortho2 = ortho2.normalize().multiply(Math.sqrt(((caster2.getRadius() + radius) * (caster2.getRadius() + radius)) - (mid.length() * mid.length()))); Vector posMid = new Vector(obst.x() + mid.x(), obst.y() + mid.y()); Vector s1 = posMid.add(ortho2); Vector s2 = posMid.add(ortho2.getInverted()); Vector newPosVec = null; double fromTetha = Math.atan2(around.y() - from.y(), around.x() - from.x()); if (fromTetha < 0) { fromTetha += 2 * Math.PI; } double s1tetha = Math.atan2(around.y() - s1.y(), around.x() - s1.x()); if (s1tetha < 0) { s1tetha += 2 * Math.PI; } double s2tetha = Math.atan2(around.y() - s2.y(), around.x() - s2.x()); if (s2tetha < 0) { s2tetha += 2 * Math.PI; } if (s1tetha < fromTetha) { s1tetha += 2 * Math.PI; } if (s2tetha < fromTetha) { s2tetha += 2 * Math.PI; } if (s1tetha < s2tetha) { if (arcDirection) { newPosVec = s1; } else { newPosVec = s2; } } else { if (arcDirection) { newPosVec = s2; } else { newPosVec = s1; } } to = around.toVector().add(newPosVec).toFPP(); tov = to.toVector(); } colliding = true; lastObstacle = t; if (from.equals(to)) { return from; } } } return to; }
protected void initializeJSFView(FacesContext context){ IWApplicationContext iwac = IWMainApplication.getIWMainApplication(context).getIWApplicationContext(); Layer div = new Layer(); div.setWidth("100%"); div.setHeight("800"); BuilderService builderService = null; try{ builderService = BuilderServiceFactory.getBuilderService(iwac); }catch (Exception e) { e.printStackTrace(); return; } String pathToSigner = null; IWContext iwc = IWContext.getIWContext(context); if(view.isSubmitable()){ String serverURL = iwc.getServerURL(); serverURL = (serverURL.endsWith("/")) ? serverURL.substring(0, serverURL.length() - 1) : serverURL; String pathToDocument = serverURL + CoreConstants.WEBDAV_SERVLET_URI + CoreConstants.SLASH + IWMainApplication.getDefaultIWMainApplication().getSettings() .getProperty(AscertiaConstants.APP_PROP_PATH_TO_DOCUMENT_TO_SIGN,"/rulling/"); Locale currentLocale = IWContext.getIWContext(context).getCurrentLocale(); pathToDocument += IWMainApplication.getDefaultIWMainApplication().getSettings() .getProperty(AscertiaConstants.APP_PROP_DOCUMENT_NAME,"rulling_aggrement"); pathToDocument += "_" + currentLocale.getLanguage() + ".pdf"; pathToSigner = builderService.getUriToObject(AscertiaBPMSigner.class, Arrays.asList(new AdvancedProperty[] { new AdvancedProperty( AscertiaConstants.UNSIGNED_DOCUMENT_URL, pathToDocument), new AdvancedProperty( AscertiaConstants.PARAM_TASK_ID, String.valueOf(view.getTaskInstanceId()))})); IFrame frame = new IFrame(SINGNING_FRAME, pathToSigner); frame.setWidth("100%"); frame.setHeight("100%"); div.add(frame); }else{ TaskInstanceW taskInstanceW = getBpmFactory().getProcessManagerByTaskInstanceId(view.getTaskInstanceId()).getTaskInstance(view.getTaskInstanceId()); BinaryVariable signedDocument = taskInstanceW.getAttachement(AscertiaConstants.SIGNED_VARIABLE_NAME); VariablesHandler variablesHandler = getVariablesHandler(); InputStream inputStream = variablesHandler.getBinaryVariablesHandler().getBinaryVariableContent(signedDocument); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte buffer[] = new byte[1024]; int noRead = 0; try { noRead = inputStream.read(buffer, 0, 1024); while (noRead != -1) { baos.write(buffer, 0, noRead); noRead = inputStream.read(buffer, 0, 1024); } } catch (IOException e) { inputStream = null; return; } AscertiaData data = new AscertiaData(); data.setDocumentName(signedDocument.getFileName()); data.setByteDocument(baos.toByteArray()); iwc.getSession().setAttribute(AscertiaConstants.PARAM_ASCERTIA_DATA, data); IFrame frame = new IFrame("signedDocument", iwc.getIWMainApplication().getMediaServletURI() + "?" + MediaWritable.PRM_WRITABLE_CLASS + "="+ IWMainApplication.getEncryptedClassName(AscertiaPDFPrinter.class)); frame.setWidth("100%"); frame.setHeight("100%"); div.add(frame); } add(div); }
protected void initializeJSFView(FacesContext context){ IWApplicationContext iwac = IWMainApplication.getIWMainApplication(context).getIWApplicationContext(); Layer div = new Layer(); div.setWidth("100%"); div.setHeight("800"); BuilderService builderService = null; try{ builderService = BuilderServiceFactory.getBuilderService(iwac); }catch (Exception e) { e.printStackTrace(); return; } String pathToSigner = null; IWContext iwc = IWContext.getIWContext(context); if(view.isSubmitable()){ String serverURL = iwc.getServerURL(); serverURL = (serverURL.endsWith("/")) ? serverURL.substring(0, serverURL.length() - 1) : serverURL; String pathToDocument = serverURL + CoreConstants.WEBDAV_SERVLET_URI + CoreConstants.SLASH + IWMainApplication.getDefaultIWMainApplication().getSettings() .getProperty(AscertiaConstants.APP_PROP_PATH_TO_DOCUMENT_TO_SIGN,"/rulling/"); Locale currentLocale = IWContext.getIWContext(context).getCurrentLocale(); pathToDocument += IWMainApplication.getDefaultIWMainApplication().getSettings() .getProperty(AscertiaConstants.APP_PROP_DOCUMENT_NAME,"rulling_aggrement"); pathToDocument += "_" + currentLocale.getLanguage() + ".pdf"; pathToSigner = builderService.getUriToObject(AscertiaBPMSigner.class, Arrays.asList(new AdvancedProperty[] { new AdvancedProperty( AscertiaConstants.UNSIGNED_DOCUMENT_URL, pathToDocument), new AdvancedProperty( AscertiaConstants.PARAM_TASK_ID, String.valueOf(view.getTaskInstanceId()))})); IFrame frame = new IFrame(SINGNING_FRAME, pathToSigner); frame.setWidth("100%"); frame.setHeight("100%"); div.add(frame); }else{ TaskInstanceW taskInstanceW = getBpmFactory().getProcessManagerByTaskInstanceId(view.getTaskInstanceId()).getTaskInstance(view.getTaskInstanceId()); BinaryVariable signedDocument = taskInstanceW.getAttachment(AscertiaConstants.SIGNED_VARIABLE_NAME); VariablesHandler variablesHandler = getVariablesHandler(); InputStream inputStream = variablesHandler.getBinaryVariablesHandler().getBinaryVariableContent(signedDocument); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte buffer[] = new byte[1024]; int noRead = 0; try { noRead = inputStream.read(buffer, 0, 1024); while (noRead != -1) { baos.write(buffer, 0, noRead); noRead = inputStream.read(buffer, 0, 1024); } } catch (IOException e) { inputStream = null; return; } AscertiaData data = new AscertiaData(); data.setDocumentName(signedDocument.getFileName()); data.setByteDocument(baos.toByteArray()); iwc.getSession().setAttribute(AscertiaConstants.PARAM_ASCERTIA_DATA, data); IFrame frame = new IFrame("signedDocument", iwc.getIWMainApplication().getMediaServletURI() + "?" + MediaWritable.PRM_WRITABLE_CLASS + "="+ IWMainApplication.getEncryptedClassName(AscertiaPDFPrinter.class)); frame.setWidth("100%"); frame.setHeight("100%"); div.add(frame); } add(div); }
public static void init() { System.out.println(Runtime.getRuntime().availableProcessors() + " available cores detected"); try { Settings.init(); } catch (IOException e) { e.printStackTrace(); } map = Map.load("example_1"); player = new Player(); actors = new ActorSet(); actors.addAll(map.actors); player.respawn(actors, map.getSpawnPosition()); renderer = new graphics.Renderer(player.getCamera()); input = new KeyboardListener(); graphics.Model.loadModels(); sound.Manager.initialize(player.getCamera()); game = new GameThread(actors); game.addCallback(input); game.addCallback(new Updateable() { public void update() { player.updateCamera(); } }); game.addCallback(new Updateable() { public void update() { sound.Manager.processEvents(); } }); }
public static void init() { System.out.println(Runtime.getRuntime().availableProcessors() + " available cores detected"); try { Settings.init(); } catch (IOException e) { e.printStackTrace(); } map = Map.load("example_1"); player = new Player(); actors = new ActorSet(); actors.addAll(map.actors); player.respawn(actors, map.getSpawnPosition()); renderer = new graphics.Renderer(player.getCamera()); input = new KeyboardListener(); graphics.Model.loadModels(); sound.Manager.initialize(player.getShip()); game = new GameThread(actors); game.addCallback(input); game.addCallback(new Updateable() { public void update() { player.updateCamera(); } }); game.addCallback(new Updateable() { public void update() { sound.Manager.processEvents(); } }); }
public void addTaskResult(String taskName, TaskResult taskResult, boolean isPrecious) { if (allResults == null) { allResults = new HashMap<String, TaskResult>(); } allResults.put(taskName, taskResult); if (isPrecious) { if (preciousResults == null) { preciousResults = new HashMap<String, TaskResult>(); } allResults.put(taskName, taskResult); } if (!PAFuture.isAwaited(taskResult) && taskResult.hadException()) { if (exceptionResults == null) { exceptionResults = new HashMap<String, TaskResult>(); } exceptionResults.put(taskName, taskResult); } }
public void addTaskResult(String taskName, TaskResult taskResult, boolean isPrecious) { if (allResults == null) { allResults = new HashMap<String, TaskResult>(); } allResults.put(taskName, taskResult); if (isPrecious) { if (preciousResults == null) { preciousResults = new HashMap<String, TaskResult>(); } preciousResults.put(taskName, taskResult); } if (!PAFuture.isAwaited(taskResult) && taskResult.hadException()) { if (exceptionResults == null) { exceptionResults = new HashMap<String, TaskResult>(); } exceptionResults.put(taskName, taskResult); } }
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException { readResolve(); List<String[]> targetsToRun = getTargetsToRun(); if (targetsToRun.size() > 0) { String execName; if (useWrapper) { FilePath wrapper = new FilePath(build.getModuleRoot(), launcher.isUnix() ? "grailsw" : "grailsw.bat"); execName = wrapper.getRemote(); } else { execName = launcher.isUnix() ? "grails" : "grails.bat"; } EnvVars env = build.getEnvironment(listener); GrailsInstallation grailsInstallation = getGrails(); if (grailsInstallation != null) { grailsInstallation = grailsInstallation.forEnvironment(env) .forNode(Computer.currentComputer().getNode(), listener); env.put("GRAILS_HOME", grailsInstallation.getHome()); } for (String[] targetsAndArgs : targetsToRun) { String target = targetsAndArgs[0]; ArgumentListBuilder args = new ArgumentListBuilder(); if (grailsInstallation == null) { args.add(execName); } else { File exec = grailsInstallation.getExecutable(); if (!new FilePath(launcher.getChannel(), grailsInstallation.getExecutable().getPath()).exists()) { listener.fatalError(exec + " doesn't exist"); return false; } args.add(exec.getPath()); } args.addKeyValuePairs("-D", build.getBuildVariables()); Map sytemProperties = new HashMap(); if (grailsWorkDir != null && !"".equals(grailsWorkDir.trim())) { sytemProperties.put("grails.work.dir", grailsWorkDir.trim()); } if (projectWorkDir != null && !"".equals(projectWorkDir.trim())) { sytemProperties.put("grails.project.work.dir", projectWorkDir.trim()); } if (serverPort != null && !"".equals(serverPort.trim())) { sytemProperties.put("server.port", serverPort.trim()); } if (sytemProperties.size() > 0) { args.addKeyValuePairs("-D", sytemProperties); } args.addKeyValuePairsFromPropertyString("-D", properties, build.getBuildVariableResolver()); args.add(target); boolean foundNonInteractive = false; for (int i = 1; i < targetsAndArgs.length; i++) { String arg = evalTarget(env, targetsAndArgs[i]); if("--non-interactive".equals(arg)) { foundNonInteractive = true; } args.add(arg); } if(nonInteractive != null && nonInteractive && !foundNonInteractive) { args.add("--non-interactive"); } if (!launcher.isUnix()) { args.prepend("cmd.exe", "/C"); args.add("&&", "exit", "%%ERRORLEVEL%%"); } try { final FilePath basePath; FilePath moduleRoot = build.getModuleRoot(); if (projectBaseDir != null && !"".equals(projectBaseDir.trim())) { basePath = new FilePath(moduleRoot, projectBaseDir); } else { basePath = moduleRoot; } int r = launcher.launch().cmds(args).envs(env).stdout(listener).pwd(basePath).join(); if (r != 0) return false; } catch (IOException e) { Util.displayIOException(e, listener); e.printStackTrace(listener.fatalError("command execution failed")); return false; } } } else { listener.getLogger().println("Error: No Targets To Run!"); return false; } return true; }
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException { readResolve(); List<String[]> targetsToRun = getTargetsToRun(); if (targetsToRun.size() > 0) { String execName; if (useWrapper) { FilePath wrapper = new FilePath(build.getModuleRoot(), launcher.isUnix() ? "grailsw" : "grailsw.bat"); execName = wrapper.getRemote(); } else { execName = launcher.isUnix() ? "grails" : "grails.bat"; } EnvVars env = build.getEnvironment(listener); GrailsInstallation grailsInstallation = useWrapper ? null : getGrails(); if (grailsInstallation != null) { grailsInstallation = grailsInstallation.forEnvironment(env) .forNode(Computer.currentComputer().getNode(), listener); env.put("GRAILS_HOME", grailsInstallation.getHome()); } for (String[] targetsAndArgs : targetsToRun) { String target = targetsAndArgs[0]; ArgumentListBuilder args = new ArgumentListBuilder(); if (grailsInstallation == null) { args.add(execName); } else { File exec = grailsInstallation.getExecutable(); if (!new FilePath(launcher.getChannel(), grailsInstallation.getExecutable().getPath()).exists()) { listener.fatalError(exec + " doesn't exist"); return false; } args.add(exec.getPath()); } args.addKeyValuePairs("-D", build.getBuildVariables()); Map sytemProperties = new HashMap(); if (grailsWorkDir != null && !"".equals(grailsWorkDir.trim())) { sytemProperties.put("grails.work.dir", grailsWorkDir.trim()); } if (projectWorkDir != null && !"".equals(projectWorkDir.trim())) { sytemProperties.put("grails.project.work.dir", projectWorkDir.trim()); } if (serverPort != null && !"".equals(serverPort.trim())) { sytemProperties.put("server.port", serverPort.trim()); } if (sytemProperties.size() > 0) { args.addKeyValuePairs("-D", sytemProperties); } args.addKeyValuePairsFromPropertyString("-D", properties, build.getBuildVariableResolver()); args.add(target); boolean foundNonInteractive = false; for (int i = 1; i < targetsAndArgs.length; i++) { String arg = evalTarget(env, targetsAndArgs[i]); if("--non-interactive".equals(arg)) { foundNonInteractive = true; } args.add(arg); } if(nonInteractive != null && nonInteractive && !foundNonInteractive) { args.add("--non-interactive"); } if (!launcher.isUnix()) { args.prepend("cmd.exe", "/C"); args.add("&&", "exit", "%%ERRORLEVEL%%"); } try { final FilePath basePath; FilePath moduleRoot = build.getModuleRoot(); if (projectBaseDir != null && !"".equals(projectBaseDir.trim())) { basePath = new FilePath(moduleRoot, projectBaseDir); } else { basePath = moduleRoot; } int r = launcher.launch().cmds(args).envs(env).stdout(listener).pwd(basePath).join(); if (r != 0) return false; } catch (IOException e) { Util.displayIOException(e, listener); e.printStackTrace(listener.fatalError("command execution failed")); return false; } } } else { listener.getLogger().println("Error: No Targets To Run!"); return false; } return true; }
public void afterThrowing(Method method, Object[] args, Exception throwable) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); throwable.printStackTrace(pw); pw.close(); LOG.error(throwable.getMessage() + "\n" + sw.toString()); String message = "Error calling jBilling API. Method: " + method.getName(); throw new SessionInternalError(message, throwable); }
public void afterThrowing(Method method, Object[] args, Object target, Exception throwable) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); throwable.printStackTrace(pw); pw.close(); LOG.debug(throwable.getMessage() + "\n" + sw.toString()); String message = "Error calling jBilling API. Method: " + method.getName(); throw new SessionInternalError(message, throwable); }
public CreditDetailsPage() { super(); String reqId = String.valueOf(RequestCycle.get().getRequest().getQueryParameters().getParameterValue("requestId")); final Integer requestId = PuzzlesUtils.parseInt(reqId); if (requestId != null) { request = DatabaseConnector.getInstance().getCreditRequestById(Integer.valueOf(reqId)); if (request.getConsultantId() != getUserId()) { setResponsePage(DashboardPage.class); } else { final CompoundPropertyModel<CreditRequest> model = new CompoundPropertyModel<CreditRequest>(request); add(new TextField<String>("name", model.<String>bind("customer.lastname"))); add(new TextField<String>("firstname", model.<String>bind("customer.firstname"))); add(new TextField<String>("state", model.<String>bind("state"))); add(new TextField<String>("interest", model.<String>bind("repaymentPlan.interest"))); add(new TextField<String>("amount", model.<String>bind("repaymentPlan.amount"))); add(new TextField<String>("duration", model.<String>bind("repaymentPlan.duration"))); add(new TextField<String>("rate", model.<String>bind("repaymentPlan.rate"))); WebMarkupContainer buttonContainer = new WebMarkupContainer("buttonContainer") { @Override public boolean isVisible() { return model.getObject().getState() == CreditState.PENDING; } }; Button acceptButton = new Button("acceptButton"); acceptButton.add(new AjaxEventBehavior("onclick") { @Override protected void onEvent(AjaxRequestTarget target) { DatabaseConnector.getInstance().changeRequestState(requestId, CreditState.ACCEPTED); setResponsePage(DashboardPage.class); } }); buttonContainer.add(acceptButton); Button declineButton = new Button("declineButton"); declineButton.add(new AjaxEventBehavior("onclick") { @Override protected void onEvent(AjaxRequestTarget target) { DatabaseConnector.getInstance().changeRequestState(requestId, CreditState.REJECTED); setResponsePage(DashboardPage.class); } }); buttonContainer.add(declineButton); add(buttonContainer); add(new ListView<Transaction>("earnings", new AbstractReadOnlyModel<List<? extends Transaction>>() { @Override public List<? extends Transaction> getObject() { List<Transaction> list = new ArrayList<Transaction>(); for (Transaction t : model.getObject().getTransactions()) { if (t.getValue() > 0.0) { list.add(t); } } return list; } }) { @Override protected void populateItem(final ListItem<Transaction> item) { item.add(new Label("earningDescription", new AbstractReadOnlyModel<String>() { @Override public String getObject() { String s = item.getModelObject().getDescription(); if (item.getModelObject().getDescription1() != null && item.getModelObject().getDescription1().length() > 0) { s+=", "+ item.getModelObject().getDescription1(); } if (item.getModelObject().getDescription2() != null && item.getModelObject().getDescription2().length() > 0) { s+=", "+ item.getModelObject().getDescription2(); } return s; } })); TextField<Double> value = new TextField<Double>("earningValue", new AbstractReadOnlyModel<Double>() { @Override public Double getObject() { return item.getModelObject().getValue(); } }); value.setEnabled(false); item.add(value); } }); final TextField<Double> resultField = new TextField<Double>("earningsTotal", new AbstractReadOnlyModel<Double>() { @Override public Double getObject() { Double d = 0.0; for (Transaction t : model.getObject().getTransactions()) { if (t.getValue() > 0.0) { d += t.getValue(); } } return d; } }); resultField.setEnabled(false); add(resultField); final TextField<Double> resultSpendings = new TextField<Double>("spendingsTotal", new AbstractReadOnlyModel<Double>() { @Override public Double getObject() { Double d = 0.0; for (Transaction t : model.getObject().getTransactions()) { if (t.getValue() < 0.0) { d += t.getValue(); } } return Math.abs(d); } }); resultSpendings.setEnabled(false); add(resultSpendings); add(new ListView<Transaction>("spendings", new AbstractReadOnlyModel<List<? extends Transaction>>() { @Override public List<? extends Transaction> getObject() { List<Transaction> list = new ArrayList<Transaction>(); for (Transaction t : model.getObject().getTransactions()) { if (t.getValue() < 0.0) { list.add(t); } } return list; } }) { @Override protected void populateItem(final ListItem<Transaction> item) { item.add(new Label("spendingDescription", new AbstractReadOnlyModel<String>() { @Override public String getObject() { String s = item.getModelObject().getDescription(); if (item.getModelObject().getDescription1() != null && item.getModelObject().getDescription1().length() > 0) { s+=", "+ item.getModelObject().getDescription1(); } if (item.getModelObject().getDescription2() != null && item.getModelObject().getDescription2().length() > 0) { s+=", "+ item.getModelObject().getDescription2(); } return s; } })); TextField<Double> value = new TextField<Double>("spendingValue", new AbstractReadOnlyModel<Double>() { @Override public Double getObject() { return item.getModelObject().getValue(); } }); value.setEnabled(false); item.add(value); } }); add(new Label("incomeTotal", resultField.getModel())); add(new Label("spendingTotal", resultSpendings.getModel())); add(new Label("rateTotal", model.<String>bind("repaymentPlan.rate"))); add(new Label("total", new AbstractReadOnlyModel<Double>() { @Override public Double getObject() { return resultField.getModelObject() - resultSpendings.getModelObject() - request.getRepaymentPlan().getRate(); } })); add(new RepaymentPlanPanel("repaymentPlan", new AbstractReadOnlyModel<List<RepaymentPlan.Entry>>() { @Override public List<RepaymentPlan.Entry> getObject() { return model.getObject().getRepaymentPlan().generateRepaymentPlan(); } })); } } else { setResponsePage(DashboardPage.class); } }
public CreditDetailsPage() { super(); String reqId = String.valueOf(RequestCycle.get().getRequest().getQueryParameters().getParameterValue("requestId")); final Integer requestId = PuzzlesUtils.parseInt(reqId); if (requestId != null) { request = DatabaseConnector.getInstance().getCreditRequestById(Integer.valueOf(reqId)); if (request.getConsultantId() != getUserId()) { setResponsePage(DashboardPage.class); } else { final CompoundPropertyModel<CreditRequest> model = new CompoundPropertyModel<CreditRequest>(request); add(new TextField<String>("state", model.<String>bind("state"))); add(new TextField<String>("interest", model.<String>bind("repaymentPlan.interest"))); add(new TextField<String>("amount", model.<String>bind("repaymentPlan.amount"))); add(new TextField<String>("duration", model.<String>bind("repaymentPlan.duration"))); add(new TextField<String>("rate", model.<String>bind("repaymentPlan.rate"))); WebMarkupContainer buttonContainer = new WebMarkupContainer("buttonContainer") { @Override public boolean isVisible() { return model.getObject().getState() == CreditState.PENDING; } }; Button acceptButton = new Button("acceptButton"); acceptButton.add(new AjaxEventBehavior("onclick") { @Override protected void onEvent(AjaxRequestTarget target) { DatabaseConnector.getInstance().changeRequestState(requestId, CreditState.ACCEPTED); setResponsePage(DashboardPage.class); } }); buttonContainer.add(acceptButton); Button declineButton = new Button("declineButton"); declineButton.add(new AjaxEventBehavior("onclick") { @Override protected void onEvent(AjaxRequestTarget target) { DatabaseConnector.getInstance().changeRequestState(requestId, CreditState.REJECTED); setResponsePage(DashboardPage.class); } }); buttonContainer.add(declineButton); add(buttonContainer); add(new ListView<Transaction>("earnings", new AbstractReadOnlyModel<List<? extends Transaction>>() { @Override public List<? extends Transaction> getObject() { List<Transaction> list = new ArrayList<Transaction>(); for (Transaction t : model.getObject().getTransactions()) { if (t.getValue() > 0.0) { list.add(t); } } return list; } }) { @Override protected void populateItem(final ListItem<Transaction> item) { item.add(new Label("earningDescription", new AbstractReadOnlyModel<String>() { @Override public String getObject() { String s = item.getModelObject().getDescription(); if (item.getModelObject().getDescription1() != null && item.getModelObject().getDescription1().length() > 0) { s+=", "+ item.getModelObject().getDescription1(); } if (item.getModelObject().getDescription2() != null && item.getModelObject().getDescription2().length() > 0) { s+=", "+ item.getModelObject().getDescription2(); } return s; } })); TextField<Double> value = new TextField<Double>("earningValue", new AbstractReadOnlyModel<Double>() { @Override public Double getObject() { return item.getModelObject().getValue(); } }); value.setEnabled(false); item.add(value); } }); final TextField<Double> resultField = new TextField<Double>("earningsTotal", new AbstractReadOnlyModel<Double>() { @Override public Double getObject() { Double d = 0.0; for (Transaction t : model.getObject().getTransactions()) { if (t.getValue() > 0.0) { d += t.getValue(); } } return d; } }); resultField.setEnabled(false); add(resultField); final TextField<Double> resultSpendings = new TextField<Double>("spendingsTotal", new AbstractReadOnlyModel<Double>() { @Override public Double getObject() { Double d = 0.0; for (Transaction t : model.getObject().getTransactions()) { if (t.getValue() < 0.0) { d += t.getValue(); } } return Math.abs(d); } }); resultSpendings.setEnabled(false); add(resultSpendings); add(new ListView<Transaction>("spendings", new AbstractReadOnlyModel<List<? extends Transaction>>() { @Override public List<? extends Transaction> getObject() { List<Transaction> list = new ArrayList<Transaction>(); for (Transaction t : model.getObject().getTransactions()) { if (t.getValue() < 0.0) { list.add(t); } } return list; } }) { @Override protected void populateItem(final ListItem<Transaction> item) { item.add(new Label("spendingDescription", new AbstractReadOnlyModel<String>() { @Override public String getObject() { String s = item.getModelObject().getDescription(); if (item.getModelObject().getDescription1() != null && item.getModelObject().getDescription1().length() > 0) { s+=", "+ item.getModelObject().getDescription1(); } if (item.getModelObject().getDescription2() != null && item.getModelObject().getDescription2().length() > 0) { s+=", "+ item.getModelObject().getDescription2(); } return s; } })); TextField<Double> value = new TextField<Double>("spendingValue", new AbstractReadOnlyModel<Double>() { @Override public Double getObject() { return item.getModelObject().getValue(); } }); value.setEnabled(false); item.add(value); } }); add(new Label("incomeTotal", resultField.getModel())); add(new Label("spendingTotal", resultSpendings.getModel())); add(new Label("rateTotal", model.<String>bind("repaymentPlan.rate"))); add(new Label("total", new AbstractReadOnlyModel<Double>() { @Override public Double getObject() { return resultField.getModelObject() - resultSpendings.getModelObject() - request.getRepaymentPlan().getRate(); } })); add(new RepaymentPlanPanel("repaymentPlan", new AbstractReadOnlyModel<List<RepaymentPlan.Entry>>() { @Override public List<RepaymentPlan.Entry> getObject() { return model.getObject().getRepaymentPlan().generateRepaymentPlan(); } })); } } else { setResponsePage(DashboardPage.class); } }
public static void main(String[] args) { try { Class.forName("csql.jdbc.JdbcSqlDriver"); Connection con = DriverManager.getConnection("jdbc:csql", "root", "manager"); Statement cStmt = con.createStatement(); int ret =0; cStmt.execute("CREATE TABLE T1 (f1 integer, f2 char (20));"); PreparedStatement stmt = null; stmt = con.prepareStatement("INSERT INTO T1 VALUES (?, ?);"); int count=0; for (int i =0 ; i< 10 ; i++) { stmt.setInt(1, i); stmt.setString(2, String.valueOf(i+100)); ret = stmt.executeUpdate(); if (ret !=1) break; count++; } con.close(); System.out.println("Total tuples inserted "+ count); con = DriverManager.getConnection("jdbc:csql", "root", "manager"); cStmt = con.createStatement(); System.out.println("Listing tuples:"); ResultSet rs = cStmt.executeQuery("SELECT * from T1;"); count =0; while (rs.next()) { System.out.println("Tuple value is " + rs.getInt(1)+ " "+ rs.getString(2)); count++; } System.out.println("Total tuples selected "+ count); rs.close(); con.commit(); cStmt.execute("DROP TABLE T1;"); con.close(); }catch(Exception e) { System.out.println("Exception in Test: "+e); e.getStackTrace(); } }
public static void main(String[] args) { try { Class.forName("csql.jdbc.JdbcSqlDriver"); Connection con = DriverManager.getConnection("jdbc:csql", "root", "manager"); con.setAutoCommit( false ); Statement cStmt = con.createStatement(); int ret =0; cStmt.execute("CREATE TABLE T1 (f1 integer, f2 char (20));"); PreparedStatement stmt = null; stmt = con.prepareStatement("INSERT INTO T1 VALUES (?, ?);"); int count=0; for (int i =0 ; i< 10 ; i++) { stmt.setInt(1, i); stmt.setString(2, String.valueOf(i+100)); ret = stmt.executeUpdate(); if (ret !=1) break; count++; } con.close(); System.out.println("Total tuples inserted "+ count); con = DriverManager.getConnection("jdbc:csql", "root", "manager"); cStmt = con.createStatement(); System.out.println("Listing tuples:"); ResultSet rs = cStmt.executeQuery("SELECT * from T1;"); count =0; while (rs.next()) { System.out.println("Tuple value is " + rs.getInt(1)+ " "+ rs.getString(2)); count++; } System.out.println("Total tuples selected "+ count); rs.close(); con.commit(); cStmt.execute("DROP TABLE T1;"); con.close(); }catch(Exception e) { System.out.println("Exception in Test: "+e); e.getStackTrace(); } }